author | jjg |
Wed, 05 Nov 2014 19:48:42 -0800 | |
changeset 27389 | 301be76491af |
parent 27385 | fb4a5f118316 |
child 27547 | d07b3dcbc707 |
permissions | -rw-r--r-- |
26100 | 1 |
/* |
2 |
* Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved. |
|
3 |
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. |
|
4 |
* |
|
5 |
* This code is free software; you can redistribute it and/or modify it |
|
6 |
* under the terms of the GNU General Public License version 2 only, as |
|
7 |
* published by the Free Software Foundation. |
|
8 |
* |
|
9 |
* This code is distributed in the hope that it will be useful, but WITHOUT |
|
10 |
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
|
11 |
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
|
12 |
* version 2 for more details (a copy is included in the LICENSE file that |
|
13 |
* accompanied this code). |
|
14 |
* |
|
15 |
* You should have received a copy of the GNU General Public License version |
|
16 |
* 2 along with this work; if not, write to the Free Software Foundation, |
|
17 |
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. |
|
18 |
* |
|
19 |
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA |
|
20 |
* or visit www.oracle.com if you need additional information or have any |
|
21 |
* questions. |
|
22 |
*/ |
|
23 |
||
24 |
import java.io.BufferedReader; |
|
25 |
import java.io.BufferedWriter; |
|
26 |
import java.io.ByteArrayInputStream; |
|
27 |
import java.io.ByteArrayOutputStream; |
|
28 |
import java.io.File; |
|
29 |
import java.io.FilterOutputStream; |
|
30 |
import java.io.FilterWriter; |
|
31 |
import java.io.IOException; |
|
32 |
import java.io.InputStream; |
|
33 |
import java.io.InputStreamReader; |
|
34 |
import java.io.OutputStream; |
|
35 |
import java.io.PrintStream; |
|
36 |
import java.io.PrintWriter; |
|
37 |
import java.io.StringWriter; |
|
38 |
import java.io.Writer; |
|
39 |
import java.net.URI; |
|
40 |
import java.nio.charset.Charset; |
|
41 |
import java.nio.file.FileVisitResult; |
|
42 |
import java.nio.file.Files; |
|
43 |
import java.nio.file.Path; |
|
44 |
import java.nio.file.Paths; |
|
45 |
import java.nio.file.SimpleFileVisitor; |
|
46 |
import java.nio.file.StandardCopyOption; |
|
47 |
import java.nio.file.attribute.BasicFileAttributes; |
|
48 |
import java.util.ArrayList; |
|
49 |
import java.util.Arrays; |
|
50 |
import java.util.Collections; |
|
51 |
import java.util.EnumMap; |
|
52 |
import java.util.HashMap; |
|
53 |
import java.util.List; |
|
54 |
import java.util.ListIterator; |
|
55 |
import java.util.Locale; |
|
56 |
import java.util.Map; |
|
57 |
import java.util.Objects; |
|
58 |
import java.util.jar.Attributes; |
|
59 |
import java.util.jar.JarEntry; |
|
60 |
import java.util.jar.JarOutputStream; |
|
61 |
import java.util.jar.Manifest; |
|
62 |
import java.util.regex.Matcher; |
|
63 |
import java.util.regex.Pattern; |
|
64 |
import java.util.stream.Collectors; |
|
65 |
import java.util.stream.Stream; |
|
66 |
import java.util.stream.StreamSupport; |
|
67 |
import javax.tools.FileObject; |
|
68 |
import javax.tools.ForwardingJavaFileManager; |
|
69 |
import javax.tools.JavaCompiler; |
|
70 |
import javax.tools.JavaFileManager; |
|
71 |
import javax.tools.JavaFileObject; |
|
72 |
import javax.tools.SimpleJavaFileObject; |
|
73 |
import javax.tools.StandardJavaFileManager; |
|
74 |
import javax.tools.StandardLocation; |
|
75 |
||
76 |
import com.sun.tools.javac.api.JavacTaskImpl; |
|
77 |
import com.sun.tools.javac.api.JavacTool; |
|
78 |
import java.io.IOError; |
|
79 |
||
80 |
/** |
|
81 |
* Utility methods and classes for writing jtreg tests for |
|
82 |
* javac, javah, javap, and sjavac. (For javadoc support, |
|
83 |
* see JavadocTester.) |
|
84 |
* |
|
85 |
* <p>There is support for common file operations similar to |
|
86 |
* shell commands like cat, cp, diff, mv, rm, grep. |
|
87 |
* |
|
88 |
* <p>There is also support for invoking various tools, like |
|
89 |
* javac, javah, javap, jar, java and other JDK tools. |
|
90 |
* |
|
91 |
* <p><em>File separators</em>: for convenience, many operations accept strings |
|
92 |
* to represent filenames. On all platforms on which JDK is supported, |
|
93 |
* "/" is a legal filename component separator. In particular, even |
|
94 |
* on Windows, where the official file separator is "\", "/" is a legal |
|
95 |
* alternative. It is therefore recommended that any client code using |
|
96 |
* strings to specify filenames should use "/". |
|
97 |
* |
|
98 |
* @author Vicente Romero (original) |
|
99 |
* @author Jonathan Gibbons (revised) |
|
100 |
*/ |
|
101 |
public class ToolBox { |
|
102 |
/** The platform line separator. */ |
|
103 |
public static final String lineSeparator = System.getProperty("line.separator"); |
|
104 |
/** The platform OS name. */ |
|
105 |
public static final String osName = System.getProperty("os.name"); |
|
106 |
||
107 |
/** The location of the class files for this test, or null if not set. */ |
|
108 |
public static final String testClasses = System.getProperty("test.classes"); |
|
109 |
/** The location of the source files for this test, or null if not set. */ |
|
110 |
public static final String testSrc = System.getProperty("test.src"); |
|
111 |
/** The location of the test JDK for this test, or null if not set. */ |
|
112 |
public static final String testJDK = System.getProperty("test.jdk"); |
|
113 |
||
114 |
/** The current directory. */ |
|
115 |
public static final Path currDir = Paths.get("."); |
|
116 |
||
117 |
/** The stream used for logging output. */ |
|
118 |
public PrintStream out = System.err; |
|
119 |
||
120 |
JavaCompiler compiler; |
|
121 |
StandardJavaFileManager standardJavaFileManager; |
|
122 |
||
123 |
/** |
|
124 |
* Checks if the host OS is some version of Windows. |
|
125 |
* @return true if the host OS is some version of Windows |
|
126 |
*/ |
|
127 |
public boolean isWindows() { |
|
128 |
return osName.toLowerCase(Locale.ENGLISH).startsWith("windows"); |
|
129 |
} |
|
130 |
||
131 |
/** |
|
132 |
* Splits a string around matches of the given regular expression. |
|
133 |
* If the string is empty, an empty list will be returned. |
|
134 |
* @param text the string to be split |
|
135 |
* @param sep the delimiting regular expression |
|
136 |
* @return the strings between the separators |
|
137 |
*/ |
|
138 |
public List<String> split(String text, String sep) { |
|
139 |
if (text.isEmpty()) |
|
140 |
return Collections.emptyList(); |
|
141 |
return Arrays.asList(text.split(sep)); |
|
142 |
} |
|
143 |
||
144 |
/** |
|
145 |
* Checks if two lists of strings are equal. |
|
146 |
* @param l1 the first list of strings to be compared |
|
147 |
* @param l2 the second list of strings to be compared |
|
148 |
* @throws Error if the lists are not equal |
|
149 |
*/ |
|
150 |
public void checkEqual(List<String> l1, List<String> l2) throws Error { |
|
151 |
if (!Objects.equals(l1, l2)) { |
|
152 |
// l1 and l2 cannot both be null |
|
153 |
if (l1 == null) |
|
154 |
throw new Error("comparison failed: l1 is null"); |
|
155 |
if (l2 == null) |
|
156 |
throw new Error("comparison failed: l2 is null"); |
|
157 |
// report first difference |
|
158 |
for (int i = 0; i < Math.min(l1.size(), l2.size()); i++) { |
|
159 |
String s1 = l1.get(i); |
|
160 |
String s2 = l1.get(i); |
|
161 |
if (!Objects.equals(s1, s2)) { |
|
162 |
throw new Error("comparison failed, index " + i + |
|
163 |
", (" + s1 + ":" + s2 + ")"); |
|
164 |
} |
|
165 |
} |
|
166 |
throw new Error("comparison failed: l1.size=" + l1.size() + ", l2.size=" + l2.size()); |
|
167 |
} |
|
168 |
} |
|
169 |
||
170 |
/** |
|
171 |
* Filters a list of strings according to the given regular expression. |
|
172 |
* @param regex the regular expression |
|
173 |
* @param lines the strings to be filtered |
|
174 |
* @return the strings matching the regular expression |
|
175 |
*/ |
|
176 |
public List<String> grep(String regex, List<String> lines) { |
|
177 |
return grep(Pattern.compile(regex), lines); |
|
178 |
} |
|
179 |
||
180 |
/** |
|
181 |
* Filters a list of strings according to the given regular expression. |
|
182 |
* @param pattern the regular expression |
|
183 |
* @param lines the strings to be filtered |
|
184 |
* @return the strings matching the regular expression |
|
185 |
*/ |
|
186 |
public List<String> grep(Pattern pattern, List<String> lines) { |
|
187 |
return lines.stream() |
|
188 |
.filter(s -> pattern.matcher(s).find()) |
|
189 |
.collect(Collectors.toList()); |
|
190 |
} |
|
191 |
||
192 |
/** |
|
193 |
* Copies a file. |
|
194 |
* If the given destination exists and is a directory, the copy is created |
|
195 |
* in that directory. Otherwise, the copy will be placed at the destination, |
|
196 |
* possibly overwriting any existing file. |
|
197 |
* <p>Similar to the shell "cp" command: {@code cp from to}. |
|
198 |
* @param from the file to be copied |
|
199 |
* @param to where to copy the file |
|
200 |
* @throws IOException if any error occurred while copying the file |
|
201 |
*/ |
|
202 |
public void copyFile(String from, String to) throws IOException { |
|
203 |
copyFile(Paths.get(from), Paths.get(to)); |
|
204 |
} |
|
205 |
||
206 |
/** |
|
207 |
* Copies a file. |
|
208 |
* If the given destination exists and is a directory, the copy is created |
|
209 |
* in that directory. Otherwise, the copy will be placed at the destination, |
|
210 |
* possibly overwriting any existing file. |
|
211 |
* <p>Similar to the shell "cp" command: {@code cp from to}. |
|
212 |
* @param from the file to be copied |
|
213 |
* @param to where to copy the file |
|
214 |
* @throws IOException if an error occurred while copying the file |
|
215 |
*/ |
|
216 |
public void copyFile(Path from, Path to) throws IOException { |
|
217 |
if (Files.isDirectory(to)) { |
|
218 |
to = to.resolve(from.getFileName()); |
|
219 |
} else { |
|
220 |
Files.createDirectories(to.getParent()); |
|
221 |
} |
|
222 |
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING); |
|
223 |
} |
|
224 |
||
225 |
/** |
|
226 |
* Creates one of more directories. |
|
227 |
* For each of the series of paths, a directory will be created, |
|
228 |
* including any necessary parent directories. |
|
229 |
* <p>Similar to the shell command: {@code mkdir -p paths}. |
|
230 |
* @param paths the directories to be created |
|
231 |
* @throws IOException if an error occurred while creating the directories |
|
232 |
*/ |
|
233 |
public void createDirectories(String... paths) throws IOException { |
|
234 |
if (paths.length == 0) |
|
235 |
throw new IllegalArgumentException("no directories specified"); |
|
236 |
for (String p: paths) |
|
237 |
Files.createDirectories(Paths.get(p)); |
|
238 |
} |
|
239 |
||
240 |
/** |
|
241 |
* Creates one or more directories. |
|
242 |
* For each of the series of paths, a directory will be created, |
|
243 |
* including any necessary parent directories. |
|
244 |
* <p>Similar to the shell command: {@code mkdir -p paths}. |
|
245 |
* @param paths the directories to be created |
|
246 |
* @throws IOException if an error occurred while creating the directories |
|
247 |
*/ |
|
248 |
public void createDirectories(Path... paths) throws IOException { |
|
249 |
if (paths.length == 0) |
|
250 |
throw new IllegalArgumentException("no directories specified"); |
|
251 |
for (Path p: paths) |
|
252 |
Files.createDirectories(p); |
|
253 |
} |
|
254 |
||
255 |
/** |
|
256 |
* Deletes one or more files. |
|
257 |
* Any directories to be deleted must be empty. |
|
258 |
* <p>Similar to the shell command: {@code rm files}. |
|
259 |
* @param files the files to be deleted |
|
260 |
* @throws IOException if an error occurred while deleting the files |
|
261 |
*/ |
|
262 |
public void deleteFiles(String... files) throws IOException { |
|
263 |
if (files.length == 0) |
|
264 |
throw new IllegalArgumentException("no files specified"); |
|
265 |
for (String file: files) |
|
266 |
Files.delete(Paths.get(file)); |
|
267 |
} |
|
268 |
||
269 |
/** |
|
270 |
* Moves a file. |
|
271 |
* If the given destination exists and is a directory, the file will be moved |
|
272 |
* to that directory. Otherwise, the file will be moved to the destination, |
|
273 |
* possibly overwriting any existing file. |
|
274 |
* <p>Similar to the shell "mv" command: {@code mv from to}. |
|
275 |
* @param from the file to be moved |
|
276 |
* @param to where to move the file |
|
277 |
* @throws IOException if an error occurred while moving the file |
|
278 |
*/ |
|
279 |
public void moveFile(String from, String to) throws IOException { |
|
280 |
moveFile(Paths.get(from), Paths.get(to)); |
|
281 |
} |
|
282 |
||
283 |
/** |
|
284 |
* Moves a file. |
|
285 |
* If the given destination exists and is a directory, the file will be moved |
|
286 |
* to that directory. Otherwise, the file will be moved to the destination, |
|
287 |
* possibly overwriting any existing file. |
|
288 |
* <p>Similar to the shell "mv" command: {@code mv from to}. |
|
289 |
* @param from the file to be moved |
|
290 |
* @param to where to move the file |
|
291 |
* @throws IOException if an error occurred while moving the file |
|
292 |
*/ |
|
293 |
public void moveFile(Path from, Path to) throws IOException { |
|
294 |
if (Files.isDirectory(to)) { |
|
295 |
to = to.resolve(from.getFileName()); |
|
296 |
} else { |
|
297 |
Files.createDirectories(to.getParent()); |
|
298 |
} |
|
299 |
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING); |
|
300 |
} |
|
301 |
||
302 |
/** |
|
303 |
* Reads the lines of a file. |
|
304 |
* The file is read using the default character encoding. |
|
305 |
* @param path the file to be read |
|
306 |
* @return the lines of the file. |
|
307 |
* @throws IOException if an error occurred while reading the file |
|
308 |
*/ |
|
309 |
public List<String> readAllLines(String path) throws IOException { |
|
310 |
return readAllLines(path, null); |
|
311 |
} |
|
312 |
||
313 |
/** |
|
314 |
* Reads the lines of a file. |
|
315 |
* The file is read using the default character encoding. |
|
316 |
* @param path the file to be read |
|
317 |
* @return the lines of the file. |
|
318 |
* @throws IOException if an error occurred while reading the file |
|
319 |
*/ |
|
320 |
public List<String> readAllLines(Path path) throws IOException { |
|
321 |
return readAllLines(path, null); |
|
322 |
} |
|
323 |
||
324 |
/** |
|
325 |
* Reads the lines of a file using the given encoding. |
|
326 |
* @param path the file to be read |
|
327 |
* @param encoding the encoding to be used to read the file |
|
328 |
* @return the lines of the file. |
|
329 |
* @throws IOException if an error occurred while reading the file |
|
330 |
*/ |
|
331 |
public List<String> readAllLines(String path, String encoding) throws IOException { |
|
332 |
return readAllLines(Paths.get(path), encoding); |
|
333 |
} |
|
334 |
||
335 |
/** |
|
336 |
* Reads the lines of a file using the given encoding. |
|
337 |
* @param path the file to be read |
|
338 |
* @param encoding the encoding to be used to read the file |
|
339 |
* @return the lines of the file. |
|
340 |
* @throws IOException if an error occurred while reading the file |
|
341 |
*/ |
|
342 |
public List<String> readAllLines(Path path, String encoding) throws IOException { |
|
343 |
return Files.readAllLines(path, getCharset(encoding)); |
|
344 |
} |
|
345 |
||
346 |
private Charset getCharset(String encoding) { |
|
347 |
return (encoding == null) ? Charset.defaultCharset() : Charset.forName(encoding); |
|
348 |
} |
|
349 |
||
350 |
/** |
|
351 |
* Writes a file containing the given content. |
|
352 |
* Any necessary directories for the file will be created. |
|
353 |
* @param path where to write the file |
|
354 |
* @param content the content for the file |
|
355 |
* @throws IOException if an error occurred while writing the file |
|
356 |
*/ |
|
357 |
public void writeFile(String path, String content) throws IOException { |
|
358 |
writeFile(Paths.get(path), content); |
|
359 |
} |
|
360 |
||
361 |
/** |
|
362 |
* Writes a file containing the given content. |
|
363 |
* Any necessary directories for the file will be created. |
|
364 |
* @param path where to write the file |
|
365 |
* @param content the content for the file |
|
366 |
* @throws IOException if an error occurred while writing the file |
|
367 |
*/ |
|
368 |
public void writeFile(Path path, String content) throws IOException { |
|
369 |
Path dir = path.getParent(); |
|
370 |
if (dir != null) |
|
371 |
Files.createDirectories(dir); |
|
372 |
try (BufferedWriter w = Files.newBufferedWriter(path)) { |
|
373 |
w.write(content); |
|
374 |
} |
|
375 |
} |
|
376 |
||
377 |
/** |
|
378 |
* Writes one or more files containing Java source code. |
|
379 |
* For each file to be written, the filename will be inferred from the |
|
380 |
* given base directory, the package declaration (if present) and from the |
|
381 |
* the name of the first class, interface or enum declared in the file. |
|
382 |
* <p>For example, if the base directory is /my/dir/ and the content |
|
383 |
* contains "package p; class C { }", the file will be written to |
|
384 |
* /my/dir/p/C.java. |
|
385 |
* <p>Note: the content is analyzed using regular expressions; |
|
386 |
* errors can occur if any contents have initial comments that might trip |
|
387 |
* up the analysis. |
|
388 |
* @param dir the base directory |
|
389 |
* @param contents the contents of the files to be written |
|
390 |
* @throws IOException if an error occurred while writing any of the files. |
|
391 |
*/ |
|
392 |
public void writeJavaFiles(Path dir, String... contents) throws IOException { |
|
393 |
if (contents.length == 0) |
|
394 |
throw new IllegalArgumentException("no content specified for any files"); |
|
395 |
for (String c: contents) { |
|
396 |
new JavaSource(c).write(dir); |
|
397 |
} |
|
398 |
} |
|
399 |
||
400 |
/** |
|
401 |
* Returns the path for the binary of a JDK tool within {@link testJDK}. |
|
402 |
* @param tool the name of the tool |
|
403 |
* @return the path of the tool |
|
404 |
*/ |
|
405 |
public Path getJDKTool(String tool) { |
|
406 |
return Paths.get(testJDK, "bin", tool); |
|
407 |
} |
|
408 |
||
409 |
/** |
|
410 |
* Returns a string representing the contents of an {@code Iterable} as a list. |
|
411 |
* @param <T> the type parameter of the {@code Iterable} |
|
412 |
* @param items the iterable |
|
413 |
* @return the string |
|
414 |
*/ |
|
415 |
<T> String toString(Iterable<T> items) { |
|
416 |
return StreamSupport.stream(items.spliterator(), false) |
|
417 |
.map(Objects::toString) |
|
418 |
.collect(Collectors.joining(",", "[", "]")); |
|
419 |
} |
|
420 |
||
421 |
/** |
|
422 |
* The supertype for tasks. |
|
423 |
* Complex operations are modelled by building and running a "Task" object. |
|
424 |
* Tasks are typically configured in a fluent series of calls. |
|
425 |
*/ |
|
426 |
public interface Task { |
|
427 |
/** |
|
428 |
* Returns the name of the task. |
|
429 |
* @return the name of the task |
|
430 |
*/ |
|
431 |
String name(); |
|
432 |
||
433 |
/** |
|
434 |
* Executes the task as currently configured. |
|
435 |
* @return a Result object containing the results of running the task |
|
436 |
* @throws TaskError if the outcome of the task was not as expected |
|
437 |
*/ |
|
438 |
Result run() throws TaskError; |
|
439 |
} |
|
440 |
||
441 |
/** |
|
442 |
* Exception thrown by {@code Task.run} when the outcome is not as |
|
443 |
* expected. |
|
444 |
*/ |
|
445 |
public static class TaskError extends Error { |
|
446 |
/** |
|
447 |
* Creates a TaskError object with the given message. |
|
448 |
* @param message the message |
|
449 |
*/ |
|
450 |
public TaskError(String message) { |
|
451 |
super(message); |
|
452 |
} |
|
453 |
} |
|
454 |
||
455 |
/** |
|
456 |
* An enum to indicate the mode a task should use it is when executed. |
|
457 |
*/ |
|
458 |
public enum Mode { |
|
459 |
/** |
|
460 |
* The task should use the interface used by the command |
|
461 |
* line launcher for the task. |
|
462 |
* For example, for javac: com.sun.tools.javac.Main.compile |
|
463 |
*/ |
|
464 |
CMDLINE, |
|
465 |
/** |
|
466 |
* The task should use a publicly defined API for the task. |
|
467 |
* For example, for javac: javax.tools.JavaCompiler |
|
468 |
*/ |
|
469 |
API, |
|
470 |
/** |
|
471 |
* The task should use the standard launcher for the task. |
|
472 |
* For example, $JAVA_HOME/bin/javac |
|
473 |
*/ |
|
474 |
EXEC |
|
475 |
} |
|
476 |
||
477 |
/** |
|
478 |
* An enum to indicate the expected success or failure of executing a task. |
|
479 |
*/ |
|
480 |
public enum Expect { |
|
481 |
/** It is expected that the task will complete successfully. */ |
|
482 |
SUCCESS, |
|
483 |
/** It is expected that the task will not complete successfully. */ |
|
484 |
FAIL |
|
485 |
} |
|
486 |
||
487 |
/** |
|
488 |
* An enum to identify the streams that may be written by a {@code Task}. |
|
489 |
*/ |
|
490 |
public enum OutputKind { |
|
491 |
/** Identifies output written to {@code System.out} or {@code stdout}. */ |
|
492 |
STDOUT, |
|
493 |
/** Identifies output written to {@code System.err} or {@code stderr}. */ |
|
494 |
STDERR, |
|
495 |
/** Identifies output written to a stream provided directly to the task. */ |
|
496 |
DIRECT |
|
497 |
}; |
|
498 |
||
499 |
/** |
|
500 |
* The results from running a {@link Task}. |
|
501 |
* The results contain the exit code returned when the tool was invoked, |
|
502 |
* and a map containing the output written to any streams during the |
|
503 |
* execution of the tool. |
|
504 |
* All tools support "stdout" and "stderr". |
|
505 |
* Tools that take an explicit PrintWriter save output written to that |
|
506 |
* stream as "main". |
|
507 |
*/ |
|
508 |
public class Result { |
|
509 |
||
510 |
final Task task; |
|
511 |
final int exitCode; |
|
512 |
final Map<OutputKind, String> outputMap; |
|
513 |
||
514 |
Result(Task task, int exitCode, Map<OutputKind, String> outputMap) { |
|
515 |
this.task = task; |
|
516 |
this.exitCode = exitCode; |
|
517 |
this.outputMap = outputMap; |
|
518 |
} |
|
519 |
||
520 |
/** |
|
521 |
* Returns the content of a specified stream. |
|
522 |
* @param outputKind the kind of the selected stream |
|
523 |
* @return the content that was written to that stream when the tool |
|
524 |
* was executed. |
|
525 |
*/ |
|
526 |
public String getOutput(OutputKind outputKind) { |
|
527 |
return outputMap.get(outputKind); |
|
528 |
} |
|
529 |
||
530 |
/** |
|
531 |
* Returns the content of a named stream as a list of lines. |
|
532 |
* @param outputKind the kind of the selected stream |
|
533 |
* @return the content that was written to that stream when the tool |
|
534 |
* was executed. |
|
535 |
*/ |
|
536 |
public List<String> getOutputLines(OutputKind outputKind) { |
|
537 |
return Arrays.asList(outputMap.get(outputKind).split(lineSeparator)); |
|
538 |
} |
|
539 |
||
540 |
/** |
|
541 |
* Writes the content of the specified stream to the log. |
|
542 |
* @param kind the kind of the selected stream |
|
543 |
* @return this Result object |
|
544 |
*/ |
|
545 |
public Result write(OutputKind kind) { |
|
546 |
String text = getOutput(kind); |
|
547 |
if (text == null || text.isEmpty()) |
|
548 |
out.println("[" + task.name() + ":" + kind + "]: empty"); |
|
549 |
else { |
|
550 |
out.println("[" + task.name() + ":" + kind + "]:"); |
|
551 |
out.print(text); |
|
552 |
} |
|
553 |
return this; |
|
554 |
} |
|
555 |
||
556 |
/** |
|
557 |
* Writes the content of all streams with any content to the log. |
|
558 |
* @return this Result object |
|
559 |
*/ |
|
560 |
public Result writeAll() { |
|
561 |
outputMap.forEach((name, text) -> { |
|
562 |
if (!text.isEmpty()) { |
|
563 |
out.println("[" + name + "]:"); |
|
564 |
out.print(text); |
|
565 |
} |
|
566 |
}); |
|
567 |
return this; |
|
568 |
} |
|
569 |
} |
|
570 |
||
571 |
/** |
|
572 |
* A utility base class to simplify the implementation of tasks. |
|
573 |
* Provides support for running the task in a process and for |
|
574 |
* capturing output written by the task to stdout, stderr and |
|
575 |
* other writers where applicable. |
|
576 |
* @param <T> the implementing subclass |
|
577 |
*/ |
|
578 |
protected static abstract class AbstractTask<T extends AbstractTask<T>> implements Task { |
|
579 |
protected final Mode mode; |
|
580 |
private final Map<OutputKind, String> redirects = new EnumMap<>(OutputKind.class); |
|
581 |
private final Map<String, String> envVars = new HashMap<>(); |
|
582 |
private Expect expect = Expect.SUCCESS; |
|
583 |
int expectedExitCode = 0; |
|
584 |
||
585 |
/** |
|
586 |
* Create a task that will execute in the specified mode. |
|
587 |
* @param mode the mode |
|
588 |
*/ |
|
589 |
protected AbstractTask(Mode mode) { |
|
590 |
this.mode = mode; |
|
591 |
} |
|
592 |
||
593 |
/** |
|
594 |
* Sets the expected outcome of the task and calls {@code run()}. |
|
595 |
* @param expect the expected outcome |
|
596 |
* @return the result of calling {@code run()} |
|
597 |
*/ |
|
598 |
public Result run(Expect expect) { |
|
599 |
expect(expect, Integer.MIN_VALUE); |
|
600 |
return run(); |
|
601 |
} |
|
602 |
||
603 |
/** |
|
604 |
* Sets the expected outcome of the task and calls {@code run()}. |
|
605 |
* @param expect the expected outcome |
|
606 |
* @param exitCode the expected exit code if the expected outcome |
|
607 |
* is {@code FAIL} |
|
608 |
* @return the result of calling {@code run()} |
|
609 |
*/ |
|
610 |
public Result run(Expect expect, int exitCode) { |
|
611 |
expect(expect, exitCode); |
|
612 |
return run(); |
|
613 |
} |
|
614 |
||
615 |
/** |
|
616 |
* Sets the expected outcome and expected exit code of the task. |
|
617 |
* The exit code will not be checked if the outcome is |
|
618 |
* {@code Expect.SUCCESS} or if the exit code is set to |
|
619 |
* {@code Integer.MIN_VALUE}. |
|
620 |
* @param expect the expected outcome |
|
621 |
* @param exitCode the expected exit code |
|
622 |
*/ |
|
623 |
protected void expect(Expect expect, int exitCode) { |
|
624 |
this.expect = expect; |
|
625 |
this.expectedExitCode = exitCode; |
|
626 |
} |
|
627 |
||
628 |
/** |
|
629 |
* Checks the exit code contained in a {@code Result} against the |
|
630 |
* expected outcome and exit value |
|
631 |
* @param result the result object |
|
632 |
* @return the result object |
|
633 |
* @throws TaskError if the exit code stored in the result object |
|
634 |
* does not match the expected outcome and exit code. |
|
635 |
*/ |
|
636 |
protected Result checkExit(Result result) throws TaskError { |
|
637 |
switch (expect) { |
|
638 |
case SUCCESS: |
|
639 |
if (result.exitCode != 0) { |
|
640 |
result.writeAll(); |
|
641 |
throw new TaskError("Task " + name() + " failed: rc=" + result.exitCode); |
|
642 |
} |
|
643 |
break; |
|
644 |
||
645 |
case FAIL: |
|
646 |
if (result.exitCode == 0) { |
|
647 |
result.writeAll(); |
|
648 |
throw new TaskError("Task " + name() + " succeeded unexpectedly"); |
|
649 |
} |
|
650 |
||
651 |
if (expectedExitCode != Integer.MIN_VALUE |
|
652 |
&& result.exitCode != expectedExitCode) { |
|
653 |
result.writeAll(); |
|
654 |
throw new TaskError("Task " + name() + "failed with unexpected exit code " |
|
655 |
+ result.exitCode + ", expected " + expectedExitCode); |
|
656 |
} |
|
657 |
break; |
|
658 |
} |
|
659 |
return result; |
|
660 |
} |
|
661 |
||
662 |
/** |
|
663 |
* Sets an environment variable to be used by this task. |
|
664 |
* @param name the name of the environment variable |
|
665 |
* @param value the value for the environment variable |
|
666 |
* @return this task object |
|
667 |
* @throws IllegalStateException if the task mode is not {@code EXEC} |
|
668 |
*/ |
|
669 |
protected T envVar(String name, String value) { |
|
670 |
if (mode != Mode.EXEC) |
|
671 |
throw new IllegalStateException(); |
|
672 |
envVars.put(name, value); |
|
673 |
return (T) this; |
|
674 |
} |
|
675 |
||
676 |
/** |
|
677 |
* Redirects output from an output stream to a file. |
|
678 |
* @param outputKind the name of the stream to be redirected. |
|
679 |
* @param path the file |
|
680 |
* @return this task object |
|
681 |
* @throws IllegalStateException if the task mode is not {@code EXEC} |
|
682 |
*/ |
|
683 |
protected T redirect(OutputKind outputKind, String path) { |
|
684 |
if (mode != Mode.EXEC) |
|
685 |
throw new IllegalStateException(); |
|
686 |
redirects.put(outputKind, path); |
|
687 |
return (T) this; |
|
688 |
} |
|
689 |
||
690 |
/** |
|
691 |
* Returns a {@code ProcessBuilder} initialized with any |
|
692 |
* redirects and environment variables that have been set. |
|
693 |
* @return a {@code ProcessBuilder} |
|
694 |
*/ |
|
695 |
protected ProcessBuilder getProcessBuilder() { |
|
696 |
if (mode != Mode.EXEC) |
|
697 |
throw new IllegalStateException(); |
|
698 |
ProcessBuilder pb = new ProcessBuilder(); |
|
699 |
if (redirects.get(OutputKind.STDOUT) != null) |
|
700 |
pb.redirectOutput(new File(redirects.get(OutputKind.STDOUT))); |
|
701 |
if (redirects.get(OutputKind.STDERR) != null) |
|
702 |
pb.redirectError(new File(redirects.get(OutputKind.STDERR))); |
|
703 |
pb.environment().putAll(envVars); |
|
704 |
return pb; |
|
705 |
} |
|
706 |
||
707 |
/** |
|
708 |
* Collects the output from a process and saves it in a {@code Result}. |
|
709 |
* @param tb the {@code ToolBox} containing the task {@code t} |
|
710 |
* @param t the task initiating the process |
|
711 |
* @param p the process |
|
712 |
* @return a Result object containing the output from the process and its |
|
713 |
* exit value. |
|
714 |
* @throws InterruptedException if the thread is interrupted |
|
715 |
*/ |
|
716 |
protected Result runProcess(ToolBox tb, Task t, Process p) throws InterruptedException { |
|
717 |
if (mode != Mode.EXEC) |
|
718 |
throw new IllegalStateException(); |
|
719 |
ProcessOutput sysOut = new ProcessOutput(p.getInputStream()).start(); |
|
720 |
ProcessOutput sysErr = new ProcessOutput(p.getErrorStream()).start(); |
|
721 |
sysOut.waitUntilDone(); |
|
722 |
sysErr.waitUntilDone(); |
|
723 |
int rc = p.waitFor(); |
|
724 |
Map<OutputKind, String> outputMap = new EnumMap<>(OutputKind.class); |
|
725 |
outputMap.put(OutputKind.STDOUT, sysOut.getOutput()); |
|
726 |
outputMap.put(OutputKind.STDERR, sysErr.getOutput()); |
|
727 |
return checkExit(tb.new Result(t, rc, outputMap)); |
|
728 |
} |
|
729 |
||
730 |
/** |
|
731 |
* Thread-friendly class to read the output from a process until the stream |
|
732 |
* is exhausted. |
|
733 |
*/ |
|
734 |
static class ProcessOutput implements Runnable { |
|
735 |
ProcessOutput(InputStream from) { |
|
736 |
in = new BufferedReader(new InputStreamReader(from)); |
|
737 |
out = new StringBuilder(); |
|
738 |
} |
|
739 |
||
740 |
ProcessOutput start() { |
|
741 |
new Thread(this).start(); |
|
742 |
return this; |
|
743 |
} |
|
744 |
||
745 |
@Override |
|
746 |
public void run() { |
|
747 |
try { |
|
748 |
String line; |
|
749 |
while ((line = in.readLine()) != null) { |
|
750 |
out.append(line).append("\n"); |
|
751 |
} |
|
752 |
} catch (IOException e) { |
|
753 |
} |
|
754 |
synchronized (this) { |
|
755 |
done = true; |
|
756 |
notifyAll(); |
|
757 |
} |
|
758 |
} |
|
759 |
||
760 |
synchronized void waitUntilDone() throws InterruptedException { |
|
761 |
boolean interrupted = false; |
|
762 |
||
763 |
// poll interrupted flag, while waiting for copy to complete |
|
764 |
while (!(interrupted = Thread.interrupted()) && !done) |
|
765 |
wait(1000); |
|
766 |
||
767 |
if (interrupted) |
|
768 |
throw new InterruptedException(); |
|
769 |
} |
|
770 |
||
771 |
String getOutput() { |
|
772 |
return out.toString(); |
|
773 |
} |
|
774 |
||
775 |
private BufferedReader in; |
|
776 |
private final StringBuilder out; |
|
777 |
private boolean done; |
|
778 |
} |
|
779 |
||
780 |
/** |
|
781 |
* Utility class to simplify the handling of temporarily setting a |
|
782 |
* new stream for System.out or System.err. |
|
783 |
*/ |
|
784 |
static class StreamOutput { |
|
785 |
// Functional interface to set a stream. |
|
786 |
// Expected use: System::setOut, System::setErr |
|
787 |
private interface Initializer { |
|
788 |
void set(PrintStream s); |
|
789 |
} |
|
790 |
||
791 |
private final ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
|
792 |
private final PrintStream ps = new PrintStream(baos); |
|
793 |
private final PrintStream prev; |
|
794 |
private final Initializer init; |
|
795 |
||
796 |
StreamOutput(PrintStream s, Initializer init) { |
|
797 |
prev = s; |
|
798 |
init.set(ps); |
|
799 |
this.init = init; |
|
800 |
} |
|
801 |
||
802 |
/** |
|
803 |
* Closes the stream and returns the contents that were written to it. |
|
804 |
* @return the contents that were written to it. |
|
805 |
*/ |
|
806 |
String close() { |
|
807 |
init.set(prev); |
|
808 |
ps.close(); |
|
809 |
return baos.toString(); |
|
810 |
} |
|
811 |
} |
|
812 |
||
813 |
/** |
|
814 |
* Utility class to simplify the handling of creating an in-memory PrintWriter. |
|
815 |
*/ |
|
816 |
static class WriterOutput { |
|
817 |
private final StringWriter sw = new StringWriter(); |
|
818 |
final PrintWriter pw = new PrintWriter(sw); |
|
819 |
||
820 |
/** |
|
821 |
* Closes the stream and returns the contents that were written to it. |
|
822 |
* @return the contents that were written to it. |
|
823 |
*/ |
|
824 |
String close() { |
|
825 |
pw.close(); |
|
826 |
return sw.toString(); |
|
827 |
} |
|
828 |
} |
|
829 |
} |
|
830 |
||
831 |
/** |
|
832 |
* A task to configure and run the Java compiler, javac. |
|
833 |
*/ |
|
834 |
public class JavacTask extends AbstractTask<JavacTask> { |
|
835 |
private boolean includeStandardOptions; |
|
836 |
private String classpath; |
|
837 |
private String sourcepath; |
|
838 |
private String outdir; |
|
839 |
private List<String> options; |
|
840 |
private List<String> classes; |
|
841 |
private List<String> files; |
|
842 |
private List<JavaFileObject> fileObjects; |
|
843 |
private JavaFileManager fileManager; |
|
844 |
||
845 |
/** |
|
846 |
* Creates a task to execute {@code javac} using API mode. |
|
847 |
*/ |
|
848 |
public JavacTask() { |
|
849 |
super(Mode.API); |
|
850 |
} |
|
851 |
||
852 |
/** |
|
853 |
* Creates a task to execute {@code javac} in a specified mode. |
|
854 |
* @param mode the mode to be used |
|
855 |
*/ |
|
856 |
public JavacTask(Mode mode) { |
|
857 |
super(mode); |
|
858 |
} |
|
859 |
||
860 |
/** |
|
861 |
* Sets the classpath. |
|
862 |
* @param classpath the classpath |
|
863 |
* @return this task object |
|
864 |
*/ |
|
865 |
public JavacTask classpath(String classpath) { |
|
866 |
this.classpath = classpath; |
|
867 |
return this; |
|
868 |
} |
|
869 |
||
870 |
/** |
|
871 |
* Sets the sourcepath. |
|
872 |
* @param sourcepath the sourcepath |
|
873 |
* @return this task object |
|
874 |
*/ |
|
875 |
public JavacTask sourcepath(String sourcepath) { |
|
876 |
this.sourcepath = sourcepath; |
|
877 |
return this; |
|
878 |
} |
|
879 |
||
880 |
/** |
|
881 |
* Sets the output directory. |
|
882 |
* @param outdir the output directory |
|
883 |
* @return this task object |
|
884 |
*/ |
|
885 |
public JavacTask outdir(String outdir) { |
|
886 |
this.outdir = outdir; |
|
887 |
return this; |
|
888 |
} |
|
889 |
||
890 |
/** |
|
891 |
* Sets the options. |
|
892 |
* @param options the options |
|
893 |
* @return this task object |
|
894 |
*/ |
|
895 |
public JavacTask options(String... options) { |
|
896 |
this.options = Arrays.asList(options); |
|
897 |
return this; |
|
898 |
} |
|
899 |
||
900 |
/** |
|
901 |
* Sets the classes to be analyzed. |
|
902 |
* @param classes the classes |
|
903 |
* @return this task object |
|
904 |
*/ |
|
905 |
public JavacTask classes(String... classes) { |
|
906 |
this.classes = Arrays.asList(classes); |
|
907 |
return this; |
|
908 |
} |
|
909 |
||
910 |
/** |
|
911 |
* Sets the files to be compiled or analyzed. |
|
912 |
* @param files the files |
|
913 |
* @return this task object |
|
914 |
*/ |
|
915 |
public JavacTask files(String... files) { |
|
916 |
this.files = Arrays.asList(files); |
|
917 |
return this; |
|
918 |
} |
|
919 |
||
920 |
/** |
|
921 |
* Sets the files to be compiled or analyzed. |
|
922 |
* @param files the files |
|
923 |
* @return this task object |
|
924 |
*/ |
|
925 |
public JavacTask files(Path... files) { |
|
926 |
this.files = Stream.of(files) |
|
927 |
.map(Path::toString) |
|
928 |
.collect(Collectors.toList()); |
|
929 |
return this; |
|
930 |
} |
|
931 |
||
932 |
/** |
|
933 |
* Sets the sources to be compiled or analyzed. |
|
934 |
* Each source string is converted into an in-memory object that |
|
935 |
* can be passed directly to the compiler. |
|
936 |
* @param sources the sources |
|
937 |
* @return this task object |
|
938 |
*/ |
|
939 |
public JavacTask sources(String... sources) { |
|
940 |
fileObjects = Stream.of(sources) |
|
941 |
.map(s -> new JavaSource(s)) |
|
942 |
.collect(Collectors.toList()); |
|
943 |
return this; |
|
944 |
} |
|
945 |
||
946 |
/** |
|
947 |
* Sets the file manager to be used by this task. |
|
948 |
* @param fileManager the file manager |
|
949 |
* @return this task object |
|
950 |
*/ |
|
951 |
public JavacTask fileManager(JavaFileManager fileManager) { |
|
952 |
this.fileManager = fileManager; |
|
953 |
return this; |
|
954 |
} |
|
955 |
||
956 |
/** |
|
957 |
* {@inheritDoc} |
|
958 |
* @return the name "javac" |
|
959 |
*/ |
|
960 |
@Override |
|
961 |
public String name() { |
|
962 |
return "javac"; |
|
963 |
} |
|
964 |
||
965 |
/** |
|
966 |
* Calls the compiler with the arguments as currently configured. |
|
967 |
* @return a Result object indicating the outcome of the compilation |
|
968 |
* and the content of any output written to stdout, stderr, or the |
|
969 |
* main stream by the compiler. |
|
970 |
* @throws TaskError if the outcome of the task is not as expected. |
|
971 |
*/ |
|
972 |
@Override |
|
973 |
public Result run() { |
|
974 |
if (mode == Mode.EXEC) |
|
975 |
return runExec(); |
|
976 |
||
977 |
WriterOutput direct = new WriterOutput(); |
|
978 |
// The following are to catch output to System.out and System.err, |
|
979 |
// in case these are used instead of the primary (main) stream |
|
980 |
StreamOutput sysOut = new StreamOutput(System.out, System::setOut); |
|
981 |
StreamOutput sysErr = new StreamOutput(System.err, System::setErr); |
|
982 |
int rc; |
|
983 |
Map<OutputKind, String> outputMap = new HashMap<>(); |
|
984 |
try { |
|
985 |
switch (mode == null ? Mode.API : mode) { |
|
986 |
case API: |
|
987 |
rc = runAPI(direct.pw); |
|
988 |
break; |
|
989 |
case CMDLINE: |
|
990 |
rc = runCommand(direct.pw); |
|
991 |
break; |
|
992 |
default: |
|
993 |
throw new IllegalStateException(); |
|
994 |
} |
|
995 |
} catch (IOException e) { |
|
996 |
out.println("Exception occurred: " + e); |
|
997 |
rc = 99; |
|
998 |
} finally { |
|
999 |
outputMap.put(OutputKind.STDOUT, sysOut.close()); |
|
1000 |
outputMap.put(OutputKind.STDERR, sysErr.close()); |
|
1001 |
outputMap.put(OutputKind.DIRECT, direct.close()); |
|
1002 |
} |
|
1003 |
return checkExit(new Result(this, rc, outputMap)); |
|
1004 |
} |
|
1005 |
||
1006 |
private int runAPI(PrintWriter pw) throws IOException { |
|
1007 |
// if (compiler == null) { |
|
1008 |
// TODO: allow this to be set externally |
|
1009 |
// compiler = ToolProvider.getSystemJavaCompiler(); |
|
1010 |
compiler = JavacTool.create(); |
|
1011 |
// } |
|
1012 |
||
1013 |
if (fileManager == null) |
|
1014 |
fileManager = compiler.getStandardFileManager(null, null, null); |
|
1015 |
if (outdir != null) |
|
1016 |
setLocation(StandardLocation.CLASS_OUTPUT, toFiles(outdir)); |
|
1017 |
if (classpath != null) |
|
1018 |
setLocation(StandardLocation.CLASS_PATH, toFiles(classpath)); |
|
1019 |
if (sourcepath != null) |
|
1020 |
setLocation(StandardLocation.SOURCE_PATH, toFiles(sourcepath)); |
|
1021 |
List<String> allOpts = new ArrayList<>(); |
|
1022 |
if (options != null) |
|
1023 |
allOpts.addAll(options); |
|
1024 |
||
1025 |
Iterable<? extends JavaFileObject> allFiles = joinFiles(files, fileObjects); |
|
1026 |
JavaCompiler.CompilationTask task = compiler.getTask(pw, |
|
1027 |
fileManager, |
|
1028 |
null, // diagnostic listener; should optionally collect diags |
|
1029 |
allOpts, |
|
1030 |
classes, |
|
1031 |
allFiles); |
|
1032 |
return ((JavacTaskImpl) task).doCall().exitCode; |
|
1033 |
} |
|
1034 |
||
1035 |
private void setLocation(StandardLocation location, List<File> files) throws IOException { |
|
1036 |
if (!(fileManager instanceof StandardJavaFileManager)) |
|
1037 |
throw new IllegalStateException("not a StandardJavaFileManager"); |
|
1038 |
((StandardJavaFileManager) fileManager).setLocation(location, files); |
|
1039 |
} |
|
1040 |
||
1041 |
private int runCommand(PrintWriter pw) { |
|
1042 |
List<String> args = getAllArgs(); |
|
1043 |
String[] argsArray = args.toArray(new String[args.size()]); |
|
1044 |
return com.sun.tools.javac.Main.compile(argsArray, pw); |
|
1045 |
} |
|
1046 |
||
1047 |
private Result runExec() { |
|
1048 |
List<String> args = new ArrayList<>(); |
|
1049 |
Path javac = getJDKTool("javac"); |
|
1050 |
args.add(javac.toString()); |
|
1051 |
if (includeStandardOptions) { |
|
1052 |
args.addAll(split(System.getProperty("test.tool.vm.opts"), " +")); |
|
1053 |
args.addAll(split(System.getProperty("test.compiler.opts"), " +")); |
|
1054 |
} |
|
1055 |
args.addAll(getAllArgs()); |
|
1056 |
||
1057 |
String[] argsArray = args.toArray(new String[args.size()]); |
|
1058 |
ProcessBuilder pb = getProcessBuilder(); |
|
1059 |
pb.command(argsArray); |
|
1060 |
try { |
|
1061 |
return runProcess(ToolBox.this, this, pb.start()); |
|
1062 |
} catch (IOException | InterruptedException e) { |
|
1063 |
throw new Error(e); |
|
1064 |
} |
|
1065 |
} |
|
1066 |
||
1067 |
private List<String> getAllArgs() { |
|
1068 |
List<String> args = new ArrayList<>(); |
|
1069 |
if (options != null) |
|
1070 |
args.addAll(options); |
|
1071 |
if (outdir != null) { |
|
1072 |
args.add("-d"); |
|
1073 |
args.add(outdir); |
|
1074 |
} |
|
1075 |
if (classpath != null) { |
|
1076 |
args.add("-classpath"); |
|
1077 |
args.add(classpath); |
|
1078 |
} |
|
1079 |
if (sourcepath != null) { |
|
1080 |
args.add("-sourcepath"); |
|
1081 |
args.add(sourcepath); |
|
1082 |
} |
|
1083 |
if (classes != null) |
|
1084 |
args.addAll(classes); |
|
1085 |
if (files != null) |
|
1086 |
args.addAll(files); |
|
1087 |
||
1088 |
return args; |
|
1089 |
} |
|
1090 |
||
1091 |
private List<File> toFiles(String path) { |
|
1092 |
List<File> result = new ArrayList<>(); |
|
1093 |
for (String s: path.split(File.pathSeparator)) { |
|
1094 |
if (!s.isEmpty()) |
|
1095 |
result.add(new File(s)); |
|
1096 |
} |
|
1097 |
return result; |
|
1098 |
} |
|
1099 |
||
1100 |
private Iterable<? extends JavaFileObject> joinFiles( |
|
1101 |
List<String> files, List<JavaFileObject> fileObjects) { |
|
1102 |
if (files == null) |
|
1103 |
return fileObjects; |
|
1104 |
if (standardJavaFileManager == null) |
|
1105 |
standardJavaFileManager = compiler.getStandardFileManager(null, null, null); |
|
1106 |
Iterable<? extends JavaFileObject> filesAsFileObjects = |
|
1107 |
standardJavaFileManager.getJavaFileObjectsFromStrings(files); |
|
1108 |
if (fileObjects == null) |
|
1109 |
return filesAsFileObjects; |
|
1110 |
List<JavaFileObject> combinedList = new ArrayList<>(); |
|
1111 |
for (JavaFileObject o: filesAsFileObjects) |
|
1112 |
combinedList.add(o); |
|
1113 |
combinedList.addAll(fileObjects); |
|
1114 |
return combinedList; |
|
1115 |
} |
|
1116 |
} |
|
1117 |
||
1118 |
/** |
|
1119 |
* A task to configure and run the native header tool, javah. |
|
1120 |
*/ |
|
1121 |
public class JavahTask extends AbstractTask<JavahTask> { |
|
1122 |
private String classpath; |
|
1123 |
private List<String> options; |
|
1124 |
private List<String> classes; |
|
1125 |
||
1126 |
/** |
|
1127 |
* Create a task to execute {@code javah} using {@code CMDLINE} mode. |
|
1128 |
*/ |
|
1129 |
public JavahTask() { |
|
1130 |
super(Mode.CMDLINE); |
|
1131 |
} |
|
1132 |
||
1133 |
/** |
|
1134 |
* Sets the classpath. |
|
1135 |
* @param classpath the classpath |
|
1136 |
* @return this task object |
|
1137 |
*/ |
|
1138 |
public JavahTask classpath(String classpath) { |
|
1139 |
this.classpath = classpath; |
|
1140 |
return this; |
|
1141 |
} |
|
1142 |
||
1143 |
/** |
|
1144 |
* Sets the options. |
|
1145 |
* @param options the options |
|
1146 |
* @return this task object |
|
1147 |
*/ |
|
1148 |
public JavahTask options(String... options) { |
|
1149 |
this.options = Arrays.asList(options); |
|
1150 |
return this; |
|
1151 |
} |
|
1152 |
||
1153 |
/** |
|
1154 |
* Sets the classes to be analyzed. |
|
1155 |
* @param classes the classes |
|
1156 |
* @return this task object |
|
1157 |
*/ |
|
1158 |
public JavahTask classes(String... classes) { |
|
1159 |
this.classes = Arrays.asList(classes); |
|
1160 |
return this; |
|
1161 |
} |
|
1162 |
||
1163 |
/** |
|
1164 |
* {@inheritDoc} |
|
1165 |
* @return the name "javah" |
|
1166 |
*/ |
|
1167 |
@Override |
|
1168 |
public String name() { |
|
1169 |
return "javah"; |
|
1170 |
} |
|
1171 |
||
1172 |
/** |
|
1173 |
* Calls the javah tool with the arguments as currently configured. |
|
1174 |
* @return a Result object indicating the outcome of the task |
|
1175 |
* and the content of any output written to stdout, stderr, or the |
|
1176 |
* main stream provided to the task. |
|
1177 |
* @throws TaskError if the outcome of the task is not as expected. |
|
1178 |
*/ |
|
1179 |
@Override |
|
1180 |
public Result run() { |
|
1181 |
List<String> args = new ArrayList<>(); |
|
1182 |
if (options != null) |
|
1183 |
args.addAll(options); |
|
1184 |
if (classpath != null) { |
|
1185 |
args.add("-classpath"); |
|
1186 |
args.add(classpath); |
|
1187 |
} |
|
1188 |
if (classes != null) |
|
1189 |
args.addAll(classes); |
|
1190 |
||
1191 |
WriterOutput direct = new WriterOutput(); |
|
1192 |
// These are to catch output to System.out and System.err, |
|
1193 |
// in case these are used instead of the primary streams |
|
1194 |
StreamOutput sysOut = new StreamOutput(System.out, System::setOut); |
|
1195 |
StreamOutput sysErr = new StreamOutput(System.err, System::setErr); |
|
1196 |
int rc; |
|
1197 |
Map<OutputKind, String> outputMap = new HashMap<>(); |
|
1198 |
try { |
|
1199 |
rc = com.sun.tools.javah.Main.run(args.toArray(new String[args.size()]), direct.pw); |
|
1200 |
} finally { |
|
1201 |
outputMap.put(OutputKind.STDOUT, sysOut.close()); |
|
1202 |
outputMap.put(OutputKind.STDERR, sysErr.close()); |
|
1203 |
outputMap.put(OutputKind.DIRECT, direct.close()); |
|
1204 |
} |
|
1205 |
return checkExit(new Result(this, rc, outputMap)); |
|
1206 |
} |
|
1207 |
} |
|
1208 |
||
1209 |
/** |
|
1210 |
* A task to configure and run the disassembler tool, javap. |
|
1211 |
*/ |
|
1212 |
public class JavapTask extends AbstractTask<JavapTask> { |
|
1213 |
private String classpath; |
|
1214 |
private List<String> options; |
|
1215 |
private List<String> classes; |
|
1216 |
||
1217 |
/** |
|
1218 |
* Create a task to execute {@code javap} using {@code CMDLINE} mode. |
|
1219 |
*/ |
|
1220 |
public JavapTask() { |
|
1221 |
super(Mode.CMDLINE); |
|
1222 |
} |
|
1223 |
||
1224 |
/** |
|
1225 |
* Sets the classpath. |
|
1226 |
* @param classpath the classpath |
|
1227 |
* @return this task object |
|
1228 |
*/ |
|
1229 |
public JavapTask classpath(String classpath) { |
|
1230 |
this.classpath = classpath; |
|
1231 |
return this; |
|
1232 |
} |
|
1233 |
||
1234 |
/** |
|
1235 |
* Sets the options. |
|
1236 |
* @param options the options |
|
1237 |
* @return this task object |
|
1238 |
*/ |
|
1239 |
public JavapTask options(String... options) { |
|
1240 |
this.options = Arrays.asList(options); |
|
1241 |
return this; |
|
1242 |
} |
|
1243 |
||
1244 |
/** |
|
1245 |
* Sets the classes to be analyzed. |
|
1246 |
* @param classes the classes |
|
1247 |
* @return this task object |
|
1248 |
*/ |
|
1249 |
public JavapTask classes(String... classes) { |
|
1250 |
this.classes = Arrays.asList(classes); |
|
1251 |
return this; |
|
1252 |
} |
|
1253 |
||
1254 |
/** |
|
1255 |
* {@inheritDoc} |
|
1256 |
* @return the name "javap" |
|
1257 |
*/ |
|
1258 |
@Override |
|
1259 |
public String name() { |
|
1260 |
return "javap"; |
|
1261 |
} |
|
1262 |
||
1263 |
/** |
|
1264 |
* Calls the javap tool with the arguments as currently configured. |
|
1265 |
* @return a Result object indicating the outcome of the task |
|
1266 |
* and the content of any output written to stdout, stderr, or the |
|
1267 |
* main stream. |
|
1268 |
* @throws TaskError if the outcome of the task is not as expected. |
|
1269 |
*/ |
|
1270 |
@Override |
|
1271 |
public Result run() { |
|
1272 |
List<String> args = new ArrayList<>(); |
|
1273 |
if (options != null) |
|
1274 |
args.addAll(options); |
|
1275 |
if (classpath != null) { |
|
1276 |
args.add("-classpath"); |
|
1277 |
args.add(classpath); |
|
1278 |
} |
|
1279 |
if (classes != null) |
|
1280 |
args.addAll(classes); |
|
1281 |
||
1282 |
WriterOutput direct = new WriterOutput(); |
|
1283 |
// These are to catch output to System.out and System.err, |
|
1284 |
// in case these are used instead of the primary streams |
|
1285 |
StreamOutput sysOut = new StreamOutput(System.out, System::setOut); |
|
1286 |
StreamOutput sysErr = new StreamOutput(System.err, System::setErr); |
|
1287 |
||
1288 |
int rc; |
|
1289 |
Map<OutputKind, String> outputMap = new HashMap<>(); |
|
1290 |
try { |
|
1291 |
rc = com.sun.tools.javap.Main.run(args.toArray(new String[args.size()]), direct.pw); |
|
1292 |
} finally { |
|
1293 |
outputMap.put(OutputKind.STDOUT, sysOut.close()); |
|
1294 |
outputMap.put(OutputKind.STDERR, sysErr.close()); |
|
1295 |
outputMap.put(OutputKind.DIRECT, direct.close()); |
|
1296 |
} |
|
1297 |
return checkExit(new Result(this, rc, outputMap)); |
|
1298 |
} |
|
1299 |
} |
|
1300 |
||
1301 |
/** |
|
1302 |
* A task to configure and run the jar file utility. |
|
1303 |
*/ |
|
1304 |
public class JarTask extends AbstractTask<JarTask> { |
|
1305 |
private Path jar; |
|
1306 |
private Manifest manifest; |
|
1307 |
private String classpath; |
|
1308 |
private String mainClass; |
|
1309 |
private Path baseDir; |
|
1310 |
private List<Path> paths; |
|
1311 |
||
1312 |
/** |
|
1313 |
* Creates a task to write jar files, using API mode. |
|
1314 |
*/ |
|
1315 |
public JarTask() { |
|
1316 |
super(Mode.API); |
|
1317 |
paths = Collections.emptyList(); |
|
1318 |
} |
|
1319 |
||
1320 |
/** |
|
1321 |
* Creates a JarTask for use with a given jar file. |
|
1322 |
* @param path the file |
|
1323 |
*/ |
|
1324 |
public JarTask(String path) { |
|
1325 |
this(); |
|
1326 |
jar = Paths.get(path); |
|
1327 |
} |
|
1328 |
||
1329 |
/** |
|
1330 |
* Sets a manifest for the jar file. |
|
1331 |
* @param manifest the manifest |
|
1332 |
* @return this task object |
|
1333 |
*/ |
|
1334 |
public JarTask manifest(Manifest manifest) { |
|
1335 |
this.manifest = manifest; |
|
1336 |
return this; |
|
1337 |
} |
|
1338 |
||
1339 |
/** |
|
1340 |
* Sets a manifest for the jar file. |
|
1341 |
* @param manifest a string containing the contents of the manifest |
|
1342 |
* @return this task object |
|
1343 |
* @throws IOException if there is a problem creating the manifest |
|
1344 |
*/ |
|
1345 |
public JarTask manifest(String manifest) throws IOException { |
|
1346 |
this.manifest = new Manifest(new ByteArrayInputStream(manifest.getBytes())); |
|
1347 |
return this; |
|
1348 |
} |
|
1349 |
||
1350 |
/** |
|
1351 |
* Sets the classpath to be written to the {@code Class-Path} |
|
1352 |
* entry in the manifest. |
|
1353 |
* @param classpath the classpath |
|
1354 |
* @return this task object |
|
1355 |
*/ |
|
1356 |
public JarTask classpath(String classpath) { |
|
1357 |
this.classpath = classpath; |
|
1358 |
return this; |
|
1359 |
} |
|
1360 |
||
1361 |
/** |
|
1362 |
* Sets the class to be written to the {@code Main-Class} |
|
1363 |
* entry in the manifest.. |
|
1364 |
* @param mainClass the name of the main class |
|
1365 |
* @return this task object |
|
1366 |
*/ |
|
1367 |
public JarTask mainClass(String mainClass) { |
|
1368 |
this.mainClass = mainClass; |
|
1369 |
return this; |
|
1370 |
} |
|
1371 |
||
1372 |
/** |
|
1373 |
* Sets the base directory for files to be written into the jar file. |
|
1374 |
* @param baseDir the base directory |
|
1375 |
* @return this task object |
|
1376 |
*/ |
|
1377 |
public JarTask baseDir(String baseDir) { |
|
1378 |
this.baseDir = Paths.get(baseDir); |
|
1379 |
return this; |
|
1380 |
} |
|
1381 |
||
1382 |
/** |
|
1383 |
* Sets the files to be written into the jar file. |
|
1384 |
* @param files the files |
|
1385 |
* @return this task object |
|
1386 |
*/ |
|
1387 |
public JarTask files(String... files) { |
|
1388 |
this.paths = Stream.of(files) |
|
1389 |
.map(file -> Paths.get(file)) |
|
1390 |
.collect(Collectors.toList()); |
|
1391 |
return this; |
|
1392 |
} |
|
1393 |
||
1394 |
/** |
|
1395 |
* Provides limited jar command-like functionality. |
|
1396 |
* The supported commands are: |
|
1397 |
* <ul> |
|
1398 |
* <li> jar cf jarfile -C dir files... |
|
1399 |
* <li> jar cfm jarfile manifestfile -C dir files... |
|
1400 |
* </ul> |
|
1401 |
* Any values specified by other configuration methods will be ignored. |
|
1402 |
* @param args arguments in the style of those for the jar command |
|
1403 |
* @return a Result object containing the results of running the task |
|
1404 |
*/ |
|
1405 |
public Result run(String... args) { |
|
1406 |
if (args.length < 2) |
|
1407 |
throw new IllegalArgumentException(); |
|
1408 |
||
1409 |
ListIterator<String> iter = Arrays.asList(args).listIterator(); |
|
1410 |
String first = iter.next(); |
|
1411 |
switch (first) { |
|
1412 |
case "cf": |
|
1413 |
jar = Paths.get(iter.next()); |
|
1414 |
break; |
|
1415 |
case "cfm": |
|
1416 |
jar = Paths.get(iter.next()); |
|
1417 |
try (InputStream in = Files.newInputStream(Paths.get(iter.next()))) { |
|
1418 |
manifest = new Manifest(in); |
|
1419 |
} catch (IOException e) { |
|
1420 |
throw new IOError(e); |
|
1421 |
} |
|
1422 |
break; |
|
1423 |
} |
|
1424 |
||
1425 |
if (iter.hasNext()) { |
|
1426 |
if (iter.next().equals("-C")) |
|
1427 |
baseDir = Paths.get(iter.next()); |
|
1428 |
else |
|
1429 |
iter.previous(); |
|
1430 |
} |
|
1431 |
||
1432 |
paths = new ArrayList<>(); |
|
1433 |
while (iter.hasNext()) |
|
1434 |
paths.add(Paths.get(iter.next())); |
|
1435 |
||
1436 |
return run(); |
|
1437 |
} |
|
1438 |
||
1439 |
/** |
|
1440 |
* {@inheritDoc} |
|
1441 |
* @return the name "jar" |
|
1442 |
*/ |
|
1443 |
@Override |
|
1444 |
public String name() { |
|
1445 |
return "jar"; |
|
1446 |
} |
|
1447 |
||
1448 |
/** |
|
1449 |
* Creates a jar file with the arguments as currently configured. |
|
1450 |
* @return a Result object indicating the outcome of the compilation |
|
1451 |
* and the content of any output written to stdout, stderr, or the |
|
1452 |
* main stream by the compiler. |
|
1453 |
* @throws TaskError if the outcome of the task is not as expected. |
|
1454 |
*/ |
|
1455 |
@Override |
|
1456 |
public Result run() { |
|
1457 |
Manifest m = (manifest == null) ? new Manifest() : manifest; |
|
1458 |
Attributes mainAttrs = m.getMainAttributes(); |
|
1459 |
if (mainClass != null) |
|
1460 |
mainAttrs.put(Attributes.Name.MAIN_CLASS, mainClass); |
|
1461 |
if (classpath != null) |
|
1462 |
mainAttrs.put(Attributes.Name.CLASS_PATH, classpath); |
|
1463 |
||
1464 |
StreamOutput sysOut = new StreamOutput(System.out, System::setOut); |
|
1465 |
StreamOutput sysErr = new StreamOutput(System.err, System::setErr); |
|
1466 |
||
1467 |
int rc; |
|
1468 |
Map<OutputKind, String> outputMap = new HashMap<>(); |
|
1469 |
||
1470 |
try (OutputStream os = Files.newOutputStream(jar); |
|
1471 |
JarOutputStream jos = openJar(os, m)) { |
|
1472 |
Path base = (baseDir == null) ? currDir : baseDir; |
|
1473 |
for (Path path: paths) { |
|
1474 |
Files.walkFileTree(base.resolve(path), new SimpleFileVisitor<Path>() { |
|
1475 |
@Override |
|
1476 |
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { |
|
1477 |
try { |
|
27389
301be76491af
8063074: test/tools/javac/plugin/showType/Test.java fails on Windows
jjg
parents:
27385
diff
changeset
|
1478 |
String p = base.relativize(file) |
301be76491af
8063074: test/tools/javac/plugin/showType/Test.java fails on Windows
jjg
parents:
27385
diff
changeset
|
1479 |
.normalize() |
301be76491af
8063074: test/tools/javac/plugin/showType/Test.java fails on Windows
jjg
parents:
27385
diff
changeset
|
1480 |
.toString() |
301be76491af
8063074: test/tools/javac/plugin/showType/Test.java fails on Windows
jjg
parents:
27385
diff
changeset
|
1481 |
.replace(File.separatorChar, '/'); |
301be76491af
8063074: test/tools/javac/plugin/showType/Test.java fails on Windows
jjg
parents:
27385
diff
changeset
|
1482 |
JarEntry e = new JarEntry(p); |
26100 | 1483 |
jos.putNextEntry(e); |
1484 |
jos.write(Files.readAllBytes(file)); |
|
1485 |
jos.closeEntry(); |
|
1486 |
return FileVisitResult.CONTINUE; |
|
1487 |
} catch (IOException e) { |
|
1488 |
System.err.println("Error adding " + file + " to jar file: " + e); |
|
1489 |
return FileVisitResult.TERMINATE; |
|
1490 |
} |
|
1491 |
} |
|
1492 |
}); |
|
1493 |
} |
|
1494 |
rc = 0; |
|
1495 |
} catch (IOException e) { |
|
1496 |
System.err.println("Error opening " + jar + ": " + e); |
|
1497 |
rc = 1; |
|
1498 |
} finally { |
|
1499 |
outputMap.put(OutputKind.STDOUT, sysOut.close()); |
|
1500 |
outputMap.put(OutputKind.STDERR, sysErr.close()); |
|
1501 |
} |
|
1502 |
return checkExit(new Result(this, rc, outputMap)); |
|
1503 |
} |
|
1504 |
||
1505 |
private JarOutputStream openJar(OutputStream os, Manifest m) throws IOException { |
|
1506 |
if (m == null || m.getMainAttributes().isEmpty() && m.getEntries().isEmpty()) { |
|
1507 |
return new JarOutputStream(os); |
|
1508 |
} else { |
|
1509 |
if (m.getMainAttributes().get(Attributes.Name.MANIFEST_VERSION) == null) |
|
1510 |
m.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); |
|
1511 |
return new JarOutputStream(os, m); |
|
1512 |
} |
|
1513 |
} |
|
1514 |
||
1515 |
} |
|
1516 |
||
1517 |
/** |
|
1518 |
* A task to configure and run the Java launcher. |
|
1519 |
*/ |
|
1520 |
public class JavaTask extends AbstractTask<JavaTask> { |
|
1521 |
boolean includeStandardOptions = true; |
|
1522 |
private String classpath; |
|
1523 |
private List<String> vmOptions; |
|
1524 |
private String className; |
|
1525 |
private List<String> classArgs; |
|
1526 |
||
1527 |
/** |
|
1528 |
* Create a task to run the Java launcher, using {@code EXEC} mode. |
|
1529 |
*/ |
|
1530 |
public JavaTask() { |
|
1531 |
super(Mode.EXEC); |
|
1532 |
} |
|
1533 |
||
1534 |
/** |
|
1535 |
* Sets the classpath. |
|
1536 |
* @param classpath the classpath |
|
1537 |
* @return this task object |
|
1538 |
*/ |
|
1539 |
public JavaTask classpath(String classpath) { |
|
1540 |
this.classpath = classpath; |
|
1541 |
return this; |
|
1542 |
} |
|
1543 |
||
1544 |
/** |
|
1545 |
* Sets the VM options. |
|
1546 |
* @param vmOptions the options |
|
1547 |
* @return this task object |
|
1548 |
*/ |
|
1549 |
public JavaTask vmOptions(String... vmOptions) { |
|
1550 |
this.vmOptions = Arrays.asList(vmOptions); |
|
1551 |
return this; |
|
1552 |
} |
|
1553 |
||
1554 |
/** |
|
1555 |
* Sets the name of the class to be executed. |
|
1556 |
* @param className the name of the class |
|
1557 |
* @return this task object |
|
1558 |
*/ |
|
1559 |
public JavaTask className(String className) { |
|
1560 |
this.className = className; |
|
1561 |
return this; |
|
1562 |
} |
|
1563 |
||
1564 |
/** |
|
1565 |
* Sets the arguments for the class to be executed. |
|
1566 |
* @param classArgs the arguments |
|
1567 |
* @return this task object |
|
1568 |
*/ |
|
1569 |
public JavaTask classArgs(String... classArgs) { |
|
1570 |
this.classArgs = Arrays.asList(classArgs); |
|
1571 |
return this; |
|
1572 |
} |
|
1573 |
||
1574 |
/** |
|
26392
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1575 |
* Sets whether or not the standard VM and java options for the test should be passed |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1576 |
* to the new VM instance. If this method is not called, the default behavior is that |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1577 |
* the options will be passed to the new VM instance. |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1578 |
* |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1579 |
* @param includeStandardOptions whether or not the standard VM and java options for |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1580 |
* the test should be passed to the new VM instance. |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1581 |
* @return this task object |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1582 |
*/ |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1583 |
public JavaTask includeStandardOptions(boolean includeStandardOptions) { |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1584 |
this.includeStandardOptions = includeStandardOptions; |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1585 |
return this; |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1586 |
} |
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1587 |
|
2bda2002e2f2
8047675: tools/javac/defaultMethods/Assertions.java fails if run with -enableassertions (-ea)
jlahoda
parents:
26100
diff
changeset
|
1588 |
/** |
26100 | 1589 |
* {@inheritDoc} |
1590 |
* @return the name "java" |
|
1591 |
*/ |
|
1592 |
@Override |
|
1593 |
public String name() { |
|
1594 |
return "java"; |
|
1595 |
} |
|
1596 |
||
1597 |
/** |
|
1598 |
* Calls the Java launcher with the arguments as currently configured. |
|
1599 |
* @return a Result object indicating the outcome of the task |
|
1600 |
* and the content of any output written to stdout or stderr. |
|
1601 |
* @throws TaskError if the outcome of the task is not as expected. |
|
1602 |
*/ |
|
1603 |
@Override |
|
1604 |
public Result run() { |
|
1605 |
List<String> args = new ArrayList<>(); |
|
1606 |
args.add(getJDKTool("java").toString()); |
|
1607 |
if (includeStandardOptions) { |
|
1608 |
args.addAll(split(System.getProperty("test.vm.opts"), " +")); |
|
1609 |
args.addAll(split(System.getProperty("test.java.opts"), " +")); |
|
1610 |
} |
|
1611 |
if (classpath != null) { |
|
1612 |
args.add("-classpath"); |
|
1613 |
args.add(classpath); |
|
1614 |
} |
|
1615 |
if (vmOptions != null) |
|
1616 |
args.addAll(vmOptions); |
|
1617 |
if (className != null) |
|
1618 |
args.add(className); |
|
1619 |
if (classArgs != null) |
|
1620 |
args.addAll(classArgs); |
|
1621 |
ProcessBuilder pb = getProcessBuilder(); |
|
1622 |
pb.command(args); |
|
1623 |
try { |
|
1624 |
return runProcess(ToolBox.this, this, pb.start()); |
|
1625 |
} catch (IOException | InterruptedException e) { |
|
1626 |
throw new Error(e); |
|
1627 |
} |
|
1628 |
} |
|
1629 |
} |
|
1630 |
||
1631 |
/** |
|
1632 |
* A task to configure and run a general command. |
|
1633 |
*/ |
|
1634 |
public class ExecTask extends AbstractTask<ExecTask> { |
|
1635 |
private final String command; |
|
1636 |
private List<String> args; |
|
1637 |
||
1638 |
/** |
|
1639 |
* Create a task to execute a given command, to be run using {@code EXEC} mode. |
|
1640 |
* @param command the command to be executed |
|
1641 |
*/ |
|
1642 |
public ExecTask(String command) { |
|
1643 |
super(Mode.EXEC); |
|
1644 |
this.command = command; |
|
1645 |
} |
|
1646 |
||
1647 |
/** |
|
1648 |
* Create a task to execute a given command, to be run using {@code EXEC} mode. |
|
1649 |
* @param command the command to be executed |
|
1650 |
*/ |
|
1651 |
public ExecTask(Path command) { |
|
1652 |
super(Mode.EXEC); |
|
1653 |
this.command = command.toString(); |
|
1654 |
} |
|
1655 |
||
1656 |
/** |
|
1657 |
* Sets the arguments for the command to be executed |
|
1658 |
* @param args the arguments |
|
1659 |
* @return this task object |
|
1660 |
*/ |
|
1661 |
public ExecTask args(String... args) { |
|
1662 |
this.args = Arrays.asList(args); |
|
1663 |
return this; |
|
1664 |
} |
|
1665 |
||
1666 |
/** |
|
1667 |
* {@inheritDoc} |
|
1668 |
* @return the name "exec" |
|
1669 |
*/ |
|
1670 |
@Override |
|
1671 |
public String name() { |
|
1672 |
return "exec"; |
|
1673 |
} |
|
1674 |
||
1675 |
/** |
|
1676 |
* Calls the command with the arguments as currently configured. |
|
1677 |
* @return a Result object indicating the outcome of the task |
|
1678 |
* and the content of any output written to stdout or stderr. |
|
1679 |
* @throws TaskError if the outcome of the task is not as expected. |
|
1680 |
*/ |
|
1681 |
@Override |
|
1682 |
public Result run() { |
|
1683 |
List<String> cmdArgs = new ArrayList<>(); |
|
1684 |
cmdArgs.add(command); |
|
1685 |
if (args != null) |
|
1686 |
cmdArgs.addAll(args); |
|
1687 |
ProcessBuilder pb = getProcessBuilder(); |
|
1688 |
pb.command(cmdArgs); |
|
1689 |
try { |
|
1690 |
return runProcess(ToolBox.this, this, pb.start()); |
|
1691 |
} catch (IOException | InterruptedException e) { |
|
1692 |
throw new Error(e); |
|
1693 |
} |
|
1694 |
} |
|
1695 |
} |
|
1696 |
||
1697 |
/** |
|
1698 |
* An in-memory Java source file. |
|
1699 |
* It is able to extract the file name from simple source text using |
|
1700 |
* regular expressions. |
|
1701 |
*/ |
|
1702 |
public static class JavaSource extends SimpleJavaFileObject { |
|
1703 |
private final String source; |
|
1704 |
||
1705 |
/** |
|
1706 |
* Creates a in-memory file object for Java source code. |
|
1707 |
* @param className the name of the class |
|
1708 |
* @param source the source text |
|
1709 |
*/ |
|
1710 |
public JavaSource(String className, String source) { |
|
1711 |
super(URI.create(className), JavaFileObject.Kind.SOURCE); |
|
1712 |
this.source = source; |
|
1713 |
} |
|
1714 |
||
1715 |
/** |
|
1716 |
* Creates a in-memory file object for Java source code. |
|
1717 |
* The name of the class will be inferred from the source code. |
|
1718 |
* @param source the source text |
|
1719 |
*/ |
|
1720 |
public JavaSource(String source) { |
|
1721 |
super(URI.create(getJavaFileNameFromSource(source)), |
|
1722 |
JavaFileObject.Kind.SOURCE); |
|
1723 |
this.source = source; |
|
1724 |
} |
|
1725 |
||
1726 |
/** |
|
1727 |
* Writes the source code to a file in the current directory. |
|
1728 |
* @throws IOException if there is a problem writing the file |
|
1729 |
*/ |
|
1730 |
public void write() throws IOException { |
|
1731 |
write(currDir); |
|
1732 |
} |
|
1733 |
||
1734 |
/** |
|
1735 |
* Writes the source code to a file in a specified directory. |
|
1736 |
* @param dir the directory |
|
1737 |
* @throws IOException if there is a problem writing the file |
|
1738 |
*/ |
|
1739 |
public void write(Path dir) throws IOException { |
|
1740 |
Path file = dir.resolve(getJavaFileNameFromSource(source)); |
|
1741 |
Files.createDirectories(file.getParent()); |
|
1742 |
try (BufferedWriter out = Files.newBufferedWriter(file)) { |
|
1743 |
out.write(source.replace("\n", lineSeparator)); |
|
1744 |
} |
|
1745 |
} |
|
1746 |
||
1747 |
@Override |
|
1748 |
public CharSequence getCharContent(boolean ignoreEncodingErrors) { |
|
1749 |
return source; |
|
1750 |
} |
|
1751 |
||
1752 |
private static Pattern packagePattern = |
|
1753 |
Pattern.compile("package\\s+(((?:\\w+\\.)*)(?:\\w+))"); |
|
1754 |
private static Pattern classPattern = |
|
1755 |
Pattern.compile("(?:public\\s+)?(?:class|enum|interface)\\s+(\\w+)"); |
|
1756 |
||
1757 |
/** |
|
1758 |
* Extracts the Java file name from the class declaration. |
|
1759 |
* This method is intended for simple files and uses regular expressions, |
|
1760 |
* so comments matching the pattern can make the method fail. |
|
1761 |
*/ |
|
1762 |
static String getJavaFileNameFromSource(String source) { |
|
1763 |
String packageName = null; |
|
1764 |
||
1765 |
Matcher matcher = packagePattern.matcher(source); |
|
1766 |
if (matcher.find()) |
|
1767 |
packageName = matcher.group(1).replace(".", "/"); |
|
1768 |
||
1769 |
matcher = classPattern.matcher(source); |
|
1770 |
if (matcher.find()) { |
|
1771 |
String className = matcher.group(1) + ".java"; |
|
1772 |
return (packageName == null) ? className : packageName + "/" + className; |
|
1773 |
} else { |
|
1774 |
throw new Error("Could not extract the java class " + |
|
1775 |
"name from the provided source"); |
|
1776 |
} |
|
1777 |
} |
|
1778 |
} |
|
1779 |
||
1780 |
/** |
|
1781 |
* Extracts the Java file name from the class declaration. |
|
1782 |
* This method is intended for simple files and uses regular expressions, |
|
1783 |
* so comments matching the pattern can make the method fail. |
|
1784 |
* @deprecated This is a legacy method for compatibility with ToolBox v1. |
|
1785 |
* Use {@link JavaSource#getName JavaSource.getName} instead. |
|
1786 |
* @param source the source text |
|
1787 |
* @return the Java file name inferred from the source |
|
1788 |
*/ |
|
1789 |
@Deprecated |
|
1790 |
public static String getJavaFileNameFromSource(String source) { |
|
1791 |
return JavaSource.getJavaFileNameFromSource(source); |
|
1792 |
} |
|
1793 |
||
1794 |
/** |
|
1795 |
* A memory file manager, for saving generated files in memory. |
|
1796 |
* The file manager delegates to a separate file manager for listing and |
|
1797 |
* reading input files. |
|
1798 |
*/ |
|
1799 |
public static class MemoryFileManager extends ForwardingJavaFileManager { |
|
1800 |
private interface Content { |
|
1801 |
byte[] getBytes(); |
|
1802 |
String getString(); |
|
1803 |
} |
|
1804 |
||
1805 |
/** |
|
1806 |
* Maps binary class names to generated content. |
|
1807 |
*/ |
|
1808 |
final Map<Location, Map<String, Content>> files; |
|
1809 |
||
1810 |
/** |
|
1811 |
* Construct a memory file manager which stores output files in memory, |
|
1812 |
* and delegates to a default file manager for input files. |
|
1813 |
*/ |
|
1814 |
public MemoryFileManager() { |
|
1815 |
this(JavacTool.create().getStandardFileManager(null, null, null)); |
|
1816 |
} |
|
1817 |
||
1818 |
/** |
|
1819 |
* Construct a memory file manager which stores output files in memory, |
|
1820 |
* and delegates to a specified file manager for input files. |
|
1821 |
* @param fileManager the file manager to be used for input files |
|
1822 |
*/ |
|
1823 |
public MemoryFileManager(JavaFileManager fileManager) { |
|
1824 |
super(fileManager); |
|
1825 |
files = new HashMap<>(); |
|
1826 |
} |
|
1827 |
||
1828 |
@Override |
|
1829 |
public JavaFileObject getJavaFileForOutput(Location location, |
|
1830 |
String name, |
|
1831 |
JavaFileObject.Kind kind, |
|
1832 |
FileObject sibling) |
|
1833 |
{ |
|
1834 |
return new MemoryFileObject(location, name, kind); |
|
1835 |
} |
|
1836 |
||
1837 |
/** |
|
1838 |
* Returns the content written to a file in a given location, |
|
1839 |
* or null if no such file has been written. |
|
1840 |
* @param location the location |
|
1841 |
* @param name the name of the file |
|
1842 |
* @return the content as an array of bytes |
|
1843 |
*/ |
|
1844 |
public byte[] getFileBytes(Location location, String name) { |
|
1845 |
Content content = getFile(location, name); |
|
1846 |
return (content == null) ? null : content.getBytes(); |
|
1847 |
} |
|
1848 |
||
1849 |
/** |
|
1850 |
* Returns the content written to a file in a given location, |
|
1851 |
* or null if no such file has been written. |
|
1852 |
* @param location the location |
|
1853 |
* @param name the name of the file |
|
1854 |
* @return the content as a string |
|
1855 |
*/ |
|
1856 |
public String getFileString(Location location, String name) { |
|
1857 |
Content content = getFile(location, name); |
|
1858 |
return (content == null) ? null : content.getString(); |
|
1859 |
} |
|
1860 |
||
1861 |
private Content getFile(Location location, String name) { |
|
1862 |
Map<String, Content> filesForLocation = files.get(location); |
|
1863 |
return (filesForLocation == null) ? null : filesForLocation.get(name); |
|
1864 |
} |
|
1865 |
||
1866 |
private void save(Location location, String name, Content content) { |
|
1867 |
Map<String, Content> filesForLocation = files.get(location); |
|
1868 |
if (filesForLocation == null) |
|
1869 |
files.put(location, filesForLocation = new HashMap<>()); |
|
1870 |
filesForLocation.put(name, content); |
|
1871 |
} |
|
1872 |
||
1873 |
/** |
|
1874 |
* A writable file object stored in memory. |
|
1875 |
*/ |
|
1876 |
private class MemoryFileObject extends SimpleJavaFileObject { |
|
1877 |
private final Location location; |
|
1878 |
private final String name; |
|
1879 |
||
1880 |
/** |
|
1881 |
* Constructs a memory file object. |
|
1882 |
* @param name binary name of the class to be stored in this file object |
|
1883 |
*/ |
|
1884 |
MemoryFileObject(Location location, String name, JavaFileObject.Kind kind) { |
|
1885 |
super(URI.create("mfm:///" + name.replace('.','/') + kind.extension), |
|
1886 |
Kind.CLASS); |
|
1887 |
this.location = location; |
|
1888 |
this.name = name; |
|
1889 |
} |
|
1890 |
||
1891 |
@Override |
|
1892 |
public OutputStream openOutputStream() { |
|
1893 |
return new FilterOutputStream(new ByteArrayOutputStream()) { |
|
1894 |
@Override |
|
1895 |
public void close() throws IOException { |
|
1896 |
out.close(); |
|
1897 |
byte[] bytes = ((ByteArrayOutputStream) out).toByteArray(); |
|
1898 |
save(location, name, new Content() { |
|
1899 |
@Override |
|
1900 |
public byte[] getBytes() { |
|
1901 |
return bytes; |
|
1902 |
} |
|
1903 |
@Override |
|
1904 |
public String getString() { |
|
1905 |
return new String(bytes); |
|
1906 |
} |
|
1907 |
||
1908 |
}); |
|
1909 |
} |
|
1910 |
}; |
|
1911 |
} |
|
1912 |
||
1913 |
@Override |
|
1914 |
public Writer openWriter() { |
|
1915 |
return new FilterWriter(new StringWriter()) { |
|
1916 |
@Override |
|
1917 |
public void close() throws IOException { |
|
1918 |
out.close(); |
|
1919 |
String text = ((StringWriter) out).toString(); |
|
1920 |
save(location, name, new Content() { |
|
1921 |
@Override |
|
1922 |
public byte[] getBytes() { |
|
1923 |
return text.getBytes(); |
|
1924 |
} |
|
1925 |
@Override |
|
1926 |
public String getString() { |
|
1927 |
return text; |
|
1928 |
} |
|
1929 |
||
1930 |
}); |
|
1931 |
} |
|
1932 |
}; |
|
1933 |
} |
|
1934 |
} |
|
1935 |
||
1936 |
} |
|
1937 |
||
1938 |
} |