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