Skip to content

Commit

Permalink
[java] Return new input stream to allow multiple reads (#11249)
Browse files Browse the repository at this point in the history
  • Loading branch information
pujagani committed Nov 11, 2022
1 parent 5f4a05c commit 558e0a0
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions java/src/org/openqa/selenium/remote/ProtocolHandshake.java
Expand Up @@ -34,7 +34,6 @@
import org.openqa.selenium.remote.http.HttpRequest;
import org.openqa.selenium.remote.http.HttpResponse;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
Expand All @@ -43,6 +42,7 @@
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
Expand Down Expand Up @@ -91,21 +91,23 @@ public Result createSession(HttpHandler client, Command command) throws IOExcept

public Either<SessionNotCreatedException, Result> createSession(HttpHandler client, NewSessionPayload payload) throws IOException {
int threshold = (int) Math.min(Runtime.getRuntime().freeMemory() / 10, Integer.MAX_VALUE);
FileBackedOutputStream os = new FileBackedOutputStream(threshold);
FileBackedOutputStream os = new FileBackedOutputStream(threshold, true);

try (CountingOutputStream counter = new CountingOutputStream(os);
Writer writer = new OutputStreamWriter(counter, UTF_8)) {
payload.writeTo(writer);

try (InputStream contentStream = os.asByteSource().openBufferedStream()) {
return createSession(client, contentStream, counter.getCount());
}
} finally {
os.reset();
Supplier<InputStream> contentSupplier = () -> {
try {
return os.asByteSource().openBufferedStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
};
return createSession(client, contentSupplier, counter.getCount());
}
}

private Either<SessionNotCreatedException, Result> createSession(HttpHandler client, InputStream newSessionBlob, long size) {
private Either<SessionNotCreatedException, Result> createSession(HttpHandler client, Supplier<InputStream> contentSupplier, long size) {
// Create the http request and send it
HttpRequest request = new HttpRequest(HttpMethod.POST, "/session");

Expand All @@ -117,7 +119,7 @@ private Either<SessionNotCreatedException, Result> createSession(HttpHandler cli
// session e.g. with profiles.
request.setHeader(CONTENT_LENGTH, String.valueOf(size));
request.setHeader(CONTENT_TYPE, JSON_UTF_8);
request.setContent(() -> newSessionBlob);
request.setContent(contentSupplier);

response = client.execute(request);
long time = System.currentTimeMillis() - start;
Expand Down

0 comments on commit 558e0a0

Please sign in to comment.