8367114: Update jdk.test.lib.net.SimpleHttpServer to use SimpleFileServer

Reviewed-by: dfuchs, vyazici
This commit is contained in:
Mahendra Chhipa 2025-10-06 15:26:59 +00:00
parent e3320a9df5
commit b6a4cfecb7
5 changed files with 53 additions and 251 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -38,6 +38,8 @@ import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.xml.catalog.Catalog;
import javax.xml.catalog.CatalogException;
@ -49,6 +51,9 @@ import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import jdk.test.lib.net.URIBuilder;
import jdk.test.lib.util.JarUtils;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
@ -56,13 +61,11 @@ import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.xml.sax.InputSource;
import jdk.test.lib.net.SimpleHttpServer;
/*
* @test
* @bug 8151154 8171243
* @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest /test/lib
* @build jdk.test.lib.net.SimpleHttpServer
* @run testng/othervm catalog.CatalogFileInputTest
* @summary Verifies that the Catalog API accepts valid URIs only;
* Verifies that the CatalogFeatures' builder throws
@ -81,9 +84,9 @@ public class CatalogFileInputTest extends CatalogSupportBase {
final static String SCHEME_JARFILE = "jar:";
static final String REMOTE_FILE_LOCATION = "/jar/META-INF";
static final String DOCROOT = SRC_DIR;
static final String TESTCONTEXT = REMOTE_FILE_LOCATION; //mapped to local file path
private SimpleHttpServer httpserver;
private HttpServer httpserver;
private String remoteFilePath;
private ExecutorService executor;
/*
* Initializing fields
@ -92,15 +95,23 @@ public class CatalogFileInputTest extends CatalogSupportBase {
public void setUpClass() throws Exception {
super.setUp();
// set up HttpServer
httpserver = new SimpleHttpServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), TESTCONTEXT, DOCROOT);
httpserver = SimpleFileServer.createFileServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0),
Path.of(DOCROOT), SimpleFileServer.OutputLevel.INFO);
executor = Executors.newCachedThreadPool();
httpserver.setExecutor(executor);
httpserver.start();
remoteFilePath = httpserver.getAddress() + REMOTE_FILE_LOCATION;
remoteFilePath = URIBuilder.newBuilder()
.scheme("http")
.host(httpserver.getAddress().getAddress())
.port(httpserver.getAddress().getPort())
.build().toString() + REMOTE_FILE_LOCATION;
}
@AfterClass
protected void tearDown() {
if (httpserver != null) {
httpserver.stop();
httpserver.stop(0);
executor.shutdown();
}
}

View File

@ -1,71 +0,0 @@
/*
* Copyright (c) 2005, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.concurrent.*;
import java.util.logging.*;
import java.io.*;
import java.net.*;
import com.sun.net.httpserver.*;
/**
* Implements a basic static content HTTP server
* which understands text/html, text/plain content types
*
* Must be given an abs pathname to the document root.
* Directory listings together with text + html files
* can be served.
*
* File Server created on files sub-path
*
* Echo server created on echo sub-path
*/
public class SimpleFileServer {
public static void main (String[] args) throws Exception {
if (args.length != 3) {
System.out.println ("usage: java FileServerHandler rootDir port logfilename");
System.exit(1);
}
Logger logger = Logger.getLogger("com.sun.net.httpserver");
ConsoleHandler ch = new ConsoleHandler();
logger.setLevel(Level.ALL);
ch.setLevel(Level.ALL);
logger.addHandler(ch);
String rootDir = args[0];
int port = Integer.parseInt (args[1]);
String logfile = args[2];
HttpServer server = HttpServer.create (new InetSocketAddress (port), 0);
HttpHandler h = new FileServerHandler (rootDir);
HttpHandler h1 = new EchoHandler ();
HttpContext c = server.createContext ("/files", h);
c.getFilters().add (new LogFilter (new File (logfile)));
HttpContext c1 = server.createContext ("/echo", h1);
c.getFilters().add (new LogFilter (new File (logfile)));
c1.getFilters().add (new LogFilter (new File (logfile)));
server.setExecutor (Executors.newCachedThreadPool());
server.start ();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -28,9 +28,7 @@
* @library /lib/testlibrary/java/util/jar /test/lib
* @modules jdk.jartool
* jdk.compiler
* jdk.httpserver
* @build CreateMultiReleaseTestJars
* jdk.test.lib.net.SimpleHttpServer
* jdk.test.lib.compiler.Compiler
* jdk.test.lib.util.JarBuilder
* @run testng MultiReleaseJarHttpProperties
@ -51,21 +49,28 @@ import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import jdk.test.lib.net.SimpleHttpServer;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class MultiReleaseJarHttpProperties extends MultiReleaseJarProperties {
private SimpleHttpServer server;
private HttpServer server;
private ExecutorService executor;
static final String TESTCONTEXT = "/multi-release.jar"; //mapped to local file path
@BeforeClass
public void initialize() throws Exception {
server = new SimpleHttpServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), TESTCONTEXT,
System.getProperty("user.dir", "."));
server = SimpleFileServer.createFileServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0),
Path.of(System.getProperty("user.dir", ".")), SimpleFileServer.OutputLevel.INFO);
executor = Executors.newCachedThreadPool();
server.setExecutor(executor);
server.start();
super.initialize();
}
@ -73,7 +78,7 @@ public class MultiReleaseJarHttpProperties extends MultiReleaseJarProperties {
@Override
protected void initializeClassLoader() throws Exception {
URL[] urls = new URL[]{
URIBuilder.newBuilder().scheme("http").port(server.getPort()).loopback()
URIBuilder.newBuilder().scheme("http").port(server.getAddress().getPort()).loopback()
.path(TESTCONTEXT).toURL(),
};
cldr = new URLClassLoader(urls);
@ -84,8 +89,10 @@ public class MultiReleaseJarHttpProperties extends MultiReleaseJarProperties {
@AfterClass
public void close() throws IOException {
// Windows requires server to stop before file is deleted
if (server != null)
server.stop();
if (server != null) {
server.stop(0);
executor.shutdown();
}
super.close();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -27,10 +27,8 @@
* @summary Test that URL connections to multi-release jars can be runtime versioned
* @library /lib/testlibrary/java/util/jar /test/lib
* @modules jdk.compiler
* jdk.httpserver
* jdk.jartool
* @build CreateMultiReleaseTestJars
* jdk.test.lib.net.SimpleHttpServer
* jdk.test.lib.util.JarBuilder
* jdk.test.lib.compiler.Compiler
* @run testng MultiReleaseJarURLConnection
@ -51,11 +49,15 @@ import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.jar.JarFile;
import jdk.test.lib.net.SimpleHttpServer;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.SimpleFileServer;
import jdk.test.lib.net.URIBuilder;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
@ -68,8 +70,8 @@ public class MultiReleaseJarURLConnection {
String unversioned = userdir + "/unversioned.jar";
String unsigned = userdir + "/multi-release.jar";
String signed = userdir + "/signed-multi-release.jar";
static final String TESTCONTEXT = "/multi-release.jar";
SimpleHttpServer server;
HttpServer server;
ExecutorService executor;
@BeforeClass
public void initialize() throws Exception {
@ -78,7 +80,10 @@ public class MultiReleaseJarURLConnection {
creator.buildUnversionedJar();
creator.buildMultiReleaseJar();
creator.buildSignedMultiReleaseJar();
server = new SimpleHttpServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), TESTCONTEXT, System.getProperty("user.dir", "."));
server = SimpleFileServer.createFileServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0),
Path.of(System.getProperty("user.dir", ".")), SimpleFileServer.OutputLevel.INFO);
executor = Executors.newCachedThreadPool();
server.setExecutor(executor);
server.start();
}
@ -86,7 +91,9 @@ public class MultiReleaseJarURLConnection {
public void close() throws IOException {
// Windows requires server to stop before file is deleted
if (server != null)
server.stop();
server.stop(0);
executor.shutdown();
Files.delete(Paths.get(unversioned));
Files.delete(Paths.get(unsigned));
Files.delete(Paths.get(signed));
@ -176,8 +183,8 @@ public class MultiReleaseJarURLConnection {
{"unsigned", new URL("jar:file:" + unsigned + "!/")},
{"signed", new URL("jar:file:" + signed + "!/")},
// external jar received via http protocol
{"http", toHttpJarURL(server.getPort(), "/multi-release.jar", "!/")},
{"http", URIBuilder.newBuilder().scheme("http").port(server.getPort())
{"http", toHttpJarURL(server.getAddress().getPort(), "/multi-release.jar", "!/")},
{"http", URIBuilder.newBuilder().scheme("http").port(server.getAddress().getPort())
.loopback().path("/multi-release.jar").toURL()},
};
}

View File

@ -1,152 +0,0 @@
/*
* Copyright (c) 2017, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.test.lib.net;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
/**
* A simple HTTP Server.
**/
public class SimpleHttpServer {
private final HttpServer httpServer;
private ExecutorService executor;
private String address;
private final String context;
private final String docRoot;
private final InetSocketAddress inetSocketAddress;
public SimpleHttpServer(final InetSocketAddress inetSocketAddress, final String context, final String docRoot)
throws IOException {
this.inetSocketAddress = inetSocketAddress;
this.context = context;
this.docRoot = docRoot;
httpServer = HttpServer.create();
}
public void start() throws IOException, URISyntaxException {
MyHttpHandler handler = new MyHttpHandler(docRoot);
httpServer.bind(inetSocketAddress, 0);
httpServer.createContext(context, handler);
executor = Executors.newCachedThreadPool();
httpServer.setExecutor(executor);
httpServer.start();
address = "http:" + URIBuilder.newBuilder().host(httpServer.getAddress().getAddress()).
port(httpServer.getAddress().getPort()).build().toString();
}
public void stop() {
httpServer.stop(0);
executor.shutdown();
}
public String getAddress() {
return address;
}
public int getPort() {
return httpServer.getAddress().getPort();
}
class MyHttpHandler implements HttpHandler {
private final URI rootUri;
MyHttpHandler(final String docroot) {
rootUri = Path.of(docroot).toUri().normalize();
}
public void handle(final HttpExchange t) throws IOException {
try (InputStream is = t.getRequestBody()) {
is.readAllBytes();
Headers rMap = t.getResponseHeaders();
try (OutputStream os = t.getResponseBody()) {
URI uri = t.getRequestURI();
String path = uri.getRawPath();
assert path.isEmpty() || path.startsWith("/");
Path fPath;
try {
uri = URI.create("file://" + rootUri.getRawPath() + path).normalize();
fPath = Path.of(uri);
} catch (IllegalArgumentException | FileSystemNotFoundException ex) {
ex.printStackTrace();
notfound(t, path);
return;
}
byte[] bytes = Files.readAllBytes(fPath);
String method = t.getRequestMethod();
if (method.equals("HEAD")) {
rMap.set("Content-Length", Long.toString(bytes.length));
t.sendResponseHeaders(200, -1);
t.close();
} else if (!method.equals("GET")) {
t.sendResponseHeaders(405, -1);
t.close();
return;
}
if (path.endsWith(".html") || path.endsWith(".htm")) {
rMap.set("Content-Type", "text/html");
} else {
rMap.set("Content-Type", "text/plain");
}
t.sendResponseHeaders(200, bytes.length);
os.write(bytes);
}
}
}
void moved(final HttpExchange t) throws IOException {
Headers req = t.getRequestHeaders();
Headers map = t.getResponseHeaders();
URI uri = t.getRequestURI();
String host = req.getFirst("Host");
String location = "http://" + host + uri.getPath() + "/";
map.set("Content-Type", "text/html");
map.set("Location", location);
t.sendResponseHeaders(301, -1);
t.close();
}
void notfound(final HttpExchange t, final String p) throws IOException {
t.getResponseHeaders().set("Content-Type", "text/html");
t.sendResponseHeaders(404, 0);
try (OutputStream os = t.getResponseBody()) {
String s = "<h2>File not found</h2>";
s = s + p + "<p>";
os.write(s.getBytes());
}
t.close();
}
}
}