8212035: merge jdk.test.lib.util.SimpleHttpServer with jaxp.library.SimpleHttpServer

Reviewed-by: dfuchs
This commit is contained in:
Mahendra Chhipa 2021-01-13 15:53:05 +00:00 committed by Daniel Fuchs
parent 535f2da5e2
commit 5df2a949e3
17 changed files with 330 additions and 424 deletions

View File

@ -1,177 +0,0 @@
/*
* Copyright (c) 2017, 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 jaxp.library;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* A simple HTTP Server
*/
public class SimpleHttpServer {
HttpServer _httpserver;
ExecutorService _executor;
String _address;
String _context, _docroot;
int _port;
public SimpleHttpServer(String context, String docroot) {
//let the system pick up an ephemeral port in a bind operation
this(0, context, docroot);
}
public SimpleHttpServer(int port, String context, String docroot) {
_port = port;
_context = context;
_docroot = docroot;
}
public void start() {
MyHttpHandler handler = new MyHttpHandler(_docroot);
InetSocketAddress addr = new InetSocketAddress(_port);
try {
_httpserver = HttpServer.create(addr, 0);
} catch (IOException ex) {
throw new RuntimeException("cannot create httpserver", ex);
}
//TestHandler is mapped to /test
HttpContext ctx = _httpserver.createContext(_context, handler);
_executor = Executors.newCachedThreadPool();
_httpserver.setExecutor(_executor);
_httpserver.start();
_address = "http://localhost:" + _httpserver.getAddress().getPort();
}
public void stop() {
_httpserver.stop(2);
_executor.shutdown();
}
public String getAddress() {
return _address;
}
static class MyHttpHandler implements HttpHandler {
String _docroot;
public MyHttpHandler(String docroot) {
_docroot = docroot;
}
public void handle(HttpExchange t)
throws IOException {
InputStream is = t.getRequestBody();
Headers map = t.getRequestHeaders();
Headers rmap = t.getResponseHeaders();
OutputStream os = t.getResponseBody();
URI uri = t.getRequestURI();
String path = uri.getPath();
while (is.read() != -1) ;
is.close();
File f = new File(_docroot, path);
if (!f.exists()) {
notfound(t, path);
return;
}
String method = t.getRequestMethod();
if (method.equals("HEAD")) {
rmap.set("Content-Length", Long.toString(f.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, f.length());
FileInputStream fis = new FileInputStream(f);
int count = 0;
try {
byte[] buf = new byte[16 * 1024];
int len;
while ((len = fis.read(buf)) != -1) {
os.write(buf, 0, len);
count += len;
}
} catch (IOException e) {
e.printStackTrace();
}
fis.close();
os.close();
}
void moved(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(HttpExchange t, String p) throws IOException {
t.getResponseHeaders().set("Content-Type", "text/html");
t.sendResponseHeaders(404, 0);
OutputStream os = t.getResponseBody();
String s = "<h2>File not found</h2>";
s = s + p + "<p>";
os.write(s.getBytes());
os.close();
t.close();
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2020, 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
@ -20,6 +20,7 @@
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package catalog;
import java.io.BufferedOutputStream;
@ -31,22 +32,24 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import javax.xml.catalog.Catalog;
import javax.xml.catalog.CatalogException;
import javax.xml.catalog.CatalogFeatures;
import javax.xml.catalog.CatalogManager;
import javax.xml.catalog.CatalogResolver;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static jaxp.library.JAXPTestUtilities.getSystemProperty;
import jaxp.library.SimpleHttpServer;
import jdk.test.lib.util.JarUtils;
import jdk.test.lib.util.JarUtils;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
@ -54,11 +57,13 @@ import org.testng.annotations.DataProvider;
import org.testng.annotations.Listeners;
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
@ -72,7 +77,6 @@ public class CatalogFileInputTest extends CatalogSupportBase {
static final CatalogFeatures FEATURES = CatalogFeatures.builder().
with(CatalogFeatures.Feature.PREFER, "system").build();
static String USER_DIR = getSystemProperty("user.dir");
static String CLS_DIR = getSystemProperty("test.classes");
static String SRC_DIR = System.getProperty("test.src");
static String JAR_CONTENT = "META-INF";
@ -80,8 +84,8 @@ public class CatalogFileInputTest extends CatalogSupportBase {
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
SimpleHttpServer _httpserver;
String _remoteFilePath;
private SimpleHttpServer httpserver;
private String remoteFilePath;
/*
* Initializing fields
@ -89,18 +93,16 @@ public class CatalogFileInputTest extends CatalogSupportBase {
@BeforeClass
public void setUpClass() throws Exception {
super.setUp();
// set up HttpServer
_httpserver = new SimpleHttpServer(TESTCONTEXT, DOCROOT);
_httpserver.start();
_remoteFilePath = _httpserver.getAddress() + REMOTE_FILE_LOCATION;
httpserver = new SimpleHttpServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), TESTCONTEXT, DOCROOT);
httpserver.start();
remoteFilePath = httpserver.getAddress() + REMOTE_FILE_LOCATION;
}
@AfterClass
protected void tearDown() throws Exception {
if (_httpserver != null) {
_httpserver.stop();
protected void tearDown() {
if (httpserver != null) {
httpserver.stop();
}
}
@ -109,8 +111,8 @@ public class CatalogFileInputTest extends CatalogSupportBase {
* and http URL, and used to resolve a systemId as expected.
*/
@Test(dataProvider = "acceptedURI")
public void testMatch(String uri, String sysId, String pubId,
String expectedId, String msg) throws Exception {
public void testMatch(final String uri, final String sysId, final String pubId,
final String expectedId, final String msg) {
CatalogResolver cr = CatalogManager.catalogResolver(FEATURES, URI.create(uri));
InputSource is = cr.resolveEntity(pubId, sysId);
Assert.assertNotNull(is, msg);
@ -118,42 +120,42 @@ public class CatalogFileInputTest extends CatalogSupportBase {
}
@Test(dataProvider = "invalidCatalog")
public void testEmptyCatalog(String uri, String publicId, String msg) {
Catalog c = CatalogManager.catalog(FEATURES, uri != null? URI.create(uri) : null);
public void testEmptyCatalog(final String uri, final String publicId, final String msg) {
Catalog c = CatalogManager.catalog(FEATURES, uri != null ? URI.create(uri) : null);
Assert.assertNull(c.matchSystem(publicId), msg);
}
@Test(dataProvider = "invalidCatalog", expectedExceptions = CatalogException.class)
public void testCatalogResolverWEmptyCatalog(String uri, String publicId, String msg) {
public void testCatalogResolverWEmptyCatalog(final String uri, final String publicId, final String msg) {
CatalogResolver cr = CatalogManager.catalogResolver(
CatalogFeatures.builder().with(CatalogFeatures.Feature.RESOLVE, "strict").build(),
uri != null? URI.create(uri) : null);
uri != null ? URI.create(uri) : null);
InputSource is = cr.resolveEntity(publicId, "");
}
@Test(dataProvider = "invalidCatalog")
public void testCatalogResolverWEmptyCatalog1(String uri, String publicId, String msg) {
public void testCatalogResolverWEmptyCatalog1(final String uri, final String publicId, final String msg) {
CatalogResolver cr = CatalogManager.catalogResolver(
CatalogFeatures.builder().with(CatalogFeatures.Feature.RESOLVE, "continue").build(),
uri != null? URI.create(uri) : null);
uri != null ? URI.create(uri) : null);
Assert.assertNull(cr.resolveEntity(publicId, ""), msg);
}
@Test(dataProvider = "invalidInput", expectedExceptions = IllegalArgumentException.class)
public void testFileInput(String file) {
public void testFileInput(final String file) {
CatalogFeatures features = CatalogFeatures.builder()
.with(CatalogFeatures.Feature.FILES, file)
.build();
}
@Test(dataProvider = "invalidInput", expectedExceptions = IllegalArgumentException.class)
public void testInvalidUri(String file) {
CatalogResolver cr = CatalogManager.catalogResolver(FEATURES, file != null? URI.create(file) : null);
public void testInvalidUri(final String file) {
CatalogResolver cr = CatalogManager.catalogResolver(FEATURES, file != null ? URI.create(file) : null);
}
@Test(dataProvider = "invalidInput", expectedExceptions = IllegalArgumentException.class)
public void testInvalidUri1(String file) {
Catalog c = CatalogManager.catalog(FEATURES, file != null? URI.create(file) : null);
public void testInvalidUri1(final String file) {
Catalog c = CatalogManager.catalog(FEATURES, file != null ? URI.create(file) : null);
System.err.println("Catalog =" + c);
}
@ -177,10 +179,10 @@ public class CatalogFileInputTest extends CatalogSupportBase {
Catalog c = CatalogManager.catalog(FEATURES, uri);
}
String systemId = "http://www.sys00test.com/rewrite.dtd";
String publicId = "PUB-404";
String expected = "http://www.groupxmlbase.com/dtds/rewrite.dtd";
String errMsg = "Relative rewriteSystem with xml:base at group level failed";
private String systemId = "http://www.sys00test.com/rewrite.dtd";
private String publicId = "PUB-404";
private String expected = "http://www.groupxmlbase.com/dtds/rewrite.dtd";
private String errMsg = "Relative rewriteSystem with xml:base at group level failed";
/*
DataProvider: used to verify CatalogResolver's resolveEntity function.
@ -191,8 +193,8 @@ public class CatalogFileInputTest extends CatalogSupportBase {
Object[][] getData() throws Exception {
String filename = "rewriteSystem_id.xml";
String urlFile = getClass().getResource(filename).toExternalForm();
String urlHttp = _remoteFilePath + "/jax-ws-catalog.xml";
String remoteXSD = _remoteFilePath + "/catalog/ws-addr.xsd";
String urlHttp = remoteFilePath + "/jax-ws-catalog.xml";
String remoteXSD = remoteFilePath + "/catalog/ws-addr.xsd";
File file = new File(CLS_DIR + "/JDK8171243.jar!/META-INF/jax-ws-catalog.xml");
String jarPath = SCHEME_JARFILE + file.toURI().toString();
String xsd = jarPath.substring(0, jarPath.lastIndexOf("/")) + "/catalog/ws-addr.xsd";
@ -220,7 +222,7 @@ public class CatalogFileInputTest extends CatalogSupportBase {
* rejected with an IAE.
*/
@DataProvider(name = "invalidCatalog")
public Object[][] getInvalidCatalog() throws Exception {
public Object[][] getInvalidCatalog() {
String catalogUri = getClass().getResource("catalog_invalid.xml").toExternalForm();
return new Object[][]{
{catalogUri, "-//W3C//DTD XHTML 1.0 Strict//EN",
@ -259,22 +261,20 @@ public class CatalogFileInputTest extends CatalogSupportBase {
DataProvider: a list of invalid inputs
*/
@DataProvider(name = "nullTest")
public Object[][] getNull() throws Exception {
public Object[][] getNull() {
return new Object[][]{
{null},
};
}
void copyFile(Path src, Path target) throws Exception {
void copyFile(final Path src, final Path target) throws Exception {
try (InputStream in = Files.newInputStream(src);
BufferedReader reader
= new BufferedReader(new InputStreamReader(in));
OutputStream out = new BufferedOutputStream(
Files.newOutputStream(target, CREATE, APPEND));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out))) {
String line = null;
String line;
while ((line = reader.readLine()) != null) {
bw.write(line);
}

View File

@ -48,7 +48,6 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import jdk.test.lib.RandomFactory;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;

View File

@ -30,7 +30,7 @@
* jdk.compiler
* jdk.httpserver
* @build CreateMultiReleaseTestJars
* SimpleHttpServer
* jdk.test.lib.net.SimpleHttpServer
* jdk.test.lib.compiler.Compiler
* jdk.test.lib.util.JarBuilder
* @run testng MultiReleaseJarHttpProperties
@ -48,22 +48,24 @@
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLClassLoader;
import jdk.test.lib.net.SimpleHttpServer;
import jdk.test.lib.net.URIBuilder;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class MultiReleaseJarHttpProperties extends MultiReleaseJarProperties {
private SimpleHttpServer server;
static final String TESTCONTEXT = "/multi-release.jar"; //mapped to local file path
@BeforeClass
public void initialize() throws Exception {
server = new SimpleHttpServer(InetAddress.getLoopbackAddress());
server = new SimpleHttpServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), TESTCONTEXT,
System.getProperty("user.dir", "."));
server.start();
super.initialize();
}
@ -72,7 +74,7 @@ public class MultiReleaseJarHttpProperties extends MultiReleaseJarProperties {
protected void initializeClassLoader() throws Exception {
URL[] urls = new URL[]{
URIBuilder.newBuilder().scheme("http").port(server.getPort()).loopback()
.path("/multi-release.jar").toURL(),
.path(TESTCONTEXT).toURL(),
};
cldr = new URLClassLoader(urls);
// load any class, Main is convenient and in the root entries

View File

@ -72,7 +72,7 @@ public class MultiReleaseJarProperties {
@BeforeClass
public void initialize() throws Exception {
CreateMultiReleaseTestJars creator = new CreateMultiReleaseTestJars();
CreateMultiReleaseTestJars creator = new CreateMultiReleaseTestJars();
creator.compileEntries();
creator.buildMultiReleaseJar();
int RUNTIME_VERSION = Runtime.version().major();
@ -99,7 +99,7 @@ public class MultiReleaseJarProperties {
@AfterClass
public void close() throws IOException {
((URLClassLoader)cldr).close();
((URLClassLoader) cldr).close();
Files.delete(multirelease.toPath());
}

View File

@ -32,11 +32,6 @@
* @run testng TestVersionedStream
*/
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@ -59,6 +54,10 @@ import java.util.stream.Stream;
import java.util.zip.ZipFile;
import jdk.test.lib.util.FileUtils;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class TestVersionedStream {
private final Path userdir;

View File

@ -35,10 +35,11 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipFile;
import jdk.security.jarsigner.JarSigner;
import java.io.File;
import jdk.test.lib.util.JarBuilder;
import jdk.security.jarsigner.JarSigner;
import jdk.test.lib.compiler.Compiler;
import jdk.test.lib.util.JarBuilder;
public class CreateMultiReleaseTestJars {
final private String main =

View File

@ -1,81 +0,0 @@
/*
* Copyright (c) 2015, 2019, 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 com.sun.net.httpserver.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Extremely simple server that only performs one task. The server listens for
* requests on the ephemeral port. If it sees a request that begins with
* "/multi-release.jar", it consumes the request and returns a stream of bytes
* representing the jar file multi-release.jar found in "userdir".
*/
class SimpleHttpServer {
private static final String userdir = System.getProperty("user.dir", ".");
private static final Path multirelease = Paths.get(userdir, "multi-release.jar");
private final HttpServer server;
private final InetAddress address;
public SimpleHttpServer() throws IOException {
this(null);
}
public SimpleHttpServer(InetAddress addr) throws IOException {
address = addr;
server = HttpServer.create();
}
public void start() throws IOException {
server.bind(new InetSocketAddress(address, 0), 0);
server.createContext("/multi-release.jar", t -> {
try (InputStream is = t.getRequestBody()) {
is.readAllBytes(); // probably not necessary to consume request
byte[] bytes = Files.readAllBytes(multirelease);
t.sendResponseHeaders(200, bytes.length);
try (OutputStream os = t.getResponseBody()) {
os.write(bytes);
}
}
});
server.setExecutor(null); // creates a default executor
server.start();
}
public void stop() {
server.stop(0);
}
int getPort() {
return server.getAddress().getPort();
}
}

View File

@ -26,8 +26,11 @@
* @bug 4756443
* @summary REGRESSION: NPE in JarURLConnection.getLastModified after setUseCache(false)
*/
import java.io.*;
import java.net.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class B4756443 {

View File

@ -35,6 +35,7 @@ import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
public class B5105410 {

View File

@ -28,10 +28,13 @@
* @run main/othervm JarURLConnectionUseCaches
*/
import java.io.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.jar.*;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
public class JarURLConnectionUseCaches {
public static void main( String[] args ) throws IOException {

View File

@ -30,7 +30,7 @@
* jdk.httpserver
* jdk.jartool
* @build CreateMultiReleaseTestJars
* SimpleHttpServer
* jdk.test.lib.net.SimpleHttpServer
* jdk.test.lib.util.JarBuilder
* jdk.test.lib.compiler.Compiler
* @run testng MultiReleaseJarURLConnection
@ -42,6 +42,7 @@ import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
@ -54,8 +55,8 @@ import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.jar.JarFile;
import jdk.test.lib.net.SimpleHttpServer;
import jdk.test.lib.net.URIBuilder;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
@ -63,10 +64,11 @@ import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class MultiReleaseJarURLConnection {
String userdir = System.getProperty("user.dir",".");
String userdir = System.getProperty("user.dir", ".");
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;
@BeforeClass
@ -76,10 +78,8 @@ public class MultiReleaseJarURLConnection {
creator.buildUnversionedJar();
creator.buildMultiReleaseJar();
creator.buildSignedMultiReleaseJar();
server = new SimpleHttpServer(InetAddress.getLoopbackAddress());
server = new SimpleHttpServer(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), TESTCONTEXT, System.getProperty("user.dir", "."));
server.start();
}
@AfterClass
@ -134,12 +134,12 @@ public class MultiReleaseJarURLConnection {
String urlFile = "jar:file:" + file + "!/";
URL rootUrl = new URL(urlFile);
JarURLConnection juc = (JarURLConnection)rootUrl.openConnection();
JarURLConnection juc = (JarURLConnection) rootUrl.openConnection();
JarFile rootJar = juc.getJarFile();
Runtime.Version root = rootJar.getVersion();
URL runtimeUrl = new URL(urlFile + "#runtime");
juc = (JarURLConnection)runtimeUrl.openConnection();
juc = (JarURLConnection) runtimeUrl.openConnection();
JarFile runtimeJar = juc.getJarFile();
Runtime.Version runtime = runtimeJar.getVersion();
if (style.equals("unversioned")) {
@ -148,12 +148,12 @@ public class MultiReleaseJarURLConnection {
Assert.assertNotEquals(root, runtime);
}
juc = (JarURLConnection)rootUrl.openConnection();
juc = (JarURLConnection) rootUrl.openConnection();
JarFile jar = juc.getJarFile();
Assert.assertEquals(jar.getVersion(), root);
Assert.assertEquals(jar, rootJar);
juc = (JarURLConnection)runtimeUrl.openConnection();
juc = (JarURLConnection) runtimeUrl.openConnection();
jar = juc.getJarFile();
Assert.assertEquals(jar.getVersion(), runtime);
Assert.assertEquals(jar, runtimeJar);
@ -184,7 +184,7 @@ public class MultiReleaseJarURLConnection {
@Test(dataProvider = "resourcedata")
public void testResources(String style, URL url) throws Throwable {
//System.out.println(" testing " + style + " url: " + url);
// System.out.println(" testing " + style + " url: " + url);
URL[] urls = {url};
URLClassLoader cldr = new URLClassLoader(urls);
Class<?> vcls = cldr.loadClass("version.Version");
@ -251,7 +251,7 @@ public class MultiReleaseJarURLConnection {
result = (new String(bytes)).contains(match);
}
if (conn instanceof JarURLConnection) {
((JarURLConnection)conn).getJarFile().close();
((JarURLConnection) conn).getJarFile().close();
}
return result;
}

View File

@ -39,16 +39,16 @@
* @run main/othervm TestDriver
*/
import jdk.test.lib.JDKToolFinder;
import jdk.test.lib.compiler.CompilerUtils;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.JarUtils;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import jdk.test.lib.JDKToolFinder;
import jdk.test.lib.compiler.CompilerUtils;
import jdk.test.lib.process.ProcessTools;
import jdk.test.lib.util.JarUtils;
public class TestDriver {
public static void main(String[] args) throws Throwable {

View File

@ -23,8 +23,7 @@
package jar1;
import java.io.*;
import java.util.*;
import java.io.InputStream;
public class GetResource {

View File

@ -23,8 +23,9 @@
package jar1;
import java.io.*;
import java.util.*;
import java.io.InputStream;
import java.util.Locale;
import java.util.ResourceBundle;
public class LoadResourceBundle {

View File

@ -21,102 +21,105 @@
* questions.
*/
import java.io.*;
import java.net.*;
import java.util.jar.*;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
public abstract class JarTest
{
static String tmpdir = System.getProperty("java.io.tmpdir");
static String javaCmd = System.getProperty("java.home") + File.separator +
"bin" + File.separator + "java";
public abstract class JarTest {
static String tmpdir = System.getProperty("java.io.tmpdir");
static String javaCmd = System.getProperty("java.home") + File.separator +
"bin" + File.separator + "java";
/**
* Reads an input stream into a byte array.
*/
protected byte[] readFully(InputStream in) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[32];
int count;
/**
* Reads an input stream into a byte array.
*/
protected byte[] readFully(InputStream in) throws Exception {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[32];
int count;
while ((count = in.read(buffer)) >= 0) {
out.write(buffer, 0, count);
}
return out.toByteArray();
while ((count = in.read(buffer)) >= 0) {
out.write(buffer, 0, count);
}
/**
* Copies the named resource into the directory specified.
*/
protected File copyResource(File dir, String resName) throws Exception {
BufferedOutputStream buffOut = null;
FileOutputStream fileOut;
InputStream in = null;
File file = null;
byte[] buffer;
int count;
return out.toByteArray();
}
file = new File(dir, resName);
/**
* Copies the named resource into the directory specified.
*/
protected File copyResource(File dir, String resName) throws Exception {
BufferedOutputStream buffOut = null;
FileOutputStream fileOut;
InputStream in = null;
File file = null;
byte[] buffer;
int count;
file = new File(dir, resName);
try {
fileOut = new FileOutputStream(file);
buffOut = new BufferedOutputStream(fileOut);
in = getClass().getResourceAsStream(resName);
buffer = new byte[1024];
while ((count = in.read(buffer)) >= 0) {
buffOut.write(buffer, 0, count);
}
buffOut.flush();
} finally {
if (buffOut != null) {
try {
fileOut = new FileOutputStream(file);
buffOut = new BufferedOutputStream(fileOut);
in = getClass().getResourceAsStream(resName);
buffer = new byte[1024];
while ((count = in.read(buffer)) >= 0) {
buffOut.write(buffer, 0, count);
}
buffOut.flush();
} finally {
if (buffOut != null) {
try {
buffOut.close();
} catch (IOException e) {
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
buffOut.close();
} catch (IOException e) {
}
return file;
}
/**
* Utility to create a temp dir.
*/
protected File createTempDir() throws Exception {
File result = new File(tmpdir + File.separator + getClass().getName());
result.delete();
result.mkdirs();
return result;
}
/**
* Utility to recursively delete a directory.
*/
protected boolean deleteRecursively(File file) {
File[] children;
boolean result = true;
children = file.listFiles();
if (children != null) {
for (int i=0; i<children.length; i++) {
result = result && deleteRecursively(children[i]);
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
result = result && file.delete();
return result;
}
}
static class Redirector implements Runnable
{
return file;
}
/**
* Utility to create a temp dir.
*/
protected File createTempDir() throws Exception {
File result = new File(tmpdir + File.separator + getClass().getName());
result.delete();
result.mkdirs();
return result;
}
/**
* Utility to recursively delete a directory.
*/
protected boolean deleteRecursively(File file) {
File[] children;
boolean result = true;
children = file.listFiles();
if (children != null) {
for (int i = 0; i < children.length; i++) {
result = result && deleteRecursively(children[i]);
}
}
result = result && file.delete();
return result;
}
static class Redirector implements Runnable {
private BufferedReader reader;
private PrintStream out;
private boolean hasReadData;

View File

@ -0,0 +1,153 @@
/*
* Copyright (c) 2017, 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(2);
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 | SecurityException 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();
}
}
}