1 /* 2 * Copyright (c) 2018, 2024, 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 /* 25 * @test 26 * @bug 8192920 8204588 8246774 8248843 8268869 8235876 8328339 8335896 27 * @summary Test source launcher 28 * @library /tools/lib 29 * @modules jdk.compiler/com.sun.tools.javac.api 30 * jdk.compiler/com.sun.tools.javac.launcher 31 * jdk.compiler/com.sun.tools.javac.main 32 * java.base/jdk.internal.module 33 * @build toolbox.JavaTask toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox 34 * @run main SourceLauncherTest 35 */ 36 37 import java.lang.classfile.*; 38 import java.lang.classfile.attribute.ModuleResolutionAttribute; 39 import java.io.ByteArrayOutputStream; 40 import java.io.File; 41 import java.io.IOException; 42 import java.io.OutputStream; 43 import java.io.PrintStream; 44 import java.io.PrintWriter; 45 import java.io.StringWriter; 46 import java.lang.reflect.InvocationTargetException; 47 import java.nio.file.Files; 48 import java.nio.file.Path; 49 import java.nio.file.Paths; 50 import java.util.ArrayList; 51 import java.util.Collections; 52 import java.util.List; 53 import java.util.Properties; 54 import java.util.regex.Pattern; 55 56 import com.sun.tools.javac.launcher.SourceLauncher; 57 import com.sun.tools.javac.launcher.Fault; 58 59 import toolbox.JavaTask; 60 import toolbox.JavacTask; 61 import toolbox.Task; 62 import toolbox.TestRunner; 63 import toolbox.ToolBox; 64 65 import static jdk.internal.module.ClassFileConstants.WARN_INCUBATING; 66 67 public class SourceLauncherTest extends TestRunner { 68 public static void main(String... args) throws Exception { 69 SourceLauncherTest t = new SourceLauncherTest(); 70 t.runTests(m -> new Object[] { Paths.get(m.getName()) }); 71 } 72 73 SourceLauncherTest() { 74 super(System.err); 75 tb = new ToolBox(); 76 System.err.println("version: " + thisVersion); 77 } 78 79 private final ToolBox tb; 80 private static final String thisVersion = System.getProperty("java.specification.version"); 81 82 /* 83 * Positive tests. 84 */ 85 86 @Test 87 public void testHelloWorld(Path base) throws IOException { 88 tb.writeJavaFiles(base, 89 "import java.util.Arrays;\n" + 90 "class HelloWorld {\n" + 91 " public static void main(String... args) {\n" + 92 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 93 " }\n" + 94 "}"); 95 testSuccess(base.resolve("HelloWorld.java"), "Hello World! [1, 2, 3]\n"); 96 } 97 98 @Test 99 public void testHelloWorldInPackage(Path base) throws IOException { 100 tb.writeJavaFiles(base, 101 "package hello;\n" + 102 "import java.util.Arrays;\n" + 103 "class World {\n" + 104 " public static void main(String... args) {\n" + 105 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 106 " }\n" + 107 "}"); 108 testSuccess(base.resolve("hello").resolve("World.java"), "Hello World! [1, 2, 3]\n"); 109 } 110 111 @Test 112 public void testHelloWorldInPackageWithStaticImport(Path base) throws IOException { 113 tb.writeJavaFiles(base, 114 """ 115 package hello; 116 import static hello.Helper.*; 117 import java.util.Arrays; 118 class World { 119 public static void main(String... args) { 120 m(args); 121 } 122 } 123 class Helper { 124 static void m(String... args) { 125 System.out.println("Hello World! " + Arrays.toString(args)); 126 } 127 } 128 """); 129 testSuccess(base.resolve("hello").resolve("World.java"), "Hello World! [1, 2, 3]\n"); 130 } 131 132 @Test 133 public void testHelloWorldWithAux(Path base) throws IOException { 134 tb.writeJavaFiles(base, 135 "import java.util.Arrays;\n" + 136 "class HelloWorld {\n" + 137 " public static void main(String... args) {\n" + 138 " Aux.write(args);\n" + 139 " }\n" + 140 "}\n" + 141 "class Aux {\n" + 142 " static void write(String... args) {\n" + 143 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 144 " }\n" + 145 "}"); 146 testSuccess(base.resolve("HelloWorld.java"), "Hello World! [1, 2, 3]\n"); 147 } 148 149 @Test 150 public void testHelloWorldWithShebang(Path base) throws IOException { 151 tb.writeJavaFiles(base, 152 "#!/usr/bin/java --source " + thisVersion + "\n" + 153 "import java.util.Arrays;\n" + 154 "class HelloWorld {\n" + 155 " public static void main(String... args) {\n" + 156 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 157 " }\n" + 158 "}"); 159 Files.copy(base.resolve("HelloWorld.java"), base.resolve("HelloWorld")); 160 testSuccess(base.resolve("HelloWorld"), "Hello World! [1, 2, 3]\n"); 161 } 162 163 @Test 164 public void testNoAnnoProcessing(Path base) throws IOException { 165 Path annoSrc = base.resolve("annoSrc"); 166 tb.writeJavaFiles(annoSrc, 167 "import java.util.*;\n" + 168 "import javax.annotation.processing.*;\n" + 169 "import javax.lang.model.element.*;\n" + 170 "@SupportedAnnotationTypes(\"*\")\n" + 171 "public class AnnoProc extends AbstractProcessor {\n" + 172 " public boolean process(Set<? extends TypeElement> annos, RoundEnvironment rEnv) {\n" + 173 " throw new Error(\"Annotation processor should not be invoked\");\n" + 174 " }\n" + 175 "}\n"); 176 Path annoClasses = Files.createDirectories(base.resolve("classes")); 177 new JavacTask(tb) 178 .outdir(annoClasses) 179 .files(annoSrc.resolve("AnnoProc.java").toString()) 180 .run(); 181 Path serviceFile = annoClasses.resolve("META-INF").resolve("services") 182 .resolve("javax.annotation.processing.Processor"); 183 tb.writeFile(serviceFile, "AnnoProc"); 184 185 Path mainSrc = base.resolve("mainSrc"); 186 tb.writeJavaFiles(mainSrc, 187 "import java.util.Arrays;\n" + 188 "class HelloWorld {\n" + 189 " public static void main(String... args) {\n" + 190 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 191 " }\n" + 192 "}"); 193 194 List<String> javacArgs = List.of("-classpath", annoClasses.toString()); 195 List<String> classArgs = List.of("1", "2", "3"); 196 String expect = "Hello World! [1, 2, 3]\n"; 197 Result r = run(mainSrc.resolve("HelloWorld.java"), javacArgs, classArgs); 198 checkEqual("stdout", r.stdOut, expect); 199 checkEmpty("stderr", r.stdErr); 200 checkNull("exception", r.exception); 201 } 202 203 @Test 204 public void testEnablePreview(Path base) throws IOException { 205 tb.writeJavaFiles(base, 206 "import java.util.Arrays;\n" + 207 "class HelloWorld {\n" + 208 " public static void main(String... args) {\n" + 209 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 210 " }\n" + 211 "}"); 212 213 String log = new JavaTask(tb) 214 .vmOptions("--enable-preview", "--source", thisVersion) 215 .className(base.resolve("HelloWorld.java").toString()) 216 .classArgs("1", "2", "3") 217 .run(Task.Expect.SUCCESS) 218 .getOutput(Task.OutputKind.STDOUT); 219 checkEqual("stdout", log.trim(), "Hello World! [1, 2, 3]"); 220 } 221 222 @Test 223 public void testCodeSource(Path base) throws IOException { 224 tb.writeJavaFiles(base, 225 "import java.net.URL;\n" + 226 "class ShowCodeSource {\n" + 227 " public static void main(String... args) {\n" + 228 " URL u = ShowCodeSource.class.getProtectionDomain().getCodeSource().getLocation();\n" + 229 " System.out.println(u);\n" + 230 " }\n" + 231 "}"); 232 233 Path file = base.resolve("ShowCodeSource.java"); 234 String log = new JavaTask(tb) 235 .className(file.toString()) 236 .run(Task.Expect.SUCCESS) 237 .getOutput(Task.OutputKind.STDOUT); 238 checkEqual("stdout", log.trim(), file.toAbsolutePath().toUri().toURL().toString()); 239 } 240 241 @Test 242 public void testSystemProperty(Path base) throws IOException { 243 tb.writeJavaFiles(base, 244 "class ShowProperty {\n" + 245 " public static void main(String... args) {\n" + 246 " System.out.println(System.getProperty(\"jdk.launcher.sourcefile\"));\n" + 247 " }\n" + 248 "}"); 249 250 Path file = base.resolve("ShowProperty.java"); 251 String log = new JavaTask(tb) 252 .className(file.toString()) 253 .run(Task.Expect.SUCCESS) 254 .getOutput(Task.OutputKind.STDOUT); 255 checkEqual("stdout", log.trim(), file.toAbsolutePath().toString()); 256 } 257 258 @Test 259 public void testThreadContextClassLoader(Path base) throws IOException { 260 tb.writeJavaFiles(base, //language=java 261 """ 262 class ThreadContextClassLoader { 263 public static void main(String... args) { 264 var expected = ThreadContextClassLoader.class.getClassLoader(); 265 var actual = Thread.currentThread().getContextClassLoader(); 266 System.out.println(expected == actual); 267 } 268 } 269 """); 270 271 Path file = base.resolve("ThreadContextClassLoader.java"); 272 String log = new JavaTask(tb) 273 .className(file.toString()) 274 .run(Task.Expect.SUCCESS) 275 .getOutput(Task.OutputKind.STDOUT); 276 checkEqual("stdout", log.trim(), "true"); 277 } 278 279 void testSuccess(Path file, String expect) throws IOException { 280 Result r = run(file, Collections.emptyList(), List.of("1", "2", "3")); 281 checkEqual("stdout", r.stdOut, expect); 282 checkEmpty("stderr", r.stdErr); 283 checkNull("exception", r.exception); 284 } 285 286 /* 287 * Negative tests: such as cannot find or execute main method. 288 */ 289 290 @Test 291 public void testHelloWorldWithShebangJava(Path base) throws IOException { 292 tb.writeJavaFiles(base, 293 "#!/usr/bin/java --source " + thisVersion + "\n" + 294 "import java.util.Arrays;\n" + 295 "class HelloWorld {\n" + 296 " public static void main(String... args) {\n" + 297 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 298 " }\n" + 299 "}"); 300 Path file = base.resolve("HelloWorld.java"); 301 testError(file, 302 file + ":1: error: illegal character: '#'\n" + 303 "#!/usr/bin/java --source " + thisVersion + "\n" + 304 "^\n" + 305 file + ":1: error: class, interface, enum, or record expected\n" + 306 "#!/usr/bin/java --source " + thisVersion + "\n" + 307 " ^\n" + 308 "2 errors\n", 309 "error: compilation failed"); 310 } 311 312 @Test 313 public void testNoClass(Path base) throws IOException { 314 var path = Files.createDirectories(base.resolve("p")); 315 Path file = path.resolve("NoClass.java"); 316 Files.write(file, List.of("package p;")); 317 testError(file, "", "error: no class declared in source file"); 318 } 319 320 @Test 321 public void testMismatchOfPathAndPackage(Path base) throws IOException { 322 Files.createDirectories(base); 323 Path file = base.resolve("MismatchOfPathAndPackage.java"); 324 Files.write(file, List.of("package p; class MismatchOfPathAndPackage {}")); 325 testError(file, "", "error: end of path to source file does not match its package name p: " + file); 326 } 327 328 @Test 329 public void testLoadClass(Path base) throws IOException { 330 Path src1 = base.resolve("src1"); 331 Path file1 = src1.resolve("LoadClass.java"); 332 tb.writeJavaFiles(src1, 333 "class LoadClass {\n" 334 + " public static void main(String... args) {\n" 335 + " System.out.println(\"on classpath\");\n" 336 + " };\n" 337 + "}\n"); 338 Path classes1 = Files.createDirectories(base.resolve("classes")); 339 new JavacTask(tb) 340 .outdir(classes1) 341 .files(file1) 342 .run(); 343 String log1 = new JavaTask(tb) 344 .classpath(classes1.toString()) 345 .className("LoadClass") 346 .run(Task.Expect.SUCCESS) 347 .getOutput(Task.OutputKind.STDOUT); 348 checkEqual("stdout", log1.trim(), 349 "on classpath"); 350 351 Path src2 = base.resolve("src2"); 352 Path file2 = src2.resolve("LoadClass.java"); 353 tb.writeJavaFiles(src2, 354 "class LoadClass {\n" 355 + " public static void main(String... args) {\n" 356 + " System.out.println(\"in source file\");\n" 357 + " };\n" 358 + "}\n"); 359 String log2 = new JavaTask(tb) 360 .classpath(classes1.toString()) 361 .className(file2.toString()) 362 .run(Task.Expect.SUCCESS) 363 .getOutput(Task.OutputKind.STDOUT); 364 checkEqual("stdout", log2.trim(), 365 "in source file"); 366 } 367 368 @Test 369 public void testGetResource(Path base) throws IOException { 370 Path src = base.resolve("src"); 371 Path file = src.resolve("GetResource.java"); 372 tb.writeJavaFiles(src, 373 "class GetResource {\n" 374 + " public static void main(String... args) {\n" 375 + " System.out.println(GetResource.class.getClassLoader().getResource(\"GetResource.class\"));\n" 376 + " };\n" 377 + "}\n"); 378 Path classes = Files.createDirectories(base.resolve("classes")); 379 new JavacTask(tb) 380 .outdir(classes) 381 .files(file) 382 .run(); 383 384 String log = new JavaTask(tb) 385 .classpath(classes.toString()) 386 .className(file.toString()) 387 .run(Task.Expect.SUCCESS) 388 .getOutput(Task.OutputKind.STDOUT); 389 checkMatch("stdout", log.trim(), 390 Pattern.compile("sourcelauncher-memoryclassloader[0-9]+:GetResource.class")); 391 } 392 393 @Test 394 public void testGetResources(Path base) throws IOException { 395 Path src = base.resolve("src"); 396 Path file = src.resolve("GetResources.java"); 397 tb.writeJavaFiles(src, 398 "import java.io.*; import java.net.*; import java.util.*;\n" 399 + "class GetResources {\n" 400 + " public static void main(String... args) throws IOException {\n" 401 + " Enumeration<URL> e =\n" 402 + " GetResources.class.getClassLoader().getResources(\"GetResources.class\");\n" 403 + " while (e.hasMoreElements()) System.out.println(e.nextElement());\n" 404 + " };\n" 405 + "}\n"); 406 Path classes = Files.createDirectories(base.resolve("classes")); 407 new JavacTask(tb) 408 .outdir(classes) 409 .files(file) 410 .run(); 411 412 List<String> log = new JavaTask(tb) 413 .classpath(classes.toString()) 414 .className(file.toString()) 415 .run(Task.Expect.SUCCESS) 416 .getOutputLines(Task.OutputKind.STDOUT); 417 checkMatch("stdout:0", log.get(0).trim(), 418 Pattern.compile("sourcelauncher-memoryclassloader[0-9]+:GetResources.class")); 419 checkMatch("stdout:1", log.get(1).trim(), 420 Pattern.compile("file:/.*/testGetResources/classes/GetResources.class")); 421 } 422 423 @Test 424 public void testSyntaxErr(Path base) throws IOException { 425 tb.writeJavaFiles(base, "class SyntaxErr {"); 426 Path file = base.resolve("SyntaxErr.java"); 427 testError(file, 428 file + ":1: error: reached end of file while parsing\n" + 429 "class SyntaxErr {\n" + 430 " ^\n" + 431 "1 error\n", 432 "error: compilation failed"); 433 } 434 435 @Test 436 public void testNoSourceOnClassPath(Path base) throws IOException { 437 Path extraSrc = base.resolve("extraSrc"); 438 tb.writeJavaFiles(extraSrc, 439 "public class Extra {\n" + 440 " static final String MESSAGE = \"Hello World\";\n" + 441 "}\n"); 442 443 Path mainSrc = base.resolve("mainSrc"); 444 tb.writeJavaFiles(mainSrc, 445 "import java.util.Arrays;\n" + 446 "class HelloWorld {\n" + 447 " public static void main(String... args) {\n" + 448 " System.out.println(Extra.MESSAGE + Arrays.toString(args));\n" + 449 " }\n" + 450 "}"); 451 452 List<String> javacArgs = List.of("-classpath", extraSrc.toString()); 453 List<String> classArgs = List.of("1", "2", "3"); 454 String FS = File.separator; 455 String expectStdErr = 456 "testNoSourceOnClassPath" + FS + "mainSrc" + FS + "HelloWorld.java:4: error: cannot find symbol\n" + 457 " System.out.println(Extra.MESSAGE + Arrays.toString(args));\n" + 458 " ^\n" + 459 " symbol: variable Extra\n" + 460 " location: class HelloWorld\n" + 461 "1 error\n"; 462 Result r = run(mainSrc.resolve("HelloWorld.java"), javacArgs, classArgs); 463 checkEmpty("stdout", r.stdOut); 464 checkEqual("stderr", r.stdErr, expectStdErr); 465 checkFault("exception", r.exception, "error: compilation failed"); 466 } 467 468 @Test 469 public void testClassNotFound(Path base) throws IOException { 470 Path src = base.resolve("src"); 471 Path file = src.resolve("ClassNotFound.java"); 472 tb.writeJavaFiles(src, 473 "class ClassNotFound {\n" 474 + " public static void main(String... args) {\n" 475 + " try {\n" 476 + " Class.forName(\"NoSuchClass\");\n" 477 + " System.out.println(\"no exception\");\n" 478 + " System.exit(1);\n" 479 + " } catch (ClassNotFoundException e) {\n" 480 + " System.out.println(\"Expected exception thrown: \" + e);\n" 481 + " }\n" 482 + " };\n" 483 + "}\n"); 484 Path classes = Files.createDirectories(base.resolve("classes")); 485 new JavacTask(tb) 486 .outdir(classes) 487 .files(file) 488 .run(); 489 490 String log = new JavaTask(tb) 491 .classpath(classes.toString()) 492 .className(file.toString()) 493 .run(Task.Expect.SUCCESS) 494 .getOutput(Task.OutputKind.STDOUT); 495 checkEqual("stdout", log.trim(), 496 "Expected exception thrown: java.lang.ClassNotFoundException: NoSuchClass"); 497 } 498 499 // For any source file that is invoked through the OS shebang mechanism, invalid shebang 500 // lines will be caught and handled by the OS, before the launcher is even invoked. 501 // However, if such a file is passed directly to the launcher, perhaps using the --source 502 // option, a well-formed shebang line will be removed but a badly-formed one will be not be 503 // removed and will cause compilation errors. 504 @Test 505 public void testBadShebang(Path base) throws IOException { 506 tb.writeJavaFiles(base, 507 "#/usr/bin/java --source " + thisVersion + "\n" + 508 "import java.util.Arrays;\n" + 509 "class HelloWorld {\n" + 510 " public static void main(String... args) {\n" + 511 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 512 " }\n" + 513 "}"); 514 Path file = base.resolve("HelloWorld.java"); 515 testError(file, 516 file + ":1: error: illegal character: '#'\n" + 517 "#/usr/bin/java --source " + thisVersion + "\n" + 518 "^\n" + 519 file + ":1: error: class, interface, enum, or record expected\n" + 520 "#/usr/bin/java --source " + thisVersion + "\n" + 521 " ^\n" + 522 "2 errors\n", 523 "error: compilation failed"); 524 } 525 526 @Test 527 public void testBadSourceOpt(Path base) throws IOException { 528 Files.createDirectories(base); 529 Path file = base.resolve("DummyClass.java"); 530 Files.write(file, List.of("class DummyClass { }")); 531 Properties sysProps = System.getProperties(); 532 Properties p = new Properties(sysProps); 533 p.setProperty("jdk.internal.javac.source", "<BAD>"); 534 System.setProperties(p); 535 try { 536 testError(file, "", "error: invalid value for --source option: <BAD>"); 537 } finally { 538 System.setProperties(sysProps); 539 } 540 } 541 542 @Test 543 public void testEnablePreviewNoSource(Path base) throws IOException { 544 tb.writeJavaFiles(base, 545 "import java.util.Arrays;\n" + 546 "class HelloWorld {\n" + 547 " public static void main(String... args) {\n" + 548 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 549 " }\n" + 550 "}"); 551 552 List<String> log = new JavaTask(tb) 553 .vmOptions("--enable-preview") 554 .className(base.resolve("HelloWorld.java").toString()) 555 .run(Task.Expect.SUCCESS) 556 .getOutputLines(Task.OutputKind.STDOUT); 557 checkEqual("stdout", log, List.of("Hello World! []")); 558 } 559 560 @Test 561 public void testNoMain(Path base) throws IOException { 562 tb.writeJavaFiles(base, "class NoMain { }"); 563 testError(base.resolve("NoMain.java"), "", 564 "error: can't find main(String[]) method in class: NoMain"); 565 } 566 567 @Test 568 public void testMainBadParams(Path base) throws IOException { 569 tb.writeJavaFiles(base, 570 "class BadParams { public static void main() { } }"); 571 testError(base.resolve("BadParams.java"), "", 572 "error: can't find main(String[]) method in class: BadParams"); 573 } 574 575 @Test 576 public void testMainNotPublic(Path base) throws IOException { 577 tb.writeJavaFiles(base, 578 "class NotPublic { static void main(String... args) { } }"); 579 testError(base.resolve("NotPublic.java"), "", 580 "error: can't find main(String[]) method in class: NotPublic"); 581 } 582 583 @Test 584 public void testMainNotStatic(Path base) throws IOException { 585 tb.writeJavaFiles(base, 586 "class NotStatic { public void main(String... args) { } }"); 587 testError(base.resolve("NotStatic.java"), "", 588 "error: can't find main(String[]) method in class: NotStatic"); 589 } 590 591 @Test 592 public void testMainNotVoid(Path base) throws IOException { 593 tb.writeJavaFiles(base, 594 "class NotVoid { public static int main(String... args) { return 0; } }"); 595 testError(base.resolve("NotVoid.java"), "", 596 "error: can't find main(String[]) method in class: NotVoid"); 597 } 598 599 @Test 600 public void testClassInModule(Path base) throws IOException { 601 tb.writeJavaFiles(base, "package java.net; class InModule { }"); 602 Path file = base.resolve("java").resolve("net").resolve("InModule.java"); 603 testError(file, 604 file + ":1: error: package exists in another module: java.base\n" + 605 "package java.net; class InModule { }\n" + 606 "^\n" + 607 "1 error\n", 608 "error: compilation failed"); 609 } 610 611 @Test 612 public void testNoRecompileWithSuggestions(Path base) throws IOException { 613 tb.writeJavaFiles(base, 614 "class NoRecompile {\n" + 615 " void use(String s) {}\n" + 616 " void test() {\n" + 617 " use(1);\n" + 618 " }\n" + 619 " <T> void test(T t, Object o) {\n" + 620 " T t1 = (T) o;\n" + 621 " }\n" + 622 " static class Generic<T> {\n" + 623 " T t;\n" + 624 " void raw(Generic raw) {\n" + 625 " raw.t = \"\";\n" + 626 " }\n" + 627 " }\n" + 628 " void deprecation() {\n" + 629 " Thread.currentThread().stop();\n" + 630 " }\n" + 631 " void preview(Object o) {\n" + 632 " if (o instanceof String s) {\n" + 633 " System.out.println(s);\n" + 634 " }\n" + 635 " }\n" + 636 "}"); 637 Result r = run(base.resolve("NoRecompile.java"), Collections.emptyList(), Collections.emptyList()); 638 if (r.stdErr.contains("recompile with")) { 639 error("Unexpected recompile suggestions in error output: " + r.stdErr); 640 } 641 } 642 643 @Test 644 public void testNoOptionsWarnings(Path base) throws IOException { 645 tb.writeJavaFiles(base, "public class Main { public static void main(String... args) {}}"); 646 String log = new JavaTask(tb) 647 .vmOptions("--source", "21") 648 .className(base.resolve("Main.java").toString()) 649 .run(Task.Expect.SUCCESS) 650 .getOutput(Task.OutputKind.STDERR); 651 652 if (log.contains("warning: [options]")) { 653 error("Unexpected options warning in error output: " + log); 654 } 655 } 656 657 void testError(Path file, String expectStdErr, String expectFault) throws IOException { 658 Result r = run(file, Collections.emptyList(), List.of("1", "2", "3")); 659 checkEmpty("stdout", r.stdOut); 660 checkEqual("stderr", r.stdErr, expectStdErr); 661 checkFault("exception", r.exception, expectFault); 662 } 663 664 /* 665 * Tests in which main throws an exception. 666 */ 667 @Test 668 public void testTargetException1(Path base) throws IOException { 669 tb.writeJavaFiles(base, 670 "import java.util.Arrays;\n" + 671 "class Thrower {\n" + 672 " public static void main(String... args) {\n" + 673 " throwWhenZero(Integer.parseInt(args[0]));\n" + 674 " }\n" + 675 " static void throwWhenZero(int arg) {\n" + 676 " if (arg == 0) throw new Error(\"zero!\");\n" + 677 " throwWhenZero(arg - 1);\n" + 678 " }\n" + 679 "}"); 680 Path file = base.resolve("Thrower.java"); 681 Result r = run(file, Collections.emptyList(), List.of("3")); 682 checkEmpty("stdout", r.stdOut); 683 checkEmpty("stderr", r.stdErr); 684 checkTrace("exception", r.exception, 685 "java.lang.Error: zero!", 686 "at Thrower.throwWhenZero(Thrower.java:7)", 687 "at Thrower.throwWhenZero(Thrower.java:8)", 688 "at Thrower.throwWhenZero(Thrower.java:8)", 689 "at Thrower.throwWhenZero(Thrower.java:8)", 690 "at Thrower.main(Thrower.java:4)"); 691 } 692 693 @Test 694 public void testNoDuplicateIncubatorWarning(Path base) throws Exception { 695 Path module = base.resolve("lib"); 696 Path moduleSrc = module.resolve("src"); 697 Path moduleClasses = module.resolve("classes"); 698 Files.createDirectories(moduleClasses); 699 tb.cleanDirectory(moduleClasses); 700 tb.writeJavaFiles(moduleSrc, "module test {}"); 701 new JavacTask(tb) 702 .outdir(moduleClasses) 703 .files(tb.findJavaFiles(moduleSrc)) 704 .run() 705 .writeAll(); 706 markModuleAsIncubator(moduleClasses.resolve("module-info.class")); 707 tb.writeJavaFiles(base, "public class Main { public static void main(String... args) {}}"); 708 String log = new JavaTask(tb) 709 .vmOptions("--module-path", moduleClasses.toString(), 710 "--add-modules", "test") 711 .className(base.resolve("Main.java").toString()) 712 .run(Task.Expect.SUCCESS) 713 .writeAll() 714 .getOutput(Task.OutputKind.STDERR); 715 716 int numberOfWarnings = log.split("WARNING").length - 1; 717 718 if (log.contains("warning:") || numberOfWarnings != 1) { 719 error("Unexpected warning in error output: " + log); 720 } 721 722 List<String> compileLog = new JavacTask(tb) 723 .options("--module-path", moduleClasses.toString(), 724 "--add-modules", "test", 725 "-XDrawDiagnostics", 726 "-XDsourceLauncher", 727 "-XDshould-stop.at=FLOW") 728 .files(base.resolve("Main.java").toString()) 729 .run(Task.Expect.SUCCESS) 730 .writeAll() 731 .getOutputLines(Task.OutputKind.DIRECT); 732 733 List<String> expectedOutput = List.of( 734 "- compiler.warn.incubating.modules: test", 735 "1 warning" 736 ); 737 738 if (!expectedOutput.equals(compileLog)) { 739 error("Unexpected options : " + compileLog); 740 } 741 } 742 //where: 743 private static void markModuleAsIncubator(Path moduleInfoFile) throws Exception { 744 ClassModel cf = ClassFile.of().parse(moduleInfoFile); 745 ModuleResolutionAttribute newAttr = ModuleResolutionAttribute.of(WARN_INCUBATING); 746 byte[] newBytes = ClassFile.of().transformClass(cf, 747 ClassTransform.endHandler(classBuilder -> classBuilder.with(newAttr))); 748 try (OutputStream out = Files.newOutputStream(moduleInfoFile)) { 749 out.write(newBytes); 750 } 751 } 752 753 Result run(Path file, List<String> runtimeArgs, List<String> appArgs) { 754 List<String> args = new ArrayList<>(); 755 args.add(file.toString()); 756 args.addAll(appArgs); 757 758 PrintStream prev = System.out; 759 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 760 try (PrintStream out = new PrintStream(baos, true)) { 761 System.setOut(out); 762 StringWriter sw = new StringWriter(); 763 try (PrintWriter err = new PrintWriter(sw, true)) { 764 SourceLauncher m = new SourceLauncher(err); 765 m.run(toArray(runtimeArgs), toArray(args)); 766 return new Result(baos.toString(), sw.toString(), null); 767 } catch (Throwable t) { 768 return new Result(baos.toString(), sw.toString(), t); 769 } 770 } finally { 771 System.setOut(prev); 772 } 773 } 774 775 void checkEqual(String name, String found, String expect) { 776 expect = expect.replace("\n", tb.lineSeparator); 777 out.println(name + ": " + found); 778 if (!expect.equals(found)) { 779 error("Unexpected output; expected: " + expect); 780 } 781 } 782 783 void checkContains(String name, String found, String expect) { 784 expect = expect.replace("\n", tb.lineSeparator); 785 out.println(name + ": " + found); 786 if (!found.contains(expect)) { 787 error("Expected output not found: " + expect); 788 } 789 } 790 791 void checkEqual(String name, List<String> found, List<String> expect) { 792 out.println(name + ": " + found); 793 tb.checkEqual(expect, found); 794 } 795 796 void checkMatch(String name, String found, Pattern expect) { 797 out.println(name + ": " + found); 798 if (!expect.matcher(found).matches()) { 799 error("Unexpected output; expected match for: " + expect); 800 } 801 } 802 803 void checkEmpty(String name, String found) { 804 out.println(name + ": " + found); 805 if (!found.isEmpty()) { 806 error("Unexpected output; expected empty string"); 807 } 808 } 809 810 void checkNull(String name, Throwable found) { 811 out.println(name + ": " + found); 812 if (found != null) { 813 error("Unexpected exception; expected null"); 814 } 815 } 816 817 void checkFault(String name, Throwable found, String expect) { 818 expect = expect.replace("\n", tb.lineSeparator); 819 out.println(name + ": " + found); 820 if (found == null) { 821 error("No exception thrown; expected Fault"); 822 } else { 823 if (!(found instanceof Fault)) { 824 error("Unexpected exception; expected Fault"); 825 } 826 if (!(found.getMessage().equals(expect))) { 827 error("Unexpected detail message; expected: " + expect); 828 } 829 } 830 } 831 832 void checkTrace(String name, Throwable found, String... expect) { 833 if (!(found instanceof InvocationTargetException)) { 834 error("Unexpected exception; expected InvocationTargetException"); 835 out.println("Found:"); 836 found.printStackTrace(out); 837 } 838 StringWriter sw = new StringWriter(); 839 try (PrintWriter pw = new PrintWriter(sw)) { 840 ((InvocationTargetException) found).getTargetException().printStackTrace(pw); 841 } 842 String trace = sw.toString(); 843 out.println(name + ":\n" + trace); 844 String[] traceLines = trace.trim().split("[\r\n]+\\s+"); 845 try { 846 tb.checkEqual(List.of(traceLines), List.of(expect)); 847 } catch (Error e) { 848 error(e.getMessage()); 849 } 850 } 851 852 String[] toArray(List<String> list) { 853 return list.toArray(new String[list.size()]); 854 } 855 856 record Result(String stdOut, String stdErr, Throwable exception) {} 857 }