Skip to content

[Core] UrlOutputStream uploads all data in one pass #1932

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 1, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 52 additions & 47 deletions core/src/main/java/io/cucumber/core/plugin/UrlOutputStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,94 +9,97 @@
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.Files.newOutputStream;

class UrlOutputStream extends OutputStream {
// Allow streaming, using a chunk size that is similar to a typical NDJSON
// message length
public static final int CHUNK_LENGTH = 256;
private final HttpURLConnection urlConnection;
private final OutputStream outputStream;

private String method;
private URL url;
private final Map<String, List<String>> requestHeaders;
private final CurlOption option;
private final Path temp;
private final OutputStream tempOutputStream;

UrlOutputStream(CurlOption option) throws IOException {
this.method = option.getMethod().name();
this.url = option.getUri().toURL();

urlConnection = (HttpURLConnection) this.url.openConnection();
for (Entry<String, String> header : option.getHeaders()) {
urlConnection.setRequestProperty(header.getKey(), header.getValue());
}
urlConnection.setRequestMethod(this.method);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(CHUNK_LENGTH);
urlConnection.setInstanceFollowRedirects(false);
requestHeaders = urlConnection.getRequestProperties();
outputStream = urlConnection.getOutputStream();
this.option = option;
this.temp = Files.createTempFile("cucumber", null);
this.tempOutputStream = newOutputStream(temp);
}

@Override
public void write(byte[] buffer, int offset, int count) throws IOException {
outputStream.write(buffer, offset, count);
tempOutputStream.write(buffer, offset, count);
}

@Override
public void write(byte[] buffer) throws IOException {
outputStream.write(buffer);
tempOutputStream.write(buffer);
}

@Override
public void write(int b) throws IOException {
outputStream.write(b);
tempOutputStream.write(b);
}

@Override
public void flush() throws IOException {
outputStream.flush();
tempOutputStream.flush();
}

@Override
public void close() throws IOException {
outputStream.close();
int httpStatus = urlConnection.getResponseCode();
boolean redirect = httpStatus >= 300 && httpStatus < 400;
boolean error = httpStatus >= 400;
try (InputStream inputStream = error ? urlConnection.getErrorStream() : urlConnection.getInputStream()) {
Map<String, List<String>> responseHeaders = urlConnection.getHeaderFields();
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, UTF_8))) {
String responseBody = br.lines().collect(Collectors.joining(System.lineSeparator()));
if (error || redirect) {
String message = generateCurlLikeMessage(this.method, this.url, this.requestHeaders, responseHeaders, responseBody, redirect);
throw new IOException(message);
}
tempOutputStream.close();

URL url = option.getUri().toURL();
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
for (Entry<String, String> header : option.getHeaders()) {
urlConnection.setRequestProperty(header.getKey(), header.getValue());
}
urlConnection.setInstanceFollowRedirects(true);
urlConnection.setRequestMethod(option.getMethod().name());
urlConnection.setDoOutput(true);
Map<String, List<String>> requestHeaders = urlConnection.getRequestProperties();
try (OutputStream outputStream = urlConnection.getOutputStream()) {
Files.copy(temp, outputStream);
handleResponse(urlConnection, requestHeaders);
}
}

private static void handleResponse(HttpURLConnection urlConnection, Map<String, List<String>> requestHeaders) throws IOException {
Map<String, List<String>> responseHeaders = urlConnection.getHeaderFields();
int responseCode = urlConnection.getResponseCode();
boolean success = 200 <= responseCode && responseCode < 300;

InputStream inputStream = urlConnection.getErrorStream() != null ? urlConnection.getErrorStream() : urlConnection.getInputStream();
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, UTF_8))) {
String responseBody = br.lines().collect(Collectors.joining(System.lineSeparator()));
if (!success) {
String method = urlConnection.getRequestMethod();
URL url = urlConnection.getURL();
throw createCurlLikeException(method, url, requestHeaders, responseHeaders, responseBody);
}
}
}

static String generateCurlLikeMessage(
static IOException createCurlLikeException(
String method,
URL url,
Map<String, List<String>> requestHeaders,
Map<String, List<String>> responseHeaders,
String responseBody,
boolean redirect) {
return String.format(
"%s:\n> %s %s\n%s%s\n%s",
redirect ? "HTTP redirect not supported" : "HTTP request failed",
String responseBody) {
return new IOException(String.format(
"%s:\n> %s %s%s%s%s",
"HTTP request failed",
method,
url,
headersToString("> ", requestHeaders),
headersToString("< ", responseHeaders),
responseBody
);
));
}

private static String headersToString(String prefix, Map<String, List<String>> headers) {
Expand All @@ -109,10 +112,12 @@ private static String headersToString(String prefix, Map<String, List<String>> h
.map(value -> {
if (header.getKey() == null) {
return prefix + value;
} else if (header.getValue() == null) {
return prefix + header.getKey();
} else {
return prefix + (header.getKey() + ": ") + value;
return prefix + header.getKey() + ": " + value;
}
})
).collect(Collectors.joining("\n"));
).collect(Collectors.joining("\n", "", "\n"));
}
}
48 changes: 31 additions & 17 deletions core/src/test/java/io/cucumber/core/plugin/UrlOutputStreamTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
@ExtendWith({VertxExtension.class})
public class UrlOutputStreamTest {
private int port;
private IOException exception;
private Exception exception;

@BeforeEach
void randomPort() throws IOException {
Expand All @@ -48,26 +48,37 @@ void throws_exception_for_500_status(Vertx vertx, VertxTestContext testContext)

verifyRequest(option, testServer, vertx, testContext, requestBody);
assertThat(testContext.awaitCompletion(5, TimeUnit.SECONDS), is(true));
assertThat(exception.getMessage(), is(equalTo("HTTP request failed:\n" +
assertThat(exception.getMessage(), equalTo("HTTP request failed:\n" +
"> POST http://localhost:" + port + "\n" +
"< HTTP/1.1 500 Internal Server Error\n" +
"< transfer-encoding: chunked\n" +
"Oh noes")));
"Oh noes"
));
}

@Test
void throws_exception_for_redirects(Vertx vertx, VertxTestContext testContext) throws InterruptedException {
void follows_307_temporary_redirects(Vertx vertx, VertxTestContext testContext) throws InterruptedException {
String requestBody = "hello";
TestServer testServer = new TestServer(port, testContext, requestBody, HttpMethod.POST, null, "application/x-www-form-urlencoded", 200, "");
CurlOption url = CurlOption.parse(format("http://localhost:%d/redirect", port));
verifyRequest(url, testServer, vertx, testContext, requestBody);

assertThat(testContext.awaitCompletion(5, TimeUnit.SECONDS), is(true));
assertThat(exception.getMessage(), is(equalTo("HTTP redirect not supported:\n" +
"> POST http://localhost:" + port + "/redirect\n" +
"< HTTP/1.1 301 Moved Permanently\n" +
"< content-length: 0\n" +
"< Location: /\n")));
}

@Test
void throws_exception_for_307_temporary_redirect_without_location(Vertx vertx, VertxTestContext testContext) throws InterruptedException {
String requestBody = "hello";
TestServer testServer = new TestServer(port, testContext, requestBody, HttpMethod.POST, null, "application/x-www-form-urlencoded", 200, "");
CurlOption url = CurlOption.parse(format("http://localhost:%d/redirect-no-location", port));
verifyRequest(url, testServer, vertx, testContext, requestBody);

assertThat(testContext.awaitCompletion(5, TimeUnit.SECONDS), is(true));
assertThat(exception.getMessage(), equalTo("HTTP request failed:\n" +
"> POST http://localhost:" + port + "/redirect-no-location\n" +
"< HTTP/1.1 307 Temporary Redirect\n" +
"< content-length: 0\n"
));
}

@Test
Expand Down Expand Up @@ -103,7 +114,7 @@ private void verifyRequest(CurlOption url, TestServer testServer, Vertx vertx, V
w.flush();
w.close();
testContext.completeNow();
} catch (IOException e) {
} catch (Exception e) {
exception = e;
testContext.completeNow();
}
Expand Down Expand Up @@ -147,15 +158,18 @@ public TestServer(
@Override
public void start(Promise<Void> startPromise) {
Router router = Router.router(vertx);
router.route("/redirect").handler(ctx -> {
ctx.response().setStatusCode(307);
ctx.response().headers().add("Location", "http://localhost:" + port);
ctx.response().end();
});
router.route("/redirect-no-location").handler(ctx -> {
ctx.response().setStatusCode(307);
ctx.response().end();
});

router.route().handler(ctx -> {
if (ctx.request().uri().equals("/redirect")) {
ctx.response().setStatusCode(301);
ctx.response().headers().add("Location", "/");
ctx.response().end();
return;
}
ctx.response().setStatusCode(statusCode);

testContext.verify(() -> {
assertThat(ctx.request().method(), is(equalTo(expectedMethod)));
assertThat(ctx.request().query(), is(equalTo(expectedQuery)));
Expand Down