1 /*
   2  * Copyright (c) 2015, 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.File;
  27 import java.io.FileReader;
  28 import java.io.FileWriter;
  29 import java.io.IOException;
  30 import java.io.InputStream;
  31 import java.io.InputStreamReader;
  32 import java.io.Reader;
  33 import java.io.SequenceInputStream;
  34 import java.io.StringWriter;
  35 import java.io.Writer;
  36 import java.nio.file.Files;
  37 import java.nio.file.Path;
  38 import java.nio.file.Paths;
  39 import java.util.ArrayList;
  40 import java.util.Arrays;
  41 import java.util.Collection;
  42 import java.util.Collections;
  43 import java.util.Iterator;
  44 import java.util.List;
  45 import java.util.Map;
  46 import java.util.function.Function;
  47 import java.util.stream.Collectors;
  48 import java.util.stream.Stream;
  49 
  50 import static java.lang.String.format;
  51 import static java.util.Arrays.asList;
  52 import static java.util.Collections.emptyMap;
  53 import static java.util.Collections.singleton;
  54 import static java.util.Collections.singletonMap;
  55 
  56 /*
  57  * @test
  58  * @bug 8064925
  59  * @summary Basic test for ContentHandler. Ensures discovery paths for content
  60  *          handlers follow a particular order.
  61  */
  62 public class ContentHandlersTest {
  63 
  64     public static void main(String[] args) throws Throwable {
  65         step1_ContentHandlerFactory();
  66         step2_ServiceLoader();
  67         step3_UserDefined();
  68         step4_BuiltIn();
  69     }
  70 
  71     private static void step1_ContentHandlerFactory() throws IOException {
  72         String factoryClassFqn = "net.java.openjdk.test.TestContentHandlerFactory";
  73 
  74         Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-1"));
  75 
  76         Path src = templatesHome().resolve("test.template");
  77         Path dst = tmp.resolve("Test.java");
  78         Files.copy(src, dst);
  79 
  80         Path build = Files.createDirectory(tmp.resolve("build"));
  81 
  82         Path dst1 = fromTemplate(templatesHome().resolve("broken_factory.template"),
  83                 factoryClassFqn, tmp);
  84 
  85         javac(build, dst, dst1);
  86 
  87         Result r = java(emptyMap(), singleton(build), "Test", factoryClassFqn);
  88 
  89         if (r.exitValue == 0 || !r.output.startsWith(
  90                 stackTraceStringForBrokenFactory(factoryClassFqn))) {
  91             throw new RuntimeException(
  92                     "Expected a different kind of failure: " + r.output);
  93         }
  94     }
  95 
  96     private static void step2_ServiceLoader() throws IOException {
  97         String factoryClassFqn = "net.java.openjdk.test.TestContentHandlerFactory";
  98 
  99         Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-2"));
 100 
 101         Path src = templatesHome().resolve("test.template");
 102         Path dst = tmp.resolve("Test.java");
 103         Files.copy(src, dst);
 104 
 105         Path dst1 = fromTemplate(templatesHome().resolve("broken_constructor_factory.template"),
 106                 factoryClassFqn, tmp);
 107 
 108         Path build = Files.createDirectory(tmp.resolve("build"));
 109 
 110         javac(build, dst);
 111 
 112         Path explodedJar = Files.createDirectory(tmp.resolve("exploded-jar"));
 113         Path services = Files.createDirectories(explodedJar.resolve("META-INF")
 114                 .resolve("services"));
 115 
 116         Path s = services.resolve("java.net.ContentHandlerFactory");
 117 
 118         try (FileWriter fw = new FileWriter(s.toFile())) {
 119             fw.write(factoryClassFqn);
 120         }
 121 
 122         javac(explodedJar, dst1);
 123         jar(tmp.resolve("test.jar"), explodedJar);
 124 
 125         Files.copy(tmp.resolve("test.jar"), build.resolve("test.jar"));
 126 
 127         Result r = java(emptyMap(), asList(build.resolve("test.jar"), build), "Test");
 128 
 129         if (r.exitValue == 0 || !verifyOutput(r.output, factoryClassFqn))
 130             throw new RuntimeException(r.output);
 131     }
 132 
 133     private static void step3_UserDefined() throws IOException {
 134         String packagePrefix = "net.java.openjdk.test";
 135         String fqn = packagePrefix + ".text.plain";
 136 
 137         Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-3"));
 138 
 139         Path src = templatesHome().resolve("test.template");
 140         Path dst = tmp.resolve("Test.java");
 141         Files.copy(src, dst);
 142 
 143         Path dst1 = fromTemplate(templatesHome().resolve("plain.template"),
 144                 fqn, tmp);
 145 
 146         Path build = Files.createDirectory(tmp.resolve("build"));
 147 
 148         javac(build, dst);
 149 
 150         Path classes = Files.createDirectory(tmp.resolve("classes"));
 151 
 152         javac(classes, dst1);
 153 
 154         Map<String, String> m = singletonMap("java.content.handler.pkgs", packagePrefix);
 155         Result r = java(m, asList(build, classes), "Test");
 156 
 157         if (r.exitValue != 0 || !r.output.contains(fqn))
 158             throw new RuntimeException(r.output);
 159     }
 160 
 161     private static void step4_BuiltIn() throws IOException {
 162         Path tmp = Files.createDirectory(Paths.get("ContentHandlersTest-4"));
 163 
 164         Path src = templatesHome().resolve("test.template");
 165         Path dst = tmp.resolve("Test.java");
 166         Files.copy(src, dst);
 167 
 168         Path build = Files.createDirectory(tmp.resolve("build"));
 169 
 170         javac(build, dst);
 171 
 172         Result r = java(emptyMap(), singleton(build), "Test");
 173 
 174         if (r.exitValue != 0 || !r.output.contains("sun.net.www.content.text.PlainTextInputStream"))
 175             throw new RuntimeException(r.output);
 176     }
 177 
 178     private static String stackTraceStringForBrokenFactory(String fqn) {
 179         return String.format(
 180                 "Exception in thread \"main\" java.lang.RuntimeException: This is a broken factory. It is supposed to throw this exception.\n" +
 181                         "\tat %s.createContentHandler",
 182                 fqn);
 183     }
 184 
 185     private static Path fromTemplate(Path srcTemplate,
 186                                      String factoryFqn,
 187                                      Path dstFolder) throws IOException {
 188 
 189         String factorySimpleName, packageName;
 190         int i = factoryFqn.lastIndexOf('.');
 191         if (i < 0) {
 192             packageName = "";
 193             factorySimpleName = factoryFqn;
 194         } else {
 195             packageName = factoryFqn.substring(0, i);
 196             factorySimpleName = factoryFqn.substring(i + 1);
 197         }
 198 
 199         Path result = dstFolder.resolve(factorySimpleName + ".java");
 200         File dst = result.toFile();
 201         File src = srcTemplate.toFile();
 202         try (BufferedReader r = new BufferedReader(new FileReader(src));
 203              BufferedWriter w = new BufferedWriter(new FileWriter(dst))) {
 204 
 205             List<String> lines = processTemplate(packageName, factorySimpleName,
 206                     r.lines()).collect(Collectors.toList());
 207 
 208             Iterator<String> it = lines.iterator();
 209             if (it.hasNext())
 210                 w.write(it.next());
 211             while (it.hasNext()) {
 212                 w.newLine();
 213                 w.write(it.next());
 214             }
 215         }
 216         return result;
 217     }
 218 
 219     private static Stream<String> processTemplate(String packageName,
 220                                                   String factorySimpleName,
 221                                                   Stream<String> lines) {
 222         Function<String, String> pckg;
 223 
 224         if (packageName.isEmpty()) {
 225             pckg = s -> s.contains("$package") ? "" : s;
 226         } else {
 227             pckg = s -> s.replaceAll("\\$package", packageName);
 228         }
 229 
 230         Function<String, String> factory
 231                 = s -> s.replaceAll("\\$className", factorySimpleName);
 232 
 233         return lines.map(pckg).map(factory);
 234     }
 235 
 236     // IMO, that's the easiest way that gives you a fair amount of confidence in
 237     // that j.u.ServiceLoader is loading a factory rather than Class.forName
 238     private static boolean verifyOutput(String output, String fqn) {
 239         String s1 = String.format("java.util.ServiceConfigurationError: " +
 240                 "java.net.ContentHandlerFactory: " +
 241                 "Provider %s could not be instantiated", fqn);
 242 
 243         return output.contains(s1);
 244     }
 245 
 246     private static void jar(Path jarName, Path jarRoot) {
 247         String jar = getJDKTool("jar");
 248         ProcessBuilder p = new ProcessBuilder(jar, "cf", jarName.toString(),
 249                 "-C", jarRoot.toString(), ".");
 250         quickFail(run(p));
 251     }
 252 
 253     private static void javac(Path compilationOutput, Path... sourceFiles) {
 254         String javac = getJDKTool("javac");
 255         List<String> commands = new ArrayList<>();
 256         commands.addAll(asList(javac, "-d", compilationOutput.toString()));
 257         List<Path> paths = asList(sourceFiles);
 258         commands.addAll(paths.stream()
 259                 .map(Path::toString)
 260                 .collect(Collectors.toList()));
 261         quickFail(run(new ProcessBuilder(commands)));
 262     }
 263 
 264     private static void quickFail(Result r) {
 265         if (r.exitValue != 0)
 266             throw new RuntimeException(r.output);
 267     }
 268 
 269     private static Result java(Map<String, String> properties,
 270                                Collection<Path> classpath,
 271                                String classname, String... args) {
 272 
 273         String java = getJDKTool("java");
 274 
 275         List<String> commands = new ArrayList<>();
 276         commands.add(java);
 277         commands.addAll(properties.entrySet()
 278                 .stream()
 279                 .map(e -> "-D" + e.getKey() + "=" + e.getValue())
 280                 .collect(Collectors.toList()));
 281 
 282         String cp = classpath.stream()
 283                 .map(Path::toString)
 284                 .collect(Collectors.joining(File.pathSeparator));
 285         commands.add("-cp");
 286         commands.add(cp);
 287         commands.add(classname);
 288         commands.addAll(Arrays.asList(args));
 289 
 290         return run(new ProcessBuilder(commands));
 291     }
 292 
 293     private static Result run(ProcessBuilder b) {
 294         Process p;
 295         try {
 296             p = b.start();
 297         } catch (IOException e) {
 298             throw new RuntimeException(
 299                     format("Couldn't start process '%s'", b.command()), e);
 300         }
 301 
 302         String output;
 303         try {
 304             output = toString(p.getInputStream(), p.getErrorStream());
 305         } catch (IOException e) {
 306             throw new RuntimeException(
 307                     format("Couldn't read process output '%s'", b.command()), e);
 308         }
 309 
 310         try {
 311             p.waitFor();
 312         } catch (InterruptedException e) {
 313             throw new RuntimeException(
 314                     format("Process hasn't finished '%s'", b.command()), e);
 315         }
 316 
 317         return new Result(p.exitValue(), output);
 318     }
 319 
 320     private static String getJDKTool(String name) {
 321         String testJdk = System.getProperty("test.jdk");
 322         if (testJdk == null)
 323             throw new RuntimeException("Please provide test.jdk property at a startup");
 324         return testJdk + File.separator + "bin" + File.separator + name;
 325     }
 326 
 327     private static Path templatesHome() {
 328         String testSrc = System.getProperty("test.src");
 329         if (testSrc == null)
 330             throw new RuntimeException("Please provide test.src property at a startup");
 331         return Paths.get(testSrc);
 332     }
 333 
 334     private static String toString(InputStream... src) throws IOException {
 335         StringWriter dst = new StringWriter();
 336         Reader concatenated =
 337                 new InputStreamReader(
 338                         new SequenceInputStream(
 339                                 Collections.enumeration(asList(src))));
 340         copy(concatenated, dst);
 341         return dst.toString();
 342     }
 343 
 344     private static void copy(Reader src, Writer dst) throws IOException {
 345         int len;
 346         char[] buf = new char[1024];
 347         try {
 348             while ((len = src.read(buf)) != -1)
 349                 dst.write(buf, 0, len);
 350         } finally {
 351             try {
 352                 src.close();
 353             } catch (IOException ignored1) {
 354             } finally {
 355                 try {
 356                     dst.close();
 357                 } catch (IOException ignored2) {
 358                 }
 359             }
 360         }
 361     }
 362 
 363     private static class Result {
 364 
 365         final int exitValue;
 366         final String output;
 367 
 368         private Result(int exitValue, String output) {
 369             this.exitValue = exitValue;
 370             this.output = output;
 371         }
 372     }
 373 }