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