Path: blob/master/test/jdk/java/net/spi/URLStreamHandlerProvider/Basic.java
66646 views
/*1* Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223import java.io.File;24import java.io.FileWriter;25import java.io.Reader;26import java.io.IOException;27import java.io.InputStream;28import java.io.InputStreamReader;29import java.io.SequenceInputStream;30import java.io.StringWriter;31import java.io.Writer;32import java.nio.file.Files;33import java.nio.file.Path;34import java.nio.file.Paths;35import java.util.ArrayList;36import java.util.Collection;37import java.util.Collections;38import java.util.List;39import java.util.function.Consumer;40import java.util.stream.Collectors;41import java.util.stream.Stream;42import javax.tools.JavaCompiler;43import javax.tools.JavaFileObject;44import javax.tools.StandardJavaFileManager;45import javax.tools.StandardLocation;46import javax.tools.ToolProvider;47import jdk.test.lib.util.FileUtils;48import jdk.test.lib.JDKToolFinder;49import static java.lang.String.format;50import static java.util.Arrays.asList;5152/*53* @test54* @bug 806492455* @modules jdk.compiler56* @summary Basic test for URLStreamHandlerProvider57* @library /test/lib58* @build jdk.test.lib.Platform59* jdk.test.lib.util.FileUtils60* jdk.test.lib.JDKToolFinder61* @compile Basic.java Child.java62* @run main Basic63*/6465public class Basic {6667static final Path TEST_SRC = Paths.get(System.getProperty("test.src", "."));68static final Path TEST_CLASSES = Paths.get(System.getProperty("test.classes", "."));6970public static void main(String[] args) throws Throwable {71unknownProtocol("foo", UNKNOWN);72unknownProtocol("bar", UNKNOWN);73viaProvider("baz", KNOWN);74viaProvider("bert", KNOWN);75viaProvider("ernie", UNKNOWN, "-Djava.security.manager");76viaProvider("curly", UNKNOWN, "-Djava.security.manager");77viaProvider("larry", KNOWN, "-Djava.security.manager",78"-Djava.security.policy=" + TEST_SRC + File.separator + "basic.policy");79viaProvider("moe", KNOWN, "-Djava.security.manager",80"-Djava.security.policy=" + TEST_SRC + File.separator + "basic.policy");81viaBadProvider("tom", SCE);82viaBadProvider("jerry", SCE);83}8485static final String SECURITY_MANAGER_DEPRECATED86= "WARNING: The Security Manager is deprecated and will be removed in a future release."87+ System.getProperty("line.separator");8889private static String withoutWarning(String in) {90return in.lines().filter(s -> !s.startsWith("WARNING:")).collect(Collectors.joining());91}9293static final Consumer<Result> KNOWN = r -> {94if (r.exitValue != 0 || !withoutWarning(r.output).isEmpty())95throw new RuntimeException("[" + r.output + "]");96};97static final Consumer<Result> UNKNOWN = r -> {98if (r.exitValue == 0 ||99!r.output.contains("java.net.MalformedURLException: unknown protocol")) {100throw new RuntimeException("exitValue: "+ r.exitValue + ", output:[" +r.output +"]");101}102};103static final Consumer<Result> SCE = r -> {104if (r.exitValue == 0 ||105!r.output.contains("java.util.ServiceConfigurationError")) {106throw new RuntimeException("exitValue: "+ r.exitValue + ", output:[" +r.output +"]");107}108};109110static void unknownProtocol(String protocol, Consumer<Result> resultChecker) {111System.out.println("\nTesting " + protocol);112Result r = java(Collections.emptyList(), asList(TEST_CLASSES),113"Child", protocol);114resultChecker.accept(r);115}116117static void viaProvider(String protocol, Consumer<Result> resultChecker,118String... sysProps)119throws Exception120{121viaProviderWithTemplate(protocol, resultChecker,122TEST_SRC.resolve("provider.template"),123sysProps);124}125126static void viaBadProvider(String protocol, Consumer<Result> resultChecker,127String... sysProps)128throws Exception129{130viaProviderWithTemplate(protocol, resultChecker,131TEST_SRC.resolve("bad.provider.template"),132sysProps);133}134135static void viaProviderWithTemplate(String protocol,136Consumer<Result> resultChecker,137Path template, String... sysProps)138throws Exception139{140System.out.println("\nTesting " + protocol);141Path testRoot = Paths.get("URLStreamHandlerProvider-" + protocol);142if (Files.exists(testRoot))143FileUtils.deleteFileTreeWithRetry(testRoot);144Files.createDirectory(testRoot);145146Path srcPath = Files.createDirectory(testRoot.resolve("src"));147Path srcClass = createProvider(protocol, template, srcPath);148149Path build = Files.createDirectory(testRoot.resolve("build"));150javac(build, srcClass);151createServices(build, protocol);152Path testJar = testRoot.resolve("test.jar");153jar(testJar, build);154155List<String> props = new ArrayList<>();156for (String p : sysProps)157props.add(p);158159Result r = java(props, asList(testJar, TEST_CLASSES),160"Child", protocol);161162resultChecker.accept(r);163}164165static String platformPath(String p) { return p.replace("/", File.separator); }166static String binaryName(String name) { return name.replace(".", "/"); }167168static final String SERVICE_IMPL_PREFIX = "net.java.openjdk.test";169170static void createServices(Path dst, String protocol) throws IOException {171Path services = Files.createDirectories(dst.resolve("META-INF")172.resolve("services"));173174final String implName = SERVICE_IMPL_PREFIX + "." + protocol + ".Provider";175Path s = services.resolve("java.net.spi.URLStreamHandlerProvider");176FileWriter fw = new FileWriter(s.toFile());177try {178fw.write(implName);179} finally {180fw.close();181}182}183184static Path createProvider(String protocol, Path srcTemplate, Path dst)185throws IOException186{187String pkg = SERVICE_IMPL_PREFIX + "." + protocol;188Path classDst = dst.resolve(platformPath(binaryName(pkg)));189Files.createDirectories(classDst);190Path classPath = classDst.resolve("Provider.java");191192List<String> lines = Files.lines(srcTemplate)193.map(s -> s.replaceAll("\\$package", pkg))194.map(s -> s.replaceAll("\\$protocol", protocol))195.collect(Collectors.toList());196Files.write(classPath, lines);197198return classPath;199}200201static void jar(Path jarName, Path jarRoot) { String jar = getJDKTool("jar");202ProcessBuilder p = new ProcessBuilder(jar, "cf", jarName.toString(),203"-C", jarRoot.toString(), ".");204quickFail(run(p));205}206207static void javac(Path dest, Path... sourceFiles) throws IOException {208JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();209try (StandardJavaFileManager fileManager =210compiler.getStandardFileManager(null, null, null)) {211212List<File> files = Stream.of(sourceFiles)213.map(p -> p.toFile())214.collect(Collectors.toList());215List<File> dests = Stream.of(dest)216.map(p -> p.toFile())217.collect(Collectors.toList());218Iterable<? extends JavaFileObject> compilationUnits =219fileManager.getJavaFileObjectsFromFiles(files);220fileManager.setLocation(StandardLocation.CLASS_OUTPUT, dests);221JavaCompiler.CompilationTask task =222compiler.getTask(null, fileManager, null, null, null, compilationUnits);223boolean passed = task.call();224if (!passed)225throw new RuntimeException("Error compiling " + files);226}227}228229static void quickFail(Result r) {230if (r.exitValue != 0)231throw new RuntimeException(r.output);232}233234static Result java(List<String> sysProps, Collection<Path> classpath,235String classname, String arg) {236String java = getJDKTool("java");237238List<String> commands = new ArrayList<>();239commands.add(java);240for (String prop : sysProps)241commands.add(prop);242243String cp = classpath.stream()244.map(Path::toString)245.collect(Collectors.joining(File.pathSeparator));246commands.add("-cp");247commands.add(cp);248commands.add(classname);249commands.add(arg);250251return run(new ProcessBuilder(commands));252}253254static Result run(ProcessBuilder pb) {255Process p = null;256System.out.println("running: " + pb.command());257try {258p = pb.start();259} catch (IOException e) {260throw new RuntimeException(261format("Couldn't start process '%s'", pb.command()), e);262}263264String output;265try {266output = toString(p.getInputStream(), p.getErrorStream());267} catch (IOException e) {268throw new RuntimeException(269format("Couldn't read process output '%s'", pb.command()), e);270}271272try {273p.waitFor();274} catch (InterruptedException e) {275throw new RuntimeException(276format("Process hasn't finished '%s'", pb.command()), e);277}278279return new Result(p.exitValue(), output);280}281282static final String DEFAULT_IMAGE_BIN = System.getProperty("java.home")283+ File.separator + "bin" + File.separator;284285static String getJDKTool(String name) {286try {287return JDKToolFinder.getJDKTool(name);288} catch (Exception x) {289return DEFAULT_IMAGE_BIN + name;290}291}292293static String toString(InputStream... src) throws IOException {294StringWriter dst = new StringWriter();295Reader concatenated =296new InputStreamReader(297new SequenceInputStream(298Collections.enumeration(asList(src))));299copy(concatenated, dst);300return dst.toString();301}302303static void copy(Reader src, Writer dst) throws IOException {304int len;305char[] buf = new char[1024];306try {307while ((len = src.read(buf)) != -1)308dst.write(buf, 0, len);309} finally {310try {311src.close();312} catch (IOException ignored1) {313} finally {314try {315dst.close();316} catch (IOException ignored2) {317}318}319}320}321322static class Result {323final int exitValue;324final String output;325326private Result(int exitValue, String output) {327this.exitValue = exitValue;328this.output = output;329}330}331}332333334