1 /* 2 * Copyright (c) 2018, 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 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 * @build toolbox.JavaTask toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox 33 * @run main SourceLauncherTest 34 */ 35 36 import java.io.ByteArrayOutputStream; 37 import java.io.File; 38 import java.io.IOException; 39 import java.io.PrintStream; 40 import java.io.PrintWriter; 41 import java.io.StringWriter; 42 import java.lang.reflect.InvocationTargetException; 43 import java.nio.file.Files; 44 import java.nio.file.Path; 45 import java.nio.file.Paths; 46 import java.util.ArrayList; 47 import java.util.Collections; 48 import java.util.List; 49 import java.util.Properties; 50 51 import com.sun.tools.javac.launcher.Main; 52 53 import toolbox.JavaTask; 54 import toolbox.JavacTask; 55 import toolbox.Task; 56 import toolbox.TestRunner; 57 import toolbox.TestRunner; 58 import toolbox.ToolBox; 59 60 public class SourceLauncherTest extends TestRunner { 61 public static void main(String... args) throws Exception { 62 SourceLauncherTest t = new SourceLauncherTest(); 63 t.runTests(m -> new Object[] { Paths.get(m.getName()) }); 64 } 65 66 SourceLauncherTest() { 67 super(System.err); 68 tb = new ToolBox(); 69 System.err.println("version: " + thisVersion); 70 } 71 72 private final ToolBox tb; 73 private static final String thisVersion = System.getProperty("java.specification.version"); 74 75 /* 76 * Positive tests. 77 */ 78 79 @Test 80 public void testHelloWorld(Path base) throws IOException { 81 tb.writeJavaFiles(base, 82 "import java.util.Arrays;\n" + 83 "class HelloWorld {\n" + 84 " public static void main(String... args) {\n" + 85 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 86 " }\n" + 87 "}"); 88 testSuccess(base.resolve("HelloWorld.java"), "Hello World! [1, 2, 3]\n"); 89 } 90 91 @Test 92 public void testHelloWorldInPackage(Path base) throws IOException { 93 tb.writeJavaFiles(base, 94 "package hello;\n" + 95 "import java.util.Arrays;\n" + 96 "class World {\n" + 97 " public static void main(String... args) {\n" + 98 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 99 " }\n" + 100 "}"); 101 testSuccess(base.resolve("hello").resolve("World.java"), "Hello World! [1, 2, 3]\n"); 102 } 103 104 @Test 105 public void testHelloWorldWithAux(Path base) throws IOException { 106 tb.writeJavaFiles(base, 107 "import java.util.Arrays;\n" + 108 "class HelloWorld {\n" + 109 " public static void main(String... args) {\n" + 110 " Aux.write(args);\n" + 111 " }\n" + 112 "}\n" + 113 "class Aux {\n" + 114 " static void write(String... args) {\n" + 115 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 116 " }\n" + 117 "}"); 118 testSuccess(base.resolve("HelloWorld.java"), "Hello World! [1, 2, 3]\n"); 119 } 120 121 @Test 122 public void testHelloWorldWithShebang(Path base) throws IOException { 123 tb.writeJavaFiles(base, 124 "#!/usr/bin/java --source " + thisVersion + "\n" + 125 "import java.util.Arrays;\n" + 126 "class HelloWorld {\n" + 127 " public static void main(String... args) {\n" + 128 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 129 " }\n" + 130 "}"); 131 Files.copy(base.resolve("HelloWorld.java"), base.resolve("HelloWorld")); 132 testSuccess(base.resolve("HelloWorld"), "Hello World! [1, 2, 3]\n"); 133 } 134 135 @Test 136 public void testNoAnnoProcessing(Path base) throws IOException { 137 Path annoSrc = base.resolve("annoSrc"); 138 tb.writeJavaFiles(annoSrc, 139 "import java.util.*;\n" + 140 "import javax.annotation.processing.*;\n" + 141 "import javax.lang.model.element.*;\n" + 142 "@SupportedAnnotationTypes(\"*\")\n" + 143 "public class AnnoProc extends AbstractProcessor {\n" + 144 " public boolean process(Set<? extends TypeElement> annos, RoundEnvironment rEnv) {\n" + 145 " throw new Error(\"Annotation processor should not be invoked\");\n" + 146 " }\n" + 147 "}\n"); 148 Path annoClasses = Files.createDirectories(base.resolve("classes")); 149 new JavacTask(tb) 150 .outdir(annoClasses) 151 .files(annoSrc.resolve("AnnoProc.java").toString()) 152 .run(); 153 Path serviceFile = annoClasses.resolve("META-INF").resolve("services") 154 .resolve("javax.annotation.processing.Processor"); 155 tb.writeFile(serviceFile, "AnnoProc"); 156 157 Path mainSrc = base.resolve("mainSrc"); 158 tb.writeJavaFiles(mainSrc, 159 "import java.util.Arrays;\n" + 160 "class HelloWorld {\n" + 161 " public static void main(String... args) {\n" + 162 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 163 " }\n" + 164 "}"); 165 166 List<String> javacArgs = List.of("-classpath", annoClasses.toString()); 167 List<String> classArgs = List.of("1", "2", "3"); 168 String expect = "Hello World! [1, 2, 3]\n"; 169 Result r = run(mainSrc.resolve("HelloWorld.java"), javacArgs, classArgs); 170 checkEqual("stdout", r.stdOut, expect); 171 checkEmpty("stderr", r.stdErr); 172 checkNull("exception", r.exception); 173 } 174 175 @Test 176 public void testEnablePreview(Path base) throws IOException { 177 tb.writeJavaFiles(base, 178 "import java.util.Arrays;\n" + 179 "class HelloWorld {\n" + 180 " public static void main(String... args) {\n" + 181 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 182 " }\n" + 183 "}"); 184 185 String log = new JavaTask(tb) 186 .vmOptions("--enable-preview", "--source", thisVersion) 187 .className(base.resolve("HelloWorld.java").toString()) 188 .classArgs("1", "2", "3") 189 .run(Task.Expect.SUCCESS) 190 .getOutput(Task.OutputKind.STDOUT); 191 checkEqual("stdout", log.trim(), "Hello World! [1, 2, 3]"); 192 } 193 194 void testSuccess(Path file, String expect) throws IOException { 195 Result r = run(file, Collections.emptyList(), List.of("1", "2", "3")); 196 checkEqual("stdout", r.stdOut, expect); 197 checkEmpty("stderr", r.stdErr); 198 checkNull("exception", r.exception); 199 } 200 201 /* 202 * Negative tests: such as cannot find or execute main method. 203 */ 204 205 @Test 206 public void testHelloWorldWithShebangJava(Path base) throws IOException { 207 tb.writeJavaFiles(base, 208 "#!/usr/bin/java --source " + thisVersion + "\n" + 209 "import java.util.Arrays;\n" + 210 "class HelloWorld {\n" + 211 " public static void main(String... args) {\n" + 212 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 213 " }\n" + 214 "}"); 215 Path file = base.resolve("HelloWorld.java"); 216 testError(file, 217 file + ":1: error: illegal character: '#'\n" + 218 "#!/usr/bin/java --source " + thisVersion + "\n" + 219 "^\n" + 220 file + ":1: error: class, interface, or enum expected\n" + 221 "#!/usr/bin/java --source " + thisVersion + "\n" + 222 " ^\n" + 223 "2 errors\n", 224 "error: compilation failed"); 225 } 226 227 @Test 228 public void testNoClass(Path base) throws IOException { 229 Files.createDirectories(base); 230 Path file = base.resolve("NoClass.java"); 231 Files.write(file, List.of("package p;")); 232 testError(file, "", "error: no class declared in file"); 233 } 234 235 @Test 236 public void testWrongClass(Path base) throws IOException { 237 Path src = base.resolve("src"); 238 Path file = src.resolve("WrongClass.java"); 239 tb.writeJavaFiles(src, "class WrongClass { }"); 240 Path classes = Files.createDirectories(base.resolve("classes")); 241 new JavacTask(tb) 242 .outdir(classes) 243 .files(file) 244 .run(); 245 String log = new JavaTask(tb) 246 .classpath(classes.toString()) 247 .className(file.toString()) 248 .run(Task.Expect.FAIL) 249 .getOutput(Task.OutputKind.STDERR); 250 checkEqual("stderr", log.trim(), 251 "error: class found on application class path: WrongClass"); 252 } 253 254 @Test 255 public void testSyntaxErr(Path base) throws IOException { 256 tb.writeJavaFiles(base, "class SyntaxErr {"); 257 Path file = base.resolve("SyntaxErr.java"); 258 testError(file, 259 file + ":1: error: reached end of file while parsing\n" + 260 "class SyntaxErr {\n" + 261 " ^\n" + 262 "1 error\n", 263 "error: compilation failed"); 264 } 265 266 @Test 267 public void testNoSourceOnClassPath(Path base) throws IOException { 268 Path auxSrc = base.resolve("auxSrc"); 269 tb.writeJavaFiles(auxSrc, 270 "public class Aux {\n" + 271 " static final String MESSAGE = \"Hello World\";\n" + 272 "}\n"); 273 274 Path mainSrc = base.resolve("mainSrc"); 275 tb.writeJavaFiles(mainSrc, 276 "import java.util.Arrays;\n" + 277 "class HelloWorld {\n" + 278 " public static void main(String... args) {\n" + 279 " System.out.println(Aux.MESSAGE + Arrays.toString(args));\n" + 280 " }\n" + 281 "}"); 282 283 List<String> javacArgs = List.of("-classpath", auxSrc.toString()); 284 List<String> classArgs = List.of("1", "2", "3"); 285 String FS = File.separator; 286 String expectStdErr = 287 "testNoSourceOnClassPath" + FS + "mainSrc" + FS + "HelloWorld.java:4: error: cannot find symbol\n" + 288 " System.out.println(Aux.MESSAGE + Arrays.toString(args));\n" + 289 " ^\n" + 290 " symbol: variable Aux\n" + 291 " location: class HelloWorld\n" + 292 "1 error\n"; 293 Result r = run(mainSrc.resolve("HelloWorld.java"), javacArgs, classArgs); 294 checkEmpty("stdout", r.stdOut); 295 checkEqual("stderr", r.stdErr, expectStdErr); 296 checkFault("exception", r.exception, "error: compilation failed"); 297 298 } 299 300 // For any source file that is invoked through the OS shebang mechanism, invalid shebang 301 // lines will be caught and handled by the OS, before the launcher is even invoked. 302 // However, if such a file is passed directly to the launcher, perhaps using the --source 303 // option, a well-formed shebang line will be removed but a badly-formed one will be not be 304 // removed and will cause compilation errors. 305 @Test 306 public void testBadShebang(Path base) throws IOException { 307 tb.writeJavaFiles(base, 308 "#/usr/bin/java --source " + thisVersion + "\n" + 309 "import java.util.Arrays;\n" + 310 "class HelloWorld {\n" + 311 " public static void main(String... args) {\n" + 312 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 313 " }\n" + 314 "}"); 315 Path file = base.resolve("HelloWorld.java"); 316 testError(file, 317 file + ":1: error: illegal character: '#'\n" + 318 "#/usr/bin/java --source " + thisVersion + "\n" + 319 "^\n" + 320 file + ":1: error: class, interface, or enum expected\n" + 321 "#/usr/bin/java --source " + thisVersion + "\n" + 322 " ^\n" + 323 "2 errors\n", 324 "error: compilation failed"); 325 } 326 327 @Test 328 public void testBadSourceOpt(Path base) throws IOException { 329 Files.createDirectories(base); 330 Path file = base.resolve("DummyClass.java"); 331 Files.write(file, List.of("class DummyClass { }")); 332 Properties sysProps = System.getProperties(); 333 Properties p = new Properties(sysProps); 334 p.setProperty("jdk.internal.javac.source", "<BAD>"); 335 System.setProperties(p); 336 try { 337 testError(file, "", "error: invalid value for --source option: <BAD>"); 338 } finally { 339 System.setProperties(sysProps); 340 } 341 } 342 343 @Test 344 public void testEnablePreviewNoSource(Path base) throws IOException { 345 tb.writeJavaFiles(base, 346 "import java.util.Arrays;\n" + 347 "class HelloWorld {\n" + 348 " public static void main(String... args) {\n" + 349 " System.out.println(\"Hello World! \" + Arrays.toString(args));\n" + 350 " }\n" + 351 "}"); 352 353 String log = new JavaTask(tb) 354 .vmOptions("--enable-preview") 355 .className(base.resolve("HelloWorld.java").toString()) 356 .run(Task.Expect.FAIL) 357 .getOutput(Task.OutputKind.STDERR); 358 checkEqual("stderr", log.trim(), 359 "error: --enable-preview must be used with --source"); 360 } 361 362 @Test 363 public void testNoMain(Path base) throws IOException { 364 tb.writeJavaFiles(base, "class NoMain { }"); 365 testError(base.resolve("NoMain.java"), "", 366 "error: can't find main(String[]) method in class: NoMain"); 367 } 368 369 @Test 370 public void testMainBadParams(Path base) throws IOException { 371 tb.writeJavaFiles(base, 372 "class BadParams { public static void main() { } }"); 373 testError(base.resolve("BadParams.java"), "", 374 "error: can't find main(String[]) method in class: BadParams"); 375 } 376 377 @Test 378 public void testMainNotPublic(Path base) throws IOException { 379 tb.writeJavaFiles(base, 380 "class NotPublic { static void main(String... args) { } }"); 381 testError(base.resolve("NotPublic.java"), "", 382 "error: 'main' method is not declared 'public static'"); 383 } 384 385 @Test 386 public void testMainNotStatic(Path base) throws IOException { 387 tb.writeJavaFiles(base, 388 "class NotStatic { public void main(String... args) { } }"); 389 testError(base.resolve("NotStatic.java"), "", 390 "error: 'main' method is not declared 'public static'"); 391 } 392 393 @Test 394 public void testMainNotVoid(Path base) throws IOException { 395 tb.writeJavaFiles(base, 396 "class NotVoid { public static int main(String... args) { return 0; } }"); 397 testError(base.resolve("NotVoid.java"), "", 398 "error: 'main' method is not declared with a return type of 'void'"); 399 } 400 401 @Test 402 public void testClassInModule(Path base) throws IOException { 403 tb.writeJavaFiles(base, "package java.net; class InModule { }"); 404 Path file = base.resolve("java").resolve("net").resolve("InModule.java"); 405 testError(file, 406 file + ":1: error: package exists in another module: java.base\n" + 407 "package java.net; class InModule { }\n" + 408 "^\n" + 409 "1 error\n", 410 "error: compilation failed"); 411 } 412 413 void testError(Path file, String expectStdErr, String expectFault) throws IOException { 414 Result r = run(file, Collections.emptyList(), List.of("1", "2", "3")); 415 checkEmpty("stdout", r.stdOut); 416 checkEqual("stderr", r.stdErr, expectStdErr); 417 checkFault("exception", r.exception, expectFault); 418 } 419 420 /* 421 * Tests in which main throws an exception. 422 */ 423 @Test 424 public void testTargetException1(Path base) throws IOException { 425 tb.writeJavaFiles(base, 426 "import java.util.Arrays;\n" + 427 "class Thrower {\n" + 428 " public static void main(String... args) {\n" + 429 " throwWhenZero(Integer.parseInt(args[0]));\n" + 430 " }\n" + 431 " static void throwWhenZero(int arg) {\n" + 432 " if (arg == 0) throw new Error(\"zero!\");\n" + 433 " throwWhenZero(arg - 1);\n" + 434 " }\n" + 435 "}"); 436 Path file = base.resolve("Thrower.java"); 437 Result r = run(file, Collections.emptyList(), List.of("3")); 438 checkEmpty("stdout", r.stdOut); 439 checkEmpty("stderr", r.stdErr); 440 checkTrace("exception", r.exception, 441 "java.lang.Error: zero!", 442 "at Thrower.throwWhenZero(Thrower.java:7)", 443 "at Thrower.throwWhenZero(Thrower.java:8)", 444 "at Thrower.throwWhenZero(Thrower.java:8)", 445 "at Thrower.throwWhenZero(Thrower.java:8)", 446 "at Thrower.main(Thrower.java:4)"); 447 } 448 449 Result run(Path file, List<String> runtimeArgs, List<String> appArgs) { 450 List<String> args = new ArrayList<>(); 451 args.add(file.toString()); 452 args.addAll(appArgs); 453 454 PrintStream prev = System.out; 455 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 456 try (PrintStream out = new PrintStream(baos, true)) { 457 System.setOut(out); 458 StringWriter sw = new StringWriter(); 459 try (PrintWriter err = new PrintWriter(sw, true)) { 460 Main m = new Main(err); 461 m.run(toArray(runtimeArgs), toArray(args)); 462 return new Result(baos.toString(), sw.toString(), null); 463 } catch (Throwable t) { 464 return new Result(baos.toString(), sw.toString(), t); 465 } 466 } finally { 467 System.setOut(prev); 468 } 469 } 470 471 void checkEqual(String name, String found, String expect) { 472 expect = expect.replace("\n", tb.lineSeparator); 473 out.println(name + ": " + found); 474 out.println(name + ": " + found); 475 if (!expect.equals(found)) { 476 error("Unexpected output; expected: " + expect); 477 } 478 } 479 480 void checkEmpty(String name, String found) { 481 out.println(name + ": " + found); 482 if (!found.isEmpty()) { 483 error("Unexpected output; expected empty string"); 484 } 485 } 486 487 void checkNull(String name, Throwable found) { 488 out.println(name + ": " + found); 489 if (found != null) { 490 error("Unexpected exception; expected null"); 491 } 492 } 493 494 void checkFault(String name, Throwable found, String expect) { 495 expect = expect.replace("\n", tb.lineSeparator); 496 out.println(name + ": " + found); 497 if (found == null) { 498 error("No exception thrown; expected Main.Fault"); 499 } else { 500 if (!(found instanceof Main.Fault)) { 501 error("Unexpected exception; expected Main.Fault"); 502 } 503 if (!(found.getMessage().equals(expect))) { 504 error("Unexpected detail message; expected: " + expect); 505 } 506 } 507 } 508 509 void checkTrace(String name, Throwable found, String... expect) { 510 if (!(found instanceof InvocationTargetException)) { 511 error("Unexpected exception; expected InvocationTargetException"); 512 out.println("Found:"); 513 found.printStackTrace(out); 514 } 515 StringWriter sw = new StringWriter(); 516 try (PrintWriter pw = new PrintWriter(sw)) { 517 ((InvocationTargetException) found).getTargetException().printStackTrace(pw); 518 } 519 String trace = sw.toString(); 520 out.println(name + ":\n" + trace); 521 String[] traceLines = trace.trim().split("[\r\n]+\\s+"); 522 try { 523 tb.checkEqual(List.of(traceLines), List.of(expect)); 524 } catch (Error e) { 525 error(e.getMessage()); 526 } 527 } 528 529 String[] toArray(List<String> list) { 530 return list.toArray(new String[list.size()]); 531 } 532 533 class Result { 534 private final String stdOut; 535 private final String stdErr; 536 private final Throwable exception; 537 538 Result(String stdOut, String stdErr, Throwable exception) { 539 this.stdOut = stdOut; 540 this.stdErr = stdErr; 541 this.exception = exception; 542 } 543 } 544 }