mirror of
https://github.com/openjdk/jdk.git
synced 2026-03-05 21:50:20 +00:00
8237470: HttpResponse.BodySubscriber::ofFile throws UOE with non-default file systems
Rework non-default file system paths of BodySubscriber::ofFile and BodyHandler::ofFile and fix BodyHandler::ofFileDownload to throw consistently for non-default file system paths Reviewed-by: dfuchs, chegar
This commit is contained in:
parent
55ed0d853f
commit
c0a1a4e4fc
@ -506,18 +506,24 @@ public interface HttpResponse<T> {
|
||||
* been completely written to the file, and {@link #body()} returns a
|
||||
* reference to its {@link Path}.
|
||||
*
|
||||
* <p> Security manager permission checks are performed in this factory
|
||||
* method, when the {@code BodyHandler} is created. Care must be taken
|
||||
* that the {@code BodyHandler} is not shared with untrusted code.
|
||||
* <p> In the case of the default file system provider, security manager
|
||||
* permission checks are performed in this factory method, when the
|
||||
* {@code BodyHandler} is created. Otherwise,
|
||||
* {@linkplain FileChannel#open(Path, OpenOption...) permission checks}
|
||||
* may be performed asynchronously against the caller's context
|
||||
* at file access time.
|
||||
* Care must be taken that the {@code BodyHandler} is not shared with
|
||||
* untrusted code.
|
||||
*
|
||||
* @param file the file to store the body in
|
||||
* @param openOptions any options to use when opening/creating the file
|
||||
* @param file the file to store the body in
|
||||
* @param openOptions any options to use when opening/creating the file
|
||||
* @return a response body handler
|
||||
* @throws IllegalArgumentException if an invalid set of open options
|
||||
* are specified
|
||||
* @throws SecurityException If a security manager has been installed
|
||||
* and it denies {@linkplain SecurityManager#checkWrite(String)
|
||||
* write access} to the file.
|
||||
* are specified
|
||||
* @throws SecurityException in the case of the default file system
|
||||
* provider, and a security manager is installed,
|
||||
* {@link SecurityManager#checkWrite(String) checkWrite}
|
||||
* is invoked to check write access to the given file
|
||||
*/
|
||||
public static BodyHandler<Path> ofFile(Path file, OpenOption... openOptions) {
|
||||
Objects.requireNonNull(file);
|
||||
@ -535,15 +541,21 @@ public interface HttpResponse<T> {
|
||||
*
|
||||
* <p> Equivalent to: {@code ofFile(file, CREATE, WRITE)}
|
||||
*
|
||||
* <p> Security manager permission checks are performed in this factory
|
||||
* method, when the {@code BodyHandler} is created. Care must be taken
|
||||
* that the {@code BodyHandler} is not shared with untrusted code.
|
||||
* <p> In the case of the default file system provider, security manager
|
||||
* permission checks are performed in this factory method, when the
|
||||
* {@code BodyHandler} is created. Otherwise,
|
||||
* {@linkplain FileChannel#open(Path, OpenOption...) permission checks}
|
||||
* may be performed asynchronously against the caller's context
|
||||
* at file access time.
|
||||
* Care must be taken that the {@code BodyHandler} is not shared with
|
||||
* untrusted code.
|
||||
*
|
||||
* @param file the file to store the body in
|
||||
* @param file the file to store the body in
|
||||
* @return a response body handler
|
||||
* @throws SecurityException If a security manager has been installed
|
||||
* and it denies {@linkplain SecurityManager#checkWrite(String)
|
||||
* write access} to the file.
|
||||
* @throws SecurityException in the case of the default file system
|
||||
* provider, and a security manager is installed,
|
||||
* {@link SecurityManager#checkWrite(String) checkWrite}
|
||||
* is invoked to check write access to the given file
|
||||
*/
|
||||
public static BodyHandler<Path> ofFile(Path file) {
|
||||
return BodyHandlers.ofFile(file, CREATE, WRITE);
|
||||
@ -570,20 +582,22 @@ public interface HttpResponse<T> {
|
||||
* method, when the {@code BodyHandler} is created. Care must be taken
|
||||
* that the {@code BodyHandler} is not shared with untrusted code.
|
||||
*
|
||||
* @param directory the directory to store the file in
|
||||
* @param openOptions open options used when opening the file
|
||||
* @param directory the directory to store the file in
|
||||
* @param openOptions open options used when opening the file
|
||||
* @return a response body handler
|
||||
* @throws IllegalArgumentException if the given path does not exist,
|
||||
* is not a directory, is not writable, or if an invalid set
|
||||
* of open options are specified
|
||||
* @throws SecurityException If a security manager has been installed
|
||||
* and it denies
|
||||
* {@linkplain SecurityManager#checkRead(String) read access}
|
||||
* to the directory, or it denies
|
||||
* {@linkplain SecurityManager#checkWrite(String) write access}
|
||||
* to the directory, or it denies
|
||||
* {@linkplain SecurityManager#checkWrite(String) write access}
|
||||
* to the files within the directory.
|
||||
* is not of the default file system, is not a directory,
|
||||
* is not writable, or if an invalid set of open options
|
||||
* are specified
|
||||
* @throws SecurityException in the case of the default file system
|
||||
* provider and a security manager has been installed,
|
||||
* and it denies
|
||||
* {@linkplain SecurityManager#checkRead(String) read access}
|
||||
* to the directory, or it denies
|
||||
* {@linkplain SecurityManager#checkWrite(String) write access}
|
||||
* to the directory, or it denies
|
||||
* {@linkplain SecurityManager#checkWrite(String) write access}
|
||||
* to the files within the directory.
|
||||
*/
|
||||
public static BodyHandler<Path> ofFileDownload(Path directory,
|
||||
OpenOption... openOptions) {
|
||||
@ -1068,18 +1082,24 @@ public interface HttpResponse<T> {
|
||||
* <p> The {@link HttpResponse} using this subscriber is available after
|
||||
* the entire response has been read.
|
||||
*
|
||||
* <p> Security manager permission checks are performed in this factory
|
||||
* method, when the {@code BodySubscriber} is created. Care must be taken
|
||||
* that the {@code BodyHandler} is not shared with untrusted code.
|
||||
* <p> In the case of the default file system provider, security manager
|
||||
* permission checks are performed in this factory method, when the
|
||||
* {@code BodySubscriber} is created. Otherwise,
|
||||
* {@linkplain FileChannel#open(Path, OpenOption...) permission checks}
|
||||
* may be performed asynchronously against the caller's context
|
||||
* at file access time.
|
||||
* Care must be taken that the {@code BodySubscriber} is not shared with
|
||||
* untrusted code.
|
||||
*
|
||||
* @param file the file to store the body in
|
||||
* @param openOptions the list of options to open the file with
|
||||
* @param file the file to store the body in
|
||||
* @param openOptions the list of options to open the file with
|
||||
* @return a body subscriber
|
||||
* @throws IllegalArgumentException if an invalid set of open options
|
||||
* are specified
|
||||
* @throws SecurityException if a security manager has been installed
|
||||
* and it denies {@linkplain SecurityManager#checkWrite(String)
|
||||
* write access} to the file
|
||||
* are specified
|
||||
* @throws SecurityException in the case of the default file system
|
||||
* provider, and a security manager is installed,
|
||||
* {@link SecurityManager#checkWrite(String) checkWrite}
|
||||
* is invoked to check write access to the given file
|
||||
*/
|
||||
public static BodySubscriber<Path> ofFile(Path file, OpenOption... openOptions) {
|
||||
Objects.requireNonNull(file);
|
||||
@ -1097,15 +1117,21 @@ public interface HttpResponse<T> {
|
||||
*
|
||||
* <p> Equivalent to: {@code ofFile(file, CREATE, WRITE)}
|
||||
*
|
||||
* <p> Security manager permission checks are performed in this factory
|
||||
* method, when the {@code BodySubscriber} is created. Care must be taken
|
||||
* that the {@code BodyHandler} is not shared with untrusted code.
|
||||
* <p> In the case of the default file system provider, security manager
|
||||
* permission checks are performed in this factory method, when the
|
||||
* {@code BodySubscriber} is created. Otherwise,
|
||||
* {@linkplain FileChannel#open(Path, OpenOption...) permission checks}
|
||||
* may be performed asynchronously against the caller's context
|
||||
* at file access time.
|
||||
* Care must be taken that the {@code BodySubscriber} is not shared with
|
||||
* untrusted code.
|
||||
*
|
||||
* @param file the file to store the body in
|
||||
* @param file the file to store the body in
|
||||
* @return a body subscriber
|
||||
* @throws SecurityException if a security manager has been installed
|
||||
* and it denies {@linkplain SecurityManager#checkWrite(String)
|
||||
* write access} to the file
|
||||
* @throws SecurityException in the case of the default file system
|
||||
* provider, and a security manager is installed,
|
||||
* {@link SecurityManager#checkWrite(String) checkWrite}
|
||||
* is invoked to check write access to the given file
|
||||
*/
|
||||
public static BodySubscriber<Path> ofFile(Path file) {
|
||||
return ofFile(file, CREATE, WRITE);
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
|
||||
* Copyright (c) 2018, 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
|
||||
@ -34,11 +34,12 @@ import java.nio.file.Files;
|
||||
import java.nio.file.OpenOption;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.security.AccessControlContext;
|
||||
import java.security.AccessController;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.function.Function;
|
||||
import java.net.http.HttpHeaders;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.net.http.HttpResponse.BodyHandler;
|
||||
@ -63,6 +64,7 @@ public final class ResponseBodyHandlers {
|
||||
public static class PathBodyHandler implements BodyHandler<Path>{
|
||||
private final Path file;
|
||||
private final List<OpenOption> openOptions; // immutable list
|
||||
private final AccessControlContext acc;
|
||||
private final FilePermission filePermission;
|
||||
|
||||
/**
|
||||
@ -77,25 +79,34 @@ public final class ResponseBodyHandlers {
|
||||
FilePermission filePermission = null;
|
||||
SecurityManager sm = System.getSecurityManager();
|
||||
if (sm != null) {
|
||||
String fn = pathForSecurityCheck(file);
|
||||
FilePermission writePermission = new FilePermission(fn, "write");
|
||||
sm.checkPermission(writePermission);
|
||||
filePermission = writePermission;
|
||||
try {
|
||||
String fn = pathForSecurityCheck(file);
|
||||
FilePermission writePermission = new FilePermission(fn, "write");
|
||||
sm.checkPermission(writePermission);
|
||||
filePermission = writePermission;
|
||||
} catch (UnsupportedOperationException ignored) {
|
||||
// path not associated with the default file system provider
|
||||
}
|
||||
}
|
||||
return new PathBodyHandler(file, openOptions, filePermission);
|
||||
|
||||
assert filePermission == null || filePermission.getActions().equals("write");
|
||||
var acc = sm != null ? AccessController.getContext() : null;
|
||||
return new PathBodyHandler(file, openOptions, acc, filePermission);
|
||||
}
|
||||
|
||||
private PathBodyHandler(Path file,
|
||||
List<OpenOption> openOptions,
|
||||
AccessControlContext acc,
|
||||
FilePermission filePermission) {
|
||||
this.file = file;
|
||||
this.openOptions = openOptions;
|
||||
this.acc = acc;
|
||||
this.filePermission = filePermission;
|
||||
}
|
||||
|
||||
@Override
|
||||
public BodySubscriber<Path> apply(ResponseInfo responseInfo) {
|
||||
return new PathSubscriber(file, openOptions, filePermission);
|
||||
return new PathSubscriber(file, openOptions, acc, filePermission);
|
||||
}
|
||||
}
|
||||
|
||||
@ -149,6 +160,7 @@ public final class ResponseBodyHandlers {
|
||||
public static class FileDownloadBodyHandler implements BodyHandler<Path> {
|
||||
private final Path directory;
|
||||
private final List<OpenOption> openOptions;
|
||||
private final AccessControlContext acc;
|
||||
private final FilePermission[] filePermissions; // may be null
|
||||
|
||||
/**
|
||||
@ -160,10 +172,17 @@ public final class ResponseBodyHandlers {
|
||||
*/
|
||||
public static FileDownloadBodyHandler create(Path directory,
|
||||
List<OpenOption> openOptions) {
|
||||
String fn;
|
||||
try {
|
||||
fn = pathForSecurityCheck(directory);
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
// directory not associated with the default file system provider
|
||||
throw new IllegalArgumentException("invalid path: " + directory, uoe);
|
||||
}
|
||||
|
||||
FilePermission filePermissions[] = null;
|
||||
SecurityManager sm = System.getSecurityManager();
|
||||
if (sm != null) {
|
||||
String fn = pathForSecurityCheck(directory);
|
||||
FilePermission writePermission = new FilePermission(fn, "write");
|
||||
String writePathPerm = fn + File.separatorChar + "*";
|
||||
FilePermission writeInDirPermission = new FilePermission(writePathPerm, "write");
|
||||
@ -184,15 +203,19 @@ public final class ResponseBodyHandlers {
|
||||
if (!Files.isWritable(directory))
|
||||
throw new IllegalArgumentException("non-writable directory: " + directory);
|
||||
|
||||
return new FileDownloadBodyHandler(directory, openOptions, filePermissions);
|
||||
|
||||
assert filePermissions == null || (filePermissions[0].getActions().equals("write")
|
||||
&& filePermissions[1].getActions().equals("write"));
|
||||
var acc = sm != null ? AccessController.getContext() : null;
|
||||
return new FileDownloadBodyHandler(directory, openOptions, acc, filePermissions);
|
||||
}
|
||||
|
||||
private FileDownloadBodyHandler(Path directory,
|
||||
List<OpenOption> openOptions,
|
||||
AccessControlContext acc,
|
||||
FilePermission... filePermissions) {
|
||||
this.directory = directory;
|
||||
this.openOptions = openOptions;
|
||||
this.acc = acc;
|
||||
this.filePermissions = filePermissions;
|
||||
}
|
||||
|
||||
@ -273,7 +296,7 @@ public final class ResponseBodyHandlers {
|
||||
"Resulting file, " + file.toString() + ", outside of given directory");
|
||||
}
|
||||
|
||||
return new PathSubscriber(file, openOptions, filePermissions);
|
||||
return new PathSubscriber(file, openOptions, acc, filePermissions);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
|
||||
* Copyright (c) 2016, 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
|
||||
@ -35,7 +35,9 @@ import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.file.OpenOption;
|
||||
import java.nio.file.Path;
|
||||
import java.security.AccessControlContext;
|
||||
import java.security.AccessController;
|
||||
import java.security.PrivilegedAction;
|
||||
import java.security.PrivilegedActionException;
|
||||
import java.security.PrivilegedExceptionAction;
|
||||
import java.util.ArrayList;
|
||||
@ -172,7 +174,9 @@ public class ResponseSubscribers {
|
||||
|
||||
private final Path file;
|
||||
private final OpenOption[] options;
|
||||
private final AccessControlContext acc;
|
||||
private final FilePermission[] filePermissions;
|
||||
private final boolean isDefaultFS;
|
||||
private final CompletableFuture<Path> result = new MinimalFuture<>();
|
||||
|
||||
private final AtomicBoolean subscribed = new AtomicBoolean();
|
||||
@ -192,25 +196,44 @@ public class ResponseSubscribers {
|
||||
*/
|
||||
public static PathSubscriber create(Path file,
|
||||
List<OpenOption> options) {
|
||||
FilePermission filePermission = null;
|
||||
SecurityManager sm = System.getSecurityManager();
|
||||
FilePermission filePermission = null;
|
||||
if (sm != null) {
|
||||
String fn = pathForSecurityCheck(file);
|
||||
FilePermission writePermission = new FilePermission(fn, "write");
|
||||
sm.checkPermission(writePermission);
|
||||
filePermission = writePermission;
|
||||
try {
|
||||
String fn = pathForSecurityCheck(file);
|
||||
FilePermission writePermission = new FilePermission(fn, "write");
|
||||
sm.checkPermission(writePermission);
|
||||
filePermission = writePermission;
|
||||
} catch (UnsupportedOperationException ignored) {
|
||||
// path not associated with the default file system provider
|
||||
}
|
||||
}
|
||||
return new PathSubscriber(file, options, filePermission);
|
||||
|
||||
assert filePermission == null || filePermission.getActions().equals("write");
|
||||
AccessControlContext acc = sm != null ? AccessController.getContext() : null;
|
||||
return new PathSubscriber(file, options, acc, filePermission);
|
||||
}
|
||||
|
||||
// pp so handler implementations in the same package can construct
|
||||
/*package-private*/ PathSubscriber(Path file,
|
||||
List<OpenOption> options,
|
||||
AccessControlContext acc,
|
||||
FilePermission... filePermissions) {
|
||||
this.file = file;
|
||||
this.options = options.stream().toArray(OpenOption[]::new);
|
||||
this.filePermissions =
|
||||
filePermissions == null ? EMPTY_FILE_PERMISSIONS : filePermissions;
|
||||
this.acc = acc;
|
||||
this.filePermissions = filePermissions == null || filePermissions[0] == null
|
||||
? EMPTY_FILE_PERMISSIONS : filePermissions;
|
||||
this.isDefaultFS = isDefaultFS(file);
|
||||
}
|
||||
|
||||
private static boolean isDefaultFS(Path file) {
|
||||
try {
|
||||
file.toFile();
|
||||
return true;
|
||||
} catch (UnsupportedOperationException uoe) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -222,23 +245,30 @@ public class ResponseSubscribers {
|
||||
}
|
||||
|
||||
this.subscription = subscription;
|
||||
if (System.getSecurityManager() == null) {
|
||||
if (acc == null) {
|
||||
try {
|
||||
out = FileChannel.open(file, options);
|
||||
} catch (IOException ioe) {
|
||||
result.completeExceptionally(ioe);
|
||||
subscription.cancel();
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
PrivilegedExceptionAction<FileChannel> pa =
|
||||
() -> FileChannel.open(file, options);
|
||||
out = AccessController.doPrivileged(pa, null, filePermissions);
|
||||
out = isDefaultFS
|
||||
? AccessController.doPrivileged(pa, acc, filePermissions)
|
||||
: AccessController.doPrivileged(pa, acc);
|
||||
} catch (PrivilegedActionException pae) {
|
||||
Throwable t = pae.getCause() != null ? pae.getCause() : pae;
|
||||
result.completeExceptionally(t);
|
||||
subscription.cancel();
|
||||
return;
|
||||
} catch (Exception e) {
|
||||
result.completeExceptionally(e);
|
||||
subscription.cancel();
|
||||
return;
|
||||
}
|
||||
}
|
||||
subscription.request(1);
|
||||
@ -249,7 +279,7 @@ public class ResponseSubscribers {
|
||||
try {
|
||||
out.write(items.toArray(Utils.EMPTY_BB_ARRAY));
|
||||
} catch (IOException ex) {
|
||||
Utils.close(out);
|
||||
close();
|
||||
subscription.cancel();
|
||||
result.completeExceptionally(ex);
|
||||
}
|
||||
@ -259,12 +289,12 @@ public class ResponseSubscribers {
|
||||
@Override
|
||||
public void onError(Throwable e) {
|
||||
result.completeExceptionally(e);
|
||||
Utils.close(out);
|
||||
close();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onComplete() {
|
||||
Utils.close(out);
|
||||
close();
|
||||
result.complete(file);
|
||||
}
|
||||
|
||||
@ -272,6 +302,22 @@ public class ResponseSubscribers {
|
||||
public CompletionStage<Path> getBody() {
|
||||
return result;
|
||||
}
|
||||
|
||||
private void close() {
|
||||
if (acc == null) {
|
||||
Utils.close(out);
|
||||
} else {
|
||||
PrivilegedAction<Void> pa = () -> {
|
||||
Utils.close(out);
|
||||
return null;
|
||||
};
|
||||
if (isDefaultFS) {
|
||||
AccessController.doPrivileged(pa, acc, filePermissions);
|
||||
} else {
|
||||
AccessController.doPrivileged(pa, acc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ByteArraySubscriber<T> implements TrustedSubscriber<T> {
|
||||
|
||||
@ -0,0 +1,247 @@
|
||||
/*
|
||||
* Copyright (c) 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
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8237470
|
||||
* @summary Confirm HttpResponse.BodySubscribers#ofFileDownload(Path)
|
||||
* works only with the default file system
|
||||
* @modules java.base/sun.net.www.http
|
||||
* java.net.http/jdk.internal.net.http.common
|
||||
* java.net.http/jdk.internal.net.http.frame
|
||||
* java.net.http/jdk.internal.net.http.hpack
|
||||
* jdk.httpserver
|
||||
* @library /test/lib ../http2/server
|
||||
* @compile ../HttpServerAdapters.java
|
||||
* @build jdk.test.lib.net.SimpleSSLContext
|
||||
* @run testng/othervm BodyHandlerOfFileDownloadTest
|
||||
* @run testng/othervm/java.security.policy=ofFileDownload.policy BodyHandlerOfFileDownloadTest
|
||||
*/
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.sun.net.httpserver.HttpsConfigurator;
|
||||
import com.sun.net.httpserver.HttpsServer;
|
||||
import jdk.test.lib.net.SimpleSSLContext;
|
||||
import jdk.test.lib.util.FileUtils;
|
||||
import org.testng.annotations.AfterTest;
|
||||
import org.testng.annotations.BeforeTest;
|
||||
import org.testng.annotations.DataProvider;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpRequest.BodyPublishers;
|
||||
import java.net.http.HttpResponse.BodyHandlers;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.FileSystem;
|
||||
import java.nio.file.FileSystems;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Map;
|
||||
|
||||
import static java.lang.System.out;
|
||||
import static java.net.http.HttpClient.Builder.NO_PROXY;
|
||||
import static java.nio.file.StandardOpenOption.CREATE;
|
||||
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
|
||||
import static java.nio.file.StandardOpenOption.WRITE;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
import static org.testng.Assert.assertTrue;
|
||||
|
||||
public class BodyHandlerOfFileDownloadTest implements HttpServerAdapters {
|
||||
static final String MSG = "msg";
|
||||
static final String contentDispositionValue = "attachment; filename=example.html";
|
||||
|
||||
SSLContext sslContext;
|
||||
HttpServerAdapters.HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
|
||||
HttpServerAdapters.HttpTestServer httpsTestServer; // HTTPS/1.1
|
||||
HttpServerAdapters.HttpTestServer http2TestServer; // HTTP/2 ( h2c )
|
||||
HttpServerAdapters.HttpTestServer https2TestServer; // HTTP/2 ( h2 )
|
||||
String httpURI;
|
||||
String httpsURI;
|
||||
String http2URI;
|
||||
String https2URI;
|
||||
|
||||
FileSystem zipFs;
|
||||
Path defaultFsPath;
|
||||
Path zipFsPath;
|
||||
|
||||
// Default file system
|
||||
|
||||
static Path defaultFsDir() throws Exception {
|
||||
var dir = Path.of("defaultDir");
|
||||
if (Files.notExists(dir)) {
|
||||
Files.createDirectory(dir);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
@DataProvider(name = "defaultFsData")
|
||||
public Object[][] defaultFsData() {
|
||||
return new Object[][]{
|
||||
{ httpURI, defaultFsPath, MSG, true },
|
||||
{ httpsURI, defaultFsPath, MSG, true },
|
||||
{ http2URI, defaultFsPath, MSG, true },
|
||||
{ https2URI, defaultFsPath, MSG, true },
|
||||
{ httpURI, defaultFsPath, MSG, false },
|
||||
{ httpsURI, defaultFsPath, MSG, false },
|
||||
{ http2URI, defaultFsPath, MSG, false },
|
||||
{ https2URI, defaultFsPath, MSG, false },
|
||||
};
|
||||
}
|
||||
|
||||
@Test(dataProvider = "defaultFsData")
|
||||
public void testDefaultFs(String uriString,
|
||||
Path path,
|
||||
String expectedMsg,
|
||||
boolean sameClient) throws Exception {
|
||||
out.printf("\n\n--- testDefaultFs(%s, %s, \"%s\", %b): starting\n",
|
||||
uriString, path, expectedMsg, sameClient);
|
||||
receive(uriString, path, expectedMsg, sameClient);
|
||||
}
|
||||
|
||||
private static final int ITERATION_COUNT = 3;
|
||||
|
||||
private void receive(String uriString,
|
||||
Path path,
|
||||
String expectedMsg,
|
||||
boolean sameClient) throws Exception {
|
||||
HttpClient client = null;
|
||||
|
||||
for (int i = 0; i < ITERATION_COUNT; i++) {
|
||||
if (!sameClient || client == null) {
|
||||
client = HttpClient.newBuilder()
|
||||
.proxy(NO_PROXY)
|
||||
.sslContext(sslContext)
|
||||
.build();
|
||||
}
|
||||
var req = HttpRequest.newBuilder(URI.create(uriString))
|
||||
.POST(BodyPublishers.noBody())
|
||||
.build();
|
||||
var resp = client.send(req, BodyHandlers.ofFileDownload(path, CREATE, TRUNCATE_EXISTING, WRITE));
|
||||
String msg = Files.readString(resp.body());
|
||||
out.printf("Resp code: %s\n", resp.statusCode());
|
||||
out.println("Resp body Path: " + resp.body());
|
||||
out.printf("Resp body written to file: %s\n", msg);
|
||||
assertEquals(resp.statusCode(), 200);
|
||||
assertEquals(msg, expectedMsg);
|
||||
assertTrue(resp.headers().firstValue("Content-Disposition").isPresent());
|
||||
assertEquals(resp.headers().firstValue("Content-Disposition").get(), contentDispositionValue);
|
||||
}
|
||||
}
|
||||
|
||||
// Zip file system
|
||||
|
||||
static FileSystem newZipFs() throws Exception {
|
||||
Path zipFile = Path.of("file.zip");
|
||||
return FileSystems.newFileSystem(zipFile, Map.of("create", "true"));
|
||||
}
|
||||
|
||||
static Path zipFsDir(FileSystem fs) throws Exception {
|
||||
var dir = fs.getPath("zipDir");
|
||||
if (Files.notExists(dir)) {
|
||||
Files.createDirectory(dir);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
@Test(expectedExceptions = IllegalArgumentException.class)
|
||||
public void testZipFs() {
|
||||
out.printf("\n\n--- testZipFs(): starting\n");
|
||||
BodyHandlers.ofFileDownload(zipFsPath, CREATE, TRUNCATE_EXISTING, WRITE);
|
||||
}
|
||||
|
||||
|
||||
@BeforeTest
|
||||
public void setup() throws Exception {
|
||||
sslContext = new SimpleSSLContext().get();
|
||||
if (sslContext == null)
|
||||
throw new AssertionError("Unexpected null sslContext");
|
||||
|
||||
defaultFsPath = defaultFsDir();
|
||||
zipFs = newZipFs();
|
||||
zipFsPath = zipFsDir(zipFs);
|
||||
|
||||
InetSocketAddress sa =
|
||||
new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
|
||||
|
||||
httpTestServer = HttpServerAdapters.HttpTestServer.of(HttpServer.create(sa, 0));
|
||||
httpTestServer.addHandler(new HttpEchoHandler(), "/http1/echo");
|
||||
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/echo";
|
||||
|
||||
HttpsServer httpsServer = HttpsServer.create(sa, 0);
|
||||
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
|
||||
httpsTestServer = HttpServerAdapters.HttpTestServer.of(httpsServer);
|
||||
httpsTestServer.addHandler(new HttpEchoHandler(), "/https1/echo");
|
||||
httpsURI = "https://" + httpsTestServer.serverAuthority() + "/https1/echo";
|
||||
|
||||
http2TestServer = HttpServerAdapters.HttpTestServer.of(
|
||||
new Http2TestServer("localhost", false, 0));
|
||||
http2TestServer.addHandler(new HttpEchoHandler(), "/http2/echo");
|
||||
http2URI = "http://" + http2TestServer.serverAuthority() + "/http2/echo";
|
||||
|
||||
https2TestServer = HttpServerAdapters.HttpTestServer.of(
|
||||
new Http2TestServer("localhost", true, sslContext));
|
||||
https2TestServer.addHandler(new HttpEchoHandler(), "/https2/echo");
|
||||
https2URI = "https://" + https2TestServer.serverAuthority() + "/https2/echo";
|
||||
|
||||
httpTestServer.start();
|
||||
httpsTestServer.start();
|
||||
http2TestServer.start();
|
||||
https2TestServer.start();
|
||||
}
|
||||
|
||||
@AfterTest
|
||||
public void teardown() throws Exception {
|
||||
if (Files.exists(zipFsPath))
|
||||
FileUtils.deleteFileTreeWithRetry(zipFsPath);
|
||||
if (Files.exists(defaultFsPath))
|
||||
FileUtils.deleteFileTreeWithRetry(defaultFsPath);
|
||||
|
||||
httpTestServer.stop();
|
||||
httpsTestServer.stop();
|
||||
http2TestServer.stop();
|
||||
https2TestServer.stop();
|
||||
zipFs.close();
|
||||
}
|
||||
|
||||
static class HttpEchoHandler implements HttpServerAdapters.HttpTestHandler {
|
||||
@Override
|
||||
public void handle(HttpServerAdapters.HttpTestExchange t) throws IOException {
|
||||
try (InputStream is = t.getRequestBody();
|
||||
OutputStream os = t.getResponseBody()) {
|
||||
is.readAllBytes();
|
||||
t.getResponseHeaders().addHeader("Content-Disposition",
|
||||
"attachment; filename=example.html");
|
||||
t.sendResponseHeaders(200, MSG.getBytes().length);
|
||||
os.write(MSG.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,252 @@
|
||||
/*
|
||||
* Copyright (c) 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
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8237470
|
||||
* @summary Confirm HttpResponse.BodyHandlers#ofFile(Path)
|
||||
* works with default and non-default file systems
|
||||
* when SecurityManager is enabled
|
||||
* @modules java.base/sun.net.www.http
|
||||
* java.net.http/jdk.internal.net.http.common
|
||||
* java.net.http/jdk.internal.net.http.frame
|
||||
* java.net.http/jdk.internal.net.http.hpack
|
||||
* jdk.httpserver
|
||||
* @library /test/lib ../http2/server
|
||||
* @compile ../HttpServerAdapters.java
|
||||
* @build jdk.test.lib.net.SimpleSSLContext
|
||||
* @run testng/othervm BodyHandlerOfFileTest
|
||||
* @run testng/othervm/java.security.policy=ofFile.policy BodyHandlerOfFileTest
|
||||
*/
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.sun.net.httpserver.HttpsConfigurator;
|
||||
import com.sun.net.httpserver.HttpsServer;
|
||||
import jdk.test.lib.net.SimpleSSLContext;
|
||||
import jdk.test.lib.util.FileUtils;
|
||||
import org.testng.annotations.AfterTest;
|
||||
import org.testng.annotations.BeforeTest;
|
||||
import org.testng.annotations.DataProvider;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpRequest.BodyPublishers;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.util.Map;
|
||||
|
||||
import static java.lang.System.out;
|
||||
import static java.net.http.HttpClient.Builder.NO_PROXY;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
|
||||
public class BodyHandlerOfFileTest implements HttpServerAdapters {
|
||||
static final String MSG = "msg";
|
||||
|
||||
SSLContext sslContext;
|
||||
HttpServerAdapters.HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
|
||||
HttpServerAdapters.HttpTestServer httpsTestServer; // HTTPS/1.1
|
||||
HttpServerAdapters.HttpTestServer http2TestServer; // HTTP/2 ( h2c )
|
||||
HttpServerAdapters.HttpTestServer https2TestServer; // HTTP/2 ( h2 )
|
||||
String httpURI;
|
||||
String httpsURI;
|
||||
String http2URI;
|
||||
String https2URI;
|
||||
|
||||
FileSystem zipFs;
|
||||
Path defaultFsPath;
|
||||
Path zipFsPath;
|
||||
|
||||
// Default file system set-up
|
||||
|
||||
static Path defaultFsFile() throws Exception {
|
||||
var file = Path.of("defaultFile.txt");
|
||||
if (Files.notExists(file)) {
|
||||
Files.createFile(file);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
@DataProvider(name = "defaultFsData")
|
||||
public Object[][] defaultFsData() {
|
||||
return new Object[][]{
|
||||
{ httpURI, defaultFsPath, MSG, true },
|
||||
{ httpsURI, defaultFsPath, MSG, true },
|
||||
{ http2URI, defaultFsPath, MSG, true },
|
||||
{ https2URI, defaultFsPath, MSG, true },
|
||||
{ httpURI, defaultFsPath, MSG, false },
|
||||
{ httpsURI, defaultFsPath, MSG, false },
|
||||
{ http2URI, defaultFsPath, MSG, false },
|
||||
{ https2URI, defaultFsPath, MSG, false },
|
||||
};
|
||||
}
|
||||
|
||||
@Test(dataProvider = "defaultFsData")
|
||||
public void testDefaultFs(String uriString,
|
||||
Path path,
|
||||
String expectedMsg,
|
||||
boolean sameClient) throws Exception {
|
||||
out.printf("\n\n--- testDefaultFs(%s, %s, \"%s\", %b): starting\n",
|
||||
uriString, path, expectedMsg, sameClient);
|
||||
receive(uriString, path, expectedMsg, sameClient);
|
||||
}
|
||||
|
||||
// Zip file system set-up
|
||||
|
||||
static FileSystem newZipFs() throws Exception {
|
||||
Path zipFile = Path.of("file.zip");
|
||||
return FileSystems.newFileSystem(zipFile, Map.of("create", "true"));
|
||||
}
|
||||
|
||||
static Path zipFsFile(FileSystem fs) throws Exception {
|
||||
var file = fs.getPath("fileInZip.txt");
|
||||
if (Files.notExists(file)) {
|
||||
Files.createFile(file);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
@DataProvider(name = "zipFsData")
|
||||
public Object[][] zipFsData() {
|
||||
return new Object[][]{
|
||||
{ httpURI, zipFsPath, MSG, true },
|
||||
{ httpsURI, zipFsPath, MSG, true },
|
||||
{ http2URI, zipFsPath, MSG, true },
|
||||
{ https2URI, zipFsPath, MSG, true },
|
||||
{ httpURI, zipFsPath, MSG, false },
|
||||
{ httpsURI, zipFsPath, MSG, false },
|
||||
{ http2URI, zipFsPath, MSG, false },
|
||||
{ https2URI, zipFsPath, MSG, false },
|
||||
};
|
||||
}
|
||||
|
||||
@Test(dataProvider = "zipFsData")
|
||||
public void testZipFs(String uriString,
|
||||
Path path,
|
||||
String expectedMsg,
|
||||
boolean sameClient) throws Exception {
|
||||
out.printf("\n\n--- testZipFs(%s, %s, \"%s\", %b): starting\n",
|
||||
uriString, path, expectedMsg, sameClient);
|
||||
receive(uriString, path, expectedMsg, sameClient);
|
||||
}
|
||||
|
||||
private static final int ITERATION_COUNT = 3;
|
||||
|
||||
private void receive(String uriString,
|
||||
Path path,
|
||||
String expectedMsg,
|
||||
boolean sameClient) throws Exception {
|
||||
HttpClient client = null;
|
||||
|
||||
for (int i = 0; i < ITERATION_COUNT; i++) {
|
||||
if (!sameClient || client == null) {
|
||||
client = HttpClient.newBuilder()
|
||||
.proxy(NO_PROXY)
|
||||
.sslContext(sslContext)
|
||||
.build();
|
||||
}
|
||||
var req = HttpRequest.newBuilder(URI.create(uriString))
|
||||
.POST(BodyPublishers.noBody())
|
||||
.build();
|
||||
var resp = client.send(req, HttpResponse.BodyHandlers.ofFile(path));
|
||||
String msg = Files.readString(path, StandardCharsets.UTF_8);
|
||||
out.printf("Resp code: %s\n", resp.statusCode());
|
||||
out.printf("Msg written to %s: %s\n", resp.body(), msg);
|
||||
assertEquals(resp.statusCode(), 200);
|
||||
assertEquals(msg, expectedMsg);
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeTest
|
||||
public void setup() throws Exception {
|
||||
sslContext = new SimpleSSLContext().get();
|
||||
if (sslContext == null)
|
||||
throw new AssertionError("Unexpected null sslContext");
|
||||
|
||||
defaultFsPath = defaultFsFile();
|
||||
zipFs = newZipFs();
|
||||
zipFsPath = zipFsFile(zipFs);
|
||||
|
||||
InetSocketAddress sa =
|
||||
new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
|
||||
|
||||
httpTestServer = HttpServerAdapters.HttpTestServer.of(HttpServer.create(sa, 0));
|
||||
httpTestServer.addHandler(new HttpEchoHandler(), "/http1/echo");
|
||||
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/echo";
|
||||
|
||||
HttpsServer httpsServer = HttpsServer.create(sa, 0);
|
||||
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
|
||||
httpsTestServer = HttpServerAdapters.HttpTestServer.of(httpsServer);
|
||||
httpsTestServer.addHandler(new HttpEchoHandler(), "/https1/echo");
|
||||
httpsURI = "https://" + httpsTestServer.serverAuthority() + "/https1/echo";
|
||||
|
||||
http2TestServer = HttpServerAdapters.HttpTestServer.of(
|
||||
new Http2TestServer("localhost", false, 0));
|
||||
http2TestServer.addHandler(new HttpEchoHandler(), "/http2/echo");
|
||||
http2URI = "http://" + http2TestServer.serverAuthority() + "/http2/echo";
|
||||
|
||||
https2TestServer = HttpServerAdapters.HttpTestServer.of(
|
||||
new Http2TestServer("localhost", true, sslContext));
|
||||
https2TestServer.addHandler(new HttpEchoHandler(), "/https2/echo");
|
||||
https2URI = "https://" + https2TestServer.serverAuthority() + "/https2/echo";
|
||||
|
||||
httpTestServer.start();
|
||||
httpsTestServer.start();
|
||||
http2TestServer.start();
|
||||
https2TestServer.start();
|
||||
}
|
||||
|
||||
@AfterTest
|
||||
public void teardown() throws Exception {
|
||||
if (Files.exists(zipFsPath))
|
||||
FileUtils.deleteFileTreeWithRetry(zipFsPath);
|
||||
if (Files.exists(defaultFsPath))
|
||||
FileUtils.deleteFileTreeWithRetry(defaultFsPath);
|
||||
|
||||
httpTestServer.stop();
|
||||
httpsTestServer.stop();
|
||||
http2TestServer.stop();
|
||||
https2TestServer.stop();
|
||||
zipFs.close();
|
||||
}
|
||||
|
||||
static class HttpEchoHandler implements HttpServerAdapters.HttpTestHandler {
|
||||
@Override
|
||||
public void handle(HttpServerAdapters.HttpTestExchange t) throws IOException {
|
||||
try (InputStream is = t.getRequestBody();
|
||||
OutputStream os = t.getResponseBody()) {
|
||||
is.readAllBytes();
|
||||
t.sendResponseHeaders(200, MSG.getBytes().length);
|
||||
os.write(MSG.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,262 @@
|
||||
/*
|
||||
* Copyright (c) 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
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* @test
|
||||
* @bug 8237470
|
||||
* @summary Confirm HttpResponse.BodySubscribers#ofFile(Path)
|
||||
* works with default and non-default file systems
|
||||
* when SecurityManager is enabled
|
||||
* @modules java.base/sun.net.www.http
|
||||
* java.net.http/jdk.internal.net.http.common
|
||||
* java.net.http/jdk.internal.net.http.frame
|
||||
* java.net.http/jdk.internal.net.http.hpack
|
||||
* jdk.httpserver
|
||||
* @library /test/lib ../http2/server
|
||||
* @compile ../HttpServerAdapters.java
|
||||
* @build jdk.test.lib.net.SimpleSSLContext
|
||||
* @run testng/othervm BodySubscriberOfFileTest
|
||||
* @run testng/othervm/java.security.policy=ofFile.policy BodySubscriberOfFileTest
|
||||
*/
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import com.sun.net.httpserver.HttpsConfigurator;
|
||||
import com.sun.net.httpserver.HttpsServer;
|
||||
import jdk.test.lib.net.SimpleSSLContext;
|
||||
import jdk.test.lib.util.FileUtils;
|
||||
import org.testng.annotations.AfterTest;
|
||||
import org.testng.annotations.BeforeTest;
|
||||
import org.testng.annotations.DataProvider;
|
||||
import org.testng.annotations.Test;
|
||||
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpRequest.BodyPublishers;
|
||||
import java.net.http.HttpResponse.BodyHandler;
|
||||
import java.net.http.HttpResponse.BodySubscriber;
|
||||
import java.net.http.HttpResponse.BodySubscribers;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import java.security.AccessController;
|
||||
import java.security.PrivilegedAction;
|
||||
import java.util.Map;
|
||||
|
||||
import static java.lang.System.out;
|
||||
import static java.net.http.HttpClient.Builder.NO_PROXY;
|
||||
import static org.testng.Assert.assertEquals;
|
||||
|
||||
public class BodySubscriberOfFileTest implements HttpServerAdapters {
|
||||
static final String MSG = "msg";
|
||||
|
||||
SSLContext sslContext;
|
||||
HttpServerAdapters.HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
|
||||
HttpServerAdapters.HttpTestServer httpsTestServer; // HTTPS/1.1
|
||||
HttpServerAdapters.HttpTestServer http2TestServer; // HTTP/2 ( h2c )
|
||||
HttpServerAdapters.HttpTestServer https2TestServer; // HTTP/2 ( h2 )
|
||||
String httpURI;
|
||||
String httpsURI;
|
||||
String http2URI;
|
||||
String https2URI;
|
||||
|
||||
FileSystem zipFs;
|
||||
Path defaultFsPath;
|
||||
Path zipFsPath;
|
||||
|
||||
// Default file system set-up
|
||||
|
||||
static Path defaultFsFile() throws Exception {
|
||||
var file = Path.of("defaultFile.txt");
|
||||
if (Files.notExists(file)) {
|
||||
Files.createFile(file);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
@DataProvider(name = "defaultFsData")
|
||||
public Object[][] defaultFsData() {
|
||||
return new Object[][]{
|
||||
{ httpURI, defaultFsPath, MSG, true },
|
||||
{ httpsURI, defaultFsPath, MSG, true },
|
||||
{ http2URI, defaultFsPath, MSG, true },
|
||||
{ https2URI, defaultFsPath, MSG, true },
|
||||
{ httpURI, defaultFsPath, MSG, false },
|
||||
{ httpsURI, defaultFsPath, MSG, false },
|
||||
{ http2URI, defaultFsPath, MSG, false },
|
||||
{ https2URI, defaultFsPath, MSG, false },
|
||||
};
|
||||
}
|
||||
|
||||
@Test(dataProvider = "defaultFsData")
|
||||
public void testDefaultFs(String uriString,
|
||||
Path path,
|
||||
String expectedMsg,
|
||||
boolean sameClient) throws Exception {
|
||||
out.printf("\n\n--- testDefaultFs(%s, %s, \"%s\", %b): starting\n",
|
||||
uriString, path, expectedMsg, sameClient);
|
||||
receive(uriString, path, expectedMsg, sameClient);
|
||||
}
|
||||
|
||||
// Zip file system set-up
|
||||
|
||||
static FileSystem newZipFs() throws Exception {
|
||||
Path zipFile = Path.of("file.zip");
|
||||
return FileSystems.newFileSystem(zipFile, Map.of("create", "true"));
|
||||
}
|
||||
|
||||
static Path zipFsFile(FileSystem fs) throws Exception {
|
||||
var file = fs.getPath("fileInZip.txt");
|
||||
if (Files.notExists(file)) {
|
||||
Files.createFile(file);
|
||||
}
|
||||
return file;
|
||||
}
|
||||
|
||||
@DataProvider(name = "zipFsData")
|
||||
public Object[][] zipFsData() {
|
||||
return new Object[][]{
|
||||
{ httpURI, zipFsPath, MSG, true },
|
||||
{ httpsURI, zipFsPath, MSG, true },
|
||||
{ http2URI, zipFsPath, MSG, true },
|
||||
{ https2URI, zipFsPath, MSG, true },
|
||||
{ httpURI, zipFsPath, MSG, false },
|
||||
{ httpsURI, zipFsPath, MSG, false },
|
||||
{ http2URI, zipFsPath, MSG, false },
|
||||
{ https2URI, zipFsPath, MSG, false },
|
||||
};
|
||||
}
|
||||
|
||||
@Test(dataProvider = "zipFsData")
|
||||
public void testZipFs(String uriString,
|
||||
Path path,
|
||||
String expectedMsg,
|
||||
boolean sameClient) throws Exception {
|
||||
out.printf("\n\n--- testZipFs(%s, %s, \"%s\", %b): starting\n",
|
||||
uriString, path, expectedMsg, sameClient);
|
||||
receive(uriString, path, expectedMsg, sameClient);
|
||||
}
|
||||
|
||||
private static final int ITERATION_COUNT = 3;
|
||||
|
||||
private void receive(String uriString,
|
||||
Path path,
|
||||
String expectedMsg,
|
||||
boolean sameClient) throws Exception {
|
||||
HttpClient client = null;
|
||||
|
||||
for (int i = 0; i < ITERATION_COUNT; i++) {
|
||||
if (!sameClient || client == null) {
|
||||
client = HttpClient.newBuilder()
|
||||
.proxy(NO_PROXY)
|
||||
.sslContext(sslContext)
|
||||
.build();
|
||||
}
|
||||
var req = HttpRequest.newBuilder(URI.create(uriString))
|
||||
.POST(BodyPublishers.noBody())
|
||||
.build();
|
||||
|
||||
// Retrieve handler with caller's privileges enabled
|
||||
PrivilegedAction<BodySubscriber<Path>> action = () ->
|
||||
BodySubscribers.ofFile(path);
|
||||
BodyHandler<Path> handler = respInfo ->
|
||||
AccessController.doPrivileged(action);
|
||||
var resp = client.send(req, handler);
|
||||
String msg = Files.readString(path, StandardCharsets.UTF_8);
|
||||
out.printf("Resp code: %s\n", resp.statusCode());
|
||||
out.printf("Msg written to %s: %s\n", resp.body(), msg);
|
||||
assertEquals(resp.statusCode(), 200);
|
||||
assertEquals(msg, expectedMsg);
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeTest
|
||||
public void setup() throws Exception {
|
||||
sslContext = new SimpleSSLContext().get();
|
||||
if (sslContext == null)
|
||||
throw new AssertionError("Unexpected null sslContext");
|
||||
|
||||
defaultFsPath = defaultFsFile();
|
||||
zipFs = newZipFs();
|
||||
zipFsPath = zipFsFile(zipFs);
|
||||
|
||||
InetSocketAddress sa =
|
||||
new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
|
||||
|
||||
httpTestServer = HttpServerAdapters.HttpTestServer.of(HttpServer.create(sa, 0));
|
||||
httpTestServer.addHandler(new HttpEchoHandler(), "/http1/echo");
|
||||
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/echo";
|
||||
|
||||
HttpsServer httpsServer = HttpsServer.create(sa, 0);
|
||||
httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext));
|
||||
httpsTestServer = HttpServerAdapters.HttpTestServer.of(httpsServer);
|
||||
httpsTestServer.addHandler(new HttpEchoHandler(), "/https1/echo");
|
||||
httpsURI = "https://" + httpsTestServer.serverAuthority() + "/https1/echo";
|
||||
|
||||
http2TestServer = HttpServerAdapters.HttpTestServer.of(
|
||||
new Http2TestServer("localhost", false, 0));
|
||||
http2TestServer.addHandler(new HttpEchoHandler(), "/http2/echo");
|
||||
http2URI = "http://" + http2TestServer.serverAuthority() + "/http2/echo";
|
||||
|
||||
https2TestServer = HttpServerAdapters.HttpTestServer.of(
|
||||
new Http2TestServer("localhost", true, sslContext));
|
||||
https2TestServer.addHandler(new HttpEchoHandler(), "/https2/echo");
|
||||
https2URI = "https://" + https2TestServer.serverAuthority() + "/https2/echo";
|
||||
|
||||
httpTestServer.start();
|
||||
httpsTestServer.start();
|
||||
http2TestServer.start();
|
||||
https2TestServer.start();
|
||||
}
|
||||
|
||||
@AfterTest
|
||||
public void teardown() throws Exception {
|
||||
if (Files.exists(zipFsPath))
|
||||
FileUtils.deleteFileTreeWithRetry(zipFsPath);
|
||||
if (Files.exists(defaultFsPath))
|
||||
FileUtils.deleteFileTreeWithRetry(defaultFsPath);
|
||||
|
||||
httpTestServer.stop();
|
||||
httpsTestServer.stop();
|
||||
http2TestServer.stop();
|
||||
https2TestServer.stop();
|
||||
zipFs.close();
|
||||
}
|
||||
|
||||
static class HttpEchoHandler implements HttpServerAdapters.HttpTestHandler {
|
||||
@Override
|
||||
public void handle(HttpServerAdapters.HttpTestExchange t) throws IOException {
|
||||
try (InputStream is = t.getRequestBody();
|
||||
OutputStream os = t.getResponseBody()) {
|
||||
is.readAllBytes();
|
||||
t.sendResponseHeaders(200, MSG.getBytes().length);
|
||||
os.write(MSG.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
79
test/jdk/java/net/httpclient/PathSubscriber/ofFile.policy
Normal file
79
test/jdk/java/net/httpclient/PathSubscriber/ofFile.policy
Normal file
@ -0,0 +1,79 @@
|
||||
//
|
||||
// Copyright (c) 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
|
||||
// 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.
|
||||
//
|
||||
|
||||
// for JTwork/classes/0/test/lib/jdk/test/lib/net/SimpleSSLContext.class
|
||||
grant codeBase "file:${test.classes}/../../../../../test/lib/-" {
|
||||
permission java.util.PropertyPermission "java.vm.info", "read";
|
||||
permission java.util.PropertyPermission "jdk.debug", "read";
|
||||
permission java.util.PropertyPermission "sun.arch.data.model", "read";
|
||||
permission java.util.PropertyPermission "sun.management.compiler", "read";
|
||||
permission java.util.PropertyPermission "test.jdk", "read";
|
||||
permission java.util.PropertyPermission "test.src.path", "read";
|
||||
permission java.util.PropertyPermission "user.name", "read";
|
||||
permission java.io.FilePermission "${test.src}/../../../../../lib/jdk/test/lib/net/testkeys", "read";
|
||||
};
|
||||
|
||||
// for JTwork/classes/0/java/net/httpclient/http2/server/*
|
||||
grant codeBase "file:${test.classes}/../../../../../java/net/httpclient/http2/server/*" {
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.common";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.frame";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.hpack";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.sun.net.www.http";
|
||||
|
||||
permission java.net.SocketPermission "localhost:*", "accept,resolve";
|
||||
permission java.lang.RuntimePermission "modifyThread";
|
||||
};
|
||||
|
||||
grant codeBase "file:${test.classes}/*" {
|
||||
permission java.net.URLPermission "http://localhost:*/http1/echo", "POST";
|
||||
permission java.net.URLPermission "https://localhost:*/https1/echo", "POST";
|
||||
permission java.net.URLPermission "http://localhost:*/http2/echo", "POST";
|
||||
permission java.net.URLPermission "https://localhost:*/https2/echo", "POST";
|
||||
permission java.net.URLPermission "https://localhost:*/http1/echo", "GET";
|
||||
permission java.net.URLPermission "https://localhost:*/https1/echo", "GET";
|
||||
permission java.net.URLPermission "http://localhost:*/http2/echo", "GET";
|
||||
permission java.net.URLPermission "https://localhost:*/https2/echo", "GET";
|
||||
|
||||
// file permissions
|
||||
permission java.io.FilePermission "${user.dir}${/}defaultFile.txt", "read,write,delete";
|
||||
permission java.io.FilePermission "${user.dir}${/}file.zip", "read,write,delete";
|
||||
permission java.io.FilePermission "${user.dir}${/}defaultDir", "read,write,delete";
|
||||
|
||||
// file permission required by ZipFileSystem for temporary file creation
|
||||
permission java.io.FilePermission "${user.dir}${/}*", "read,write,delete";
|
||||
|
||||
// needed to grant permission to the HTTP/2 server
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.common";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.frame";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.hpack";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.sun.net.www.http";
|
||||
|
||||
// for HTTP/1.1 server logging
|
||||
permission java.util.logging.LoggingPermission "control";
|
||||
|
||||
// needed to grant the HTTP servers
|
||||
permission java.net.SocketPermission "localhost:*", "accept,resolve";
|
||||
|
||||
permission java.util.PropertyPermission "*", "read";
|
||||
permission java.lang.RuntimePermission "modifyThread";
|
||||
};
|
||||
@ -0,0 +1,76 @@
|
||||
//
|
||||
// Copyright (c) 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
|
||||
// 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.
|
||||
//
|
||||
|
||||
// for JTwork/classes/0/test/lib/jdk/test/lib/net/SimpleSSLContext.class
|
||||
grant codeBase "file:${test.classes}/../../../../../test/lib/-" {
|
||||
permission java.util.PropertyPermission "java.vm.info", "read";
|
||||
permission java.util.PropertyPermission "jdk.debug", "read";
|
||||
permission java.util.PropertyPermission "sun.arch.data.model", "read";
|
||||
permission java.util.PropertyPermission "sun.management.compiler", "read";
|
||||
permission java.util.PropertyPermission "test.jdk", "read";
|
||||
permission java.util.PropertyPermission "test.src.path", "read";
|
||||
permission java.util.PropertyPermission "user.name", "read";
|
||||
permission java.io.FilePermission "${test.src}/../../../../../lib/jdk/test/lib/net/testkeys", "read";
|
||||
};
|
||||
|
||||
// for JTwork/classes/0/java/net/httpclient/http2/server/*
|
||||
grant codeBase "file:${test.classes}/../../../../../java/net/httpclient/http2/server/*" {
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.common";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.frame";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.hpack";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.sun.net.www.http";
|
||||
|
||||
permission java.net.SocketPermission "localhost:*", "accept,resolve";
|
||||
permission java.lang.RuntimePermission "modifyThread";
|
||||
};
|
||||
|
||||
grant codeBase "file:${test.classes}/*" {
|
||||
permission java.net.URLPermission "http://localhost:*/http1/echo", "POST";
|
||||
permission java.net.URLPermission "https://localhost:*/https1/echo", "POST";
|
||||
permission java.net.URLPermission "http://localhost:*/http2/echo", "POST";
|
||||
permission java.net.URLPermission "https://localhost:*/https2/echo", "POST";
|
||||
permission java.net.URLPermission "https://localhost:*/http1/echo", "GET";
|
||||
permission java.net.URLPermission "https://localhost:*/https1/echo", "GET";
|
||||
permission java.net.URLPermission "http://localhost:*/http2/echo", "GET";
|
||||
permission java.net.URLPermission "https://localhost:*/https2/echo", "GET";
|
||||
|
||||
// file permissions
|
||||
permission java.io.FilePermission "${user.dir}${/}file.zip", "read,write,delete";
|
||||
permission java.io.FilePermission "${user.dir}${/}defaultDir", "read,write,delete";
|
||||
permission java.io.FilePermission "${user.dir}${/}defaultDir/*", "read,write,delete";
|
||||
|
||||
// needed to grant permission to the HTTP/2 server
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.common";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.frame";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.jdk.internal.net.http.hpack";
|
||||
permission java.lang.RuntimePermission "accessClassInPackage.sun.net.www.http";
|
||||
|
||||
// for HTTP/1.1 server logging
|
||||
permission java.util.logging.LoggingPermission "control";
|
||||
|
||||
// needed to grant the HTTP servers
|
||||
permission java.net.SocketPermission "localhost:*", "accept,resolve";
|
||||
|
||||
permission java.util.PropertyPermission "*", "read";
|
||||
permission java.lang.RuntimePermission "modifyThread";
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user