Path: blob/master/test/jdk/java/net/spi/URLStreamHandlerProvider/Basic.java
41155 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");88static final Consumer<Result> KNOWN = r -> {89if (r.exitValue != 0 ||90(!r.output.isEmpty() && !r.output.equals(SECURITY_MANAGER_DEPRECATED)))91throw new RuntimeException(r.output);92};93static final Consumer<Result> UNKNOWN = r -> {94if (r.exitValue == 0 ||95!r.output.contains("java.net.MalformedURLException: unknown protocol")) {96throw new RuntimeException("exitValue: "+ r.exitValue + ", output:[" +r.output +"]");97}98};99static final Consumer<Result> SCE = r -> {100if (r.exitValue == 0 ||101!r.output.contains("java.util.ServiceConfigurationError")) {102throw new RuntimeException("exitValue: "+ r.exitValue + ", output:[" +r.output +"]");103}104};105106static void unknownProtocol(String protocol, Consumer<Result> resultChecker) {107System.out.println("\nTesting " + protocol);108Result r = java(Collections.emptyList(), asList(TEST_CLASSES),109"Child", protocol);110resultChecker.accept(r);111}112113static void viaProvider(String protocol, Consumer<Result> resultChecker,114String... sysProps)115throws Exception116{117viaProviderWithTemplate(protocol, resultChecker,118TEST_SRC.resolve("provider.template"),119sysProps);120}121122static void viaBadProvider(String protocol, Consumer<Result> resultChecker,123String... sysProps)124throws Exception125{126viaProviderWithTemplate(protocol, resultChecker,127TEST_SRC.resolve("bad.provider.template"),128sysProps);129}130131static void viaProviderWithTemplate(String protocol,132Consumer<Result> resultChecker,133Path template, String... sysProps)134throws Exception135{136System.out.println("\nTesting " + protocol);137Path testRoot = Paths.get("URLStreamHandlerProvider-" + protocol);138if (Files.exists(testRoot))139FileUtils.deleteFileTreeWithRetry(testRoot);140Files.createDirectory(testRoot);141142Path srcPath = Files.createDirectory(testRoot.resolve("src"));143Path srcClass = createProvider(protocol, template, srcPath);144145Path build = Files.createDirectory(testRoot.resolve("build"));146javac(build, srcClass);147createServices(build, protocol);148Path testJar = testRoot.resolve("test.jar");149jar(testJar, build);150151List<String> props = new ArrayList<>();152for (String p : sysProps)153props.add(p);154155Result r = java(props, asList(testJar, TEST_CLASSES),156"Child", protocol);157158resultChecker.accept(r);159}160161static String platformPath(String p) { return p.replace("/", File.separator); }162static String binaryName(String name) { return name.replace(".", "/"); }163164static final String SERVICE_IMPL_PREFIX = "net.java.openjdk.test";165166static void createServices(Path dst, String protocol) throws IOException {167Path services = Files.createDirectories(dst.resolve("META-INF")168.resolve("services"));169170final String implName = SERVICE_IMPL_PREFIX + "." + protocol + ".Provider";171Path s = services.resolve("java.net.spi.URLStreamHandlerProvider");172FileWriter fw = new FileWriter(s.toFile());173try {174fw.write(implName);175} finally {176fw.close();177}178}179180static Path createProvider(String protocol, Path srcTemplate, Path dst)181throws IOException182{183String pkg = SERVICE_IMPL_PREFIX + "." + protocol;184Path classDst = dst.resolve(platformPath(binaryName(pkg)));185Files.createDirectories(classDst);186Path classPath = classDst.resolve("Provider.java");187188List<String> lines = Files.lines(srcTemplate)189.map(s -> s.replaceAll("\\$package", pkg))190.map(s -> s.replaceAll("\\$protocol", protocol))191.collect(Collectors.toList());192Files.write(classPath, lines);193194return classPath;195}196197static void jar(Path jarName, Path jarRoot) { String jar = getJDKTool("jar");198ProcessBuilder p = new ProcessBuilder(jar, "cf", jarName.toString(),199"-C", jarRoot.toString(), ".");200quickFail(run(p));201}202203static void javac(Path dest, Path... sourceFiles) throws IOException {204JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();205try (StandardJavaFileManager fileManager =206compiler.getStandardFileManager(null, null, null)) {207208List<File> files = Stream.of(sourceFiles)209.map(p -> p.toFile())210.collect(Collectors.toList());211List<File> dests = Stream.of(dest)212.map(p -> p.toFile())213.collect(Collectors.toList());214Iterable<? extends JavaFileObject> compilationUnits =215fileManager.getJavaFileObjectsFromFiles(files);216fileManager.setLocation(StandardLocation.CLASS_OUTPUT, dests);217JavaCompiler.CompilationTask task =218compiler.getTask(null, fileManager, null, null, null, compilationUnits);219boolean passed = task.call();220if (!passed)221throw new RuntimeException("Error compiling " + files);222}223}224225static void quickFail(Result r) {226if (r.exitValue != 0)227throw new RuntimeException(r.output);228}229230static Result java(List<String> sysProps, Collection<Path> classpath,231String classname, String arg) {232String java = getJDKTool("java");233234List<String> commands = new ArrayList<>();235commands.add(java);236for (String prop : sysProps)237commands.add(prop);238239String cp = classpath.stream()240.map(Path::toString)241.collect(Collectors.joining(File.pathSeparator));242commands.add("-cp");243commands.add(cp);244commands.add(classname);245commands.add(arg);246247return run(new ProcessBuilder(commands));248}249250static Result run(ProcessBuilder pb) {251Process p = null;252System.out.println("running: " + pb.command());253try {254p = pb.start();255} catch (IOException e) {256throw new RuntimeException(257format("Couldn't start process '%s'", pb.command()), e);258}259260String output;261try {262output = toString(p.getInputStream(), p.getErrorStream());263} catch (IOException e) {264throw new RuntimeException(265format("Couldn't read process output '%s'", pb.command()), e);266}267268try {269p.waitFor();270} catch (InterruptedException e) {271throw new RuntimeException(272format("Process hasn't finished '%s'", pb.command()), e);273}274275return new Result(p.exitValue(), output);276}277278static final String DEFAULT_IMAGE_BIN = System.getProperty("java.home")279+ File.separator + "bin" + File.separator;280281static String getJDKTool(String name) {282try {283return JDKToolFinder.getJDKTool(name);284} catch (Exception x) {285return DEFAULT_IMAGE_BIN + name;286}287}288289static String toString(InputStream... src) throws IOException {290StringWriter dst = new StringWriter();291Reader concatenated =292new InputStreamReader(293new SequenceInputStream(294Collections.enumeration(asList(src))));295copy(concatenated, dst);296return dst.toString();297}298299static void copy(Reader src, Writer dst) throws IOException {300int len;301char[] buf = new char[1024];302try {303while ((len = src.read(buf)) != -1)304dst.write(buf, 0, len);305} finally {306try {307src.close();308} catch (IOException ignored1) {309} finally {310try {311dst.close();312} catch (IOException ignored2) {313}314}315}316}317318static class Result {319final int exitValue;320final String output;321322private Result(int exitValue, String output) {323this.exitValue = exitValue;324this.output = output;325}326}327}328329330