Skip to content

Commit 9c5c800

Browse files
authored
Update ProxyHandler to use transferTo
1 parent 2a13b2a commit 9c5c800

File tree

1 file changed

+4
-22
lines changed

1 file changed

+4
-22
lines changed

src/main/java/robaho/net/httpserver/extras/ProxyHandler.java

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -82,12 +82,12 @@ public void handle(HttpExchange exchange) throws IOException {
8282
try {
8383
exchange.getHttpContext().getServer().getExecutor().execute(() -> {
8484
try {
85-
transfer(s.getInputStream(),exchange.getResponseBody());
85+
s.getInputStream().transferTo(exchange.getResponseBody());
8686
} catch (IOException ex) {
8787
ex.printStackTrace();
8888
}
8989
});
90-
transfer(exchange.getRequestBody(),s.getOutputStream());
90+
exchange.getRequestBody().transferTo(s.getOutputStream());
9191
} finally {
9292
logger.fine("proxy connection to "+s.getRemoteSocketAddress()+" ended");
9393
return;
@@ -109,7 +109,7 @@ public void handle(HttpExchange exchange) throws IOException {
109109
exchange.getResponseHeaders().putAll(response.headers().map());
110110
exchange.sendResponseHeaders(response.statusCode(),0);
111111
try (var os = exchange.getResponseBody ()) {
112-
transfer(response.body(),os);
112+
response.body().transferTo(os);
113113
}
114114
} catch (InterruptedException ex) {
115115
throw new IOException("unable to proxy request to "+exchange.getRequestURI(),ex);
@@ -127,24 +127,6 @@ protected boolean authorizeConnect(HttpExchange exchange) {
127127
}
128128

129129
private static int DEFAULT_BUFFER_SIZE = 16384;
130-
private static long transfer(InputStream in, OutputStream out) throws IOException {
131-
Objects.requireNonNull(out, "out");
132-
long transferred = 0;
133-
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
134-
int read;
135-
while ((read = in.read(buffer, 0, DEFAULT_BUFFER_SIZE)) >= 0) {
136-
out.write(buffer, 0, read);
137-
out.flush();
138-
if (transferred < Long.MAX_VALUE) {
139-
try {
140-
transferred = Math.addExact(transferred, read);
141-
} catch (ArithmeticException ignore) {
142-
transferred = Long.MAX_VALUE;
143-
}
144-
}
145-
}
146-
return transferred;
147-
}
148130

149131
private static final Set<String> restrictedHeaders = Set.of("CONNECTION","HOST","UPGRADE","CONTENT-LENGTH");
150132

@@ -161,4 +143,4 @@ protected Optional<HostPort> proxyTo(HttpExchange exchange) {
161143
protected void connectFailed(URI uri, SocketAddress sa, IOException ieo) {
162144
}
163145

164-
}
146+
}

0 commit comments

Comments
 (0)