8378344: Refactor test/jdk/java/net/httpclient/*.java TestNG tests to JUnit

Reviewed-by: vyazici
This commit is contained in:
Daniel Fuchs 2026-02-24 13:57:01 +00:00
parent e452d47867
commit 49f14eb9fc
79 changed files with 2804 additions and 2617 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -46,24 +46,24 @@ import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import static java.time.Duration.*;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
abstract class AbstractConnectTimeoutHandshake {
// The number of iterations each testXXXClient performs.
static final int TIMES = 2;
Server server;
URI httpsURI;
private static Server server;
private static URI httpsURI;
static final Duration NO_DURATION = null;
@ -79,8 +79,7 @@ abstract class AbstractConnectTimeoutHandshake {
static final List<String> METHODS = List.of("GET" , "POST");
static final List<Version> VERSIONS = List.of(HTTP_2, HTTP_1_1);
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
List<Object[]> l = new ArrayList<>();
for (List<Duration> timeouts : TIMEOUTS) {
Duration connectTimeout = timeouts.get(0);
@ -198,8 +197,8 @@ abstract class AbstractConnectTimeoutHandshake {
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
server = new Server();
httpsURI = URIBuilder.newBuilder()
.scheme("https")
@ -210,8 +209,8 @@ abstract class AbstractConnectTimeoutHandshake {
out.println("HTTPS URI: " + httpsURI);
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
server.close();
out.printf("%n--- teardown ---%n");

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2026, 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
@ -38,9 +38,6 @@ import javax.net.ssl.SSLContext;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.httpclient.test.lib.http3.Http3TestServer;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import static java.lang.System.err;
import static java.lang.System.out;
@ -49,8 +46,16 @@ import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
// Use TestInstance.Lifecycle.PER_CLASS because we need access
// to this.getClass() in methods that are called from
// @BeforeAll and @AfterAll
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public abstract class AbstractNoBody implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
@ -76,7 +81,6 @@ public abstract class AbstractNoBody implements HttpServerAdapters {
// a shared executor helps reduce the amount of threads created by the test
static final ExecutorService executor = Executors.newFixedThreadPool(ITERATION_COUNT * 2);
static final ExecutorService serverExecutor = Executors.newFixedThreadPool(ITERATION_COUNT * 4);
static final AtomicLong serverCount = new AtomicLong();
static final AtomicLong clientCount = new AtomicLong();
static final long start = System.nanoTime();
public static String now() {
@ -87,7 +91,6 @@ public abstract class AbstractNoBody implements HttpServerAdapters {
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
}
@DataProvider(name = "variants")
public Object[][] variants() {
return new Object[][]{
{ http3URI_fixed, false,},
@ -145,8 +148,8 @@ public abstract class AbstractNoBody implements HttpServerAdapters {
var request = newRequestBuilder(http3URI_head)
.HEAD().version(HTTP_2).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), HTTP_2);
assertEquals(200, response.statusCode());
assertEquals(HTTP_2, response.version());
out.println("\n" + now() + "--- HEAD request succeeded ----\n");
err.println("\n" + now() + "--- HEAD request succeeded ----\n");
return response;
@ -182,7 +185,7 @@ public abstract class AbstractNoBody implements HttpServerAdapters {
}
}
@BeforeTest
@BeforeAll
public void setup() throws Exception {
printStamp(START, "setup");
HttpServerAdapters.enableServerLogging();
@ -252,7 +255,7 @@ public abstract class AbstractNoBody implements HttpServerAdapters {
printStamp(END,"setup");
}
@AfterTest
@AfterAll
public void teardown() throws Exception {
printStamp(START, "teardown");
sharedClient.close();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2022, 2026, 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
@ -37,36 +37,37 @@ import javax.net.ssl.SSLContext;
import jdk.test.lib.net.SimpleSSLContext;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Version.HTTP_2;
import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.net.http.HttpOption.Http3DiscoveryMode.ALT_SVC;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/*
* @test
* @summary Verifies that the HTTP client correctly handles various alt-svc usages
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.common.HttpServerAdapters
*
* @run testng/othervm -Djdk.internal.httpclient.debug=true
* @run junit/othervm -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=requests,responses,errors
* AltServiceUsageTest
*/
public class AltServiceUsageTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
private HttpTestServer originServer;
private HttpTestServer altServer;
private static HttpTestServer originServer;
private static HttpTestServer altServer;
private DatagramChannel udpNotResponding;
private static DatagramChannel udpNotResponding;
@BeforeClass
public void beforeClass() throws Exception {
@BeforeAll
public static void beforeClass() throws Exception {
// attempt to create an HTTP/3 server, an HTTP/2 server, and a
// DatagramChannel bound to the same port as the HTTP/2 server
int count = 0;
@ -99,7 +100,7 @@ public class AltServiceUsageTest implements HttpServerAdapters {
System.err.println("**** All servers started. Test will start shortly ****");
}
private void createServers() throws IOException {
private static void createServers() throws IOException {
altServer = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext);
altServer.addHandler(new All200OKHandler(), "/foo/");
altServer.addHandler(new RequireAltUsedHeader(), "/bar/");
@ -114,8 +115,8 @@ public class AltServiceUsageTest implements HttpServerAdapters {
originServer.start();
}
@AfterClass
public void afterClass() throws Exception {
@AfterAll
public static void afterClass() throws Exception {
safeStop(originServer);
safeStop(altServer);
safeClose(udpNotResponding);
@ -271,14 +272,14 @@ public class AltServiceUsageTest implements HttpServerAdapters {
System.out.println("Issuing request " + reqURI);
final HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
Assert.assertEquals(response.statusCode(), 200, "Unexpected response code");
Assert.assertEquals(response.body(), H3AltServicePublisher.RESPONSE_CONTENT,
Assertions.assertEquals(200, response.statusCode(), "Unexpected response code");
Assertions.assertEquals(H3AltServicePublisher.RESPONSE_CONTENT, response.body(),
"Unexpected response body");
final Optional<String> altSvcHeader = response.headers().firstValue("alt-svc");
Assert.assertTrue(altSvcHeader.isPresent(), "alt-svc header is missing in response");
Assertions.assertTrue(altSvcHeader.isPresent(), "alt-svc header is missing in response");
System.out.println("Received alt-svc header value: " + altSvcHeader.get());
final String expectedHeader = "h3=\"" + toHostPort(altServer) + "\"";
Assert.assertTrue(altSvcHeader.get().contains(expectedHeader),
Assertions.assertTrue(altSvcHeader.get().contains(expectedHeader),
"Unexpected alt-svc header value: " + altSvcHeader.get()
+ ", was expected to contain: " + expectedHeader);
@ -286,8 +287,8 @@ public class AltServiceUsageTest implements HttpServerAdapters {
System.out.println("Again issuing request " + reqURI);
final HttpResponse<String> secondResponse = client.send(request,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
Assert.assertEquals(secondResponse.statusCode(), 200, "Unexpected response code");
Assert.assertEquals(secondResponse.body(), All200OKHandler.RESPONSE_CONTENT,
Assertions.assertEquals(200, secondResponse.statusCode(), "Unexpected response code");
Assertions.assertEquals(All200OKHandler.RESPONSE_CONTENT, secondResponse.body(),
"Unexpected response body");
var TRACKER = ReferenceTracker.INSTANCE;
var tracker = TRACKER.getTracker(client);
@ -318,14 +319,14 @@ public class AltServiceUsageTest implements HttpServerAdapters {
System.out.println("Issuing request " + reqURI);
final HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
Assert.assertEquals(response.statusCode(), 421, "Unexpected response code");
Assert.assertEquals(response.body(), H3AltServicePublisher.RESPONSE_CONTENT,
Assertions.assertEquals(421, response.statusCode(), "Unexpected response code");
Assertions.assertEquals(H3AltServicePublisher.RESPONSE_CONTENT, response.body(),
"Unexpected response body");
final Optional<String> altSvcHeader = response.headers().firstValue("alt-svc");
Assert.assertTrue(altSvcHeader.isPresent(), "alt-svc header is missing in response");
Assertions.assertTrue(altSvcHeader.isPresent(), "alt-svc header is missing in response");
System.out.println("Received alt-svc header value: " + altSvcHeader.get());
final String expectedHeader = "h3=\"" + toHostPort(altServer) + "\"";
Assert.assertTrue(altSvcHeader.get().contains(expectedHeader),
Assertions.assertTrue(altSvcHeader.get().contains(expectedHeader),
"Unexpected alt-svc header value: " + altSvcHeader.get()
+ ", was expected to contain: " + expectedHeader);
@ -333,8 +334,8 @@ public class AltServiceUsageTest implements HttpServerAdapters {
System.out.println("Again issuing request " + reqURI);
final HttpResponse<String> secondResponse = client.send(request,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
Assert.assertEquals(secondResponse.statusCode(), 421, "Unexpected response code");
Assert.assertEquals(response.body(), H3AltServicePublisher.RESPONSE_CONTENT,
Assertions.assertEquals(421, secondResponse.statusCode(), "Unexpected response code");
Assertions.assertEquals(H3AltServicePublisher.RESPONSE_CONTENT, response.body(),
"Unexpected response body");
var TRACKER = ReferenceTracker.INSTANCE;
var tracker = TRACKER.getTracker(client);
@ -369,14 +370,14 @@ public class AltServiceUsageTest implements HttpServerAdapters {
System.out.println("Issuing request " + reqURI);
final HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
Assert.assertEquals(response.statusCode(), 200, "Unexpected response code");
Assert.assertEquals(response.body(), H3AltServicePublisher.RESPONSE_CONTENT,
Assertions.assertEquals(200, response.statusCode(), "Unexpected response code");
Assertions.assertEquals(H3AltServicePublisher.RESPONSE_CONTENT, response.body(),
"Unexpected response body");
final Optional<String> altSvcHeader = response.headers().firstValue("alt-svc");
Assert.assertTrue(altSvcHeader.isPresent(), "alt-svc header is missing in response");
Assertions.assertTrue(altSvcHeader.isPresent(), "alt-svc header is missing in response");
System.out.println("Received alt-svc header value: " + altSvcHeader.get());
final String expectedHeader = "h3=\"" + toHostPort(altServer) + "\"";
Assert.assertTrue(altSvcHeader.get().contains(expectedHeader),
Assertions.assertTrue(altSvcHeader.get().contains(expectedHeader),
"Unexpected alt-svc header value: " + altSvcHeader.get()
+ ", was expected to contain: " + expectedHeader);
@ -386,8 +387,8 @@ public class AltServiceUsageTest implements HttpServerAdapters {
System.out.println("Again issuing request " + reqURI);
final HttpResponse<String> secondResponse = client.send(request,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
Assert.assertEquals(secondResponse.statusCode(), 200, "Unexpected response code");
Assert.assertEquals(secondResponse.body(), RequireAltUsedHeader.RESPONSE_CONTENT,
Assertions.assertEquals(200, secondResponse.statusCode(), "Unexpected response code");
Assertions.assertEquals(RequireAltUsedHeader.RESPONSE_CONTENT, secondResponse.body(),
"Unexpected response body");
var TRACKER = ReferenceTracker.INSTANCE;
var tracker = TRACKER.getTracker(client);
@ -424,14 +425,14 @@ public class AltServiceUsageTest implements HttpServerAdapters {
System.out.println("Issuing request " + reqURI);
final HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
Assert.assertEquals(response.statusCode(), 200, "Unexpected response code");
Assert.assertEquals(response.body(), H3AltServicePublisher.RESPONSE_CONTENT,
Assertions.assertEquals(200, response.statusCode(), "Unexpected response code");
Assertions.assertEquals(H3AltServicePublisher.RESPONSE_CONTENT, response.body(),
"Unexpected response body");
final Optional<String> altSvcHeader = response.headers().firstValue("alt-svc");
Assert.assertTrue(altSvcHeader.isPresent(), "alt-svc header is missing in response");
Assertions.assertTrue(altSvcHeader.isPresent(), "alt-svc header is missing in response");
System.out.println("Received alt-svc header value: " + altSvcHeader.get());
final String expectedHeader = "h3=\"" + toHostPort(altServer) + "\"";
Assert.assertTrue(altSvcHeader.get().contains(expectedHeader),
Assertions.assertTrue(altSvcHeader.get().contains(expectedHeader),
"Unexpected alt-svc header value: " + altSvcHeader.get()
+ ", was expected to contain: " + expectedHeader);
@ -439,8 +440,8 @@ public class AltServiceUsageTest implements HttpServerAdapters {
System.out.println("Again issuing request " + reqURI);
final HttpResponse<String> secondResponse = client.send(request,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
Assert.assertEquals(secondResponse.statusCode(), 200, "Unexpected response code");
Assert.assertEquals(secondResponse.body(), All200OKHandler.RESPONSE_CONTENT,
Assertions.assertEquals(200, secondResponse.statusCode(), "Unexpected response code");
Assertions.assertEquals(All200OKHandler.RESPONSE_CONTENT, secondResponse.body(),
"Unexpected response body");
// wait for alt-service to expire
@ -452,8 +453,8 @@ public class AltServiceUsageTest implements HttpServerAdapters {
System.out.println("Issuing request for a third time " + reqURI);
final HttpResponse<String> thirdResponse = client.send(request,
HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
Assert.assertEquals(thirdResponse.statusCode(), 200, "Unexpected response code");
Assert.assertEquals(thirdResponse.body(), H3AltServicePublisher.RESPONSE_CONTENT,
Assertions.assertEquals(200, thirdResponse.statusCode(), "Unexpected response code");
Assertions.assertEquals(H3AltServicePublisher.RESPONSE_CONTENT, thirdResponse.body(),
"Unexpected response body");
var TRACKER = ReferenceTracker.INSTANCE;
var tracker = TRACKER.getTracker(client);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -63,19 +63,20 @@ import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestServer;
import jdk.httpclient.test.lib.http2.Http2TestServer;
import jdk.httpclient.test.lib.http2.Http2TestExchange;
import jdk.httpclient.test.lib.http2.Http2Handler;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.net.http.HttpResponse.BodyHandlers.ofFileDownload;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.*;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
@ -86,24 +87,24 @@ import static org.testng.Assert.fail;
* jdk.test.lib.Platform jdk.test.lib.util.FileUtils
* jdk.httpclient.test.lib.common.HttpServerAdapters
* jdk.httpclient.test.lib.common.TestServerConfigurator
* @run testng/othervm/timeout=480 AsFileDownloadTest
* @run junit/othervm/timeout=480 AsFileDownloadTest
*/
public class AsFileDownloadTest {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpsServer httpsTestServer; // HTTPS/1.1
Http2TestServer http2TestServer; // HTTP/2 ( h2c )
Http2TestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer h3TestServer; // HTTP/3
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String h3URI;
private static HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpsServer httpsTestServer; // HTTPS/1.1
private static Http2TestServer http2TestServer; // HTTP/2 ( h2c )
private static Http2TestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer h3TestServer; // HTTP/3
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String h3URI;
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
Path tempDir;
static Path tempDir;
static final String[][] contentDispositionValues = new String[][] {
// URI query Content-Type header value Expected filename
@ -151,8 +152,7 @@ public class AsFileDownloadTest {
{ "041", "attachment; filename=\"foo/../../file12.txt\"", "file12.txt" },
};
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
List<Object[]> list = new ArrayList<>();
Arrays.asList(contentDispositionValues).stream()
@ -181,7 +181,8 @@ public class AsFileDownloadTest {
return builder.sslContext(sslContext).proxy(Builder.NO_PROXY).build();
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void test(String uriString, String contentDispositionValue, String expectedFilename,
Optional<Version> requestVersion) throws Exception {
out.printf("test(%s, %s, %s): starting", uriString, contentDispositionValue, expectedFilename);
@ -207,14 +208,13 @@ public class AsFileDownloadTest {
String fileContents = new String(Files.readAllBytes(response.body()), UTF_8);
out.println("Got body: " + fileContents);
assertEquals(response.statusCode(), 200);
assertEquals(body.getFileName().toString(), expectedFilename);
assertEquals(200, response.statusCode());
assertEquals(expectedFilename, body.getFileName().toString());
assertTrue(response.headers().firstValue("Content-Disposition").isPresent());
assertEquals(response.headers().firstValue("Content-Disposition").get(),
contentDispositionValue);
assertEquals(fileContents, "May the luck of the Irish be with you!");
assertEquals( contentDispositionValue, response.headers().firstValue("Content-Disposition").get());
assertEquals("May the luck of the Irish be with you!", fileContents);
if (requestVersion.isPresent()) {
assertEquals(response.version(), requestVersion.get(), "unexpected HTTP version" +
assertEquals(requestVersion.get(), response.version(), "unexpected HTTP version" +
" in response");
}
@ -254,8 +254,7 @@ public class AsFileDownloadTest {
};
@DataProvider(name = "negative")
public Object[][] negative() {
public static Object[][] negative() {
List<Object[]> list = new ArrayList<>();
Arrays.asList(contentDispositionBADValues).stream()
@ -276,7 +275,8 @@ public class AsFileDownloadTest {
return list.stream().toArray(Object[][]::new);
}
@Test(dataProvider = "negative")
@ParameterizedTest
@MethodSource("negative")
void negativeTest(String uriString, String contentDispositionValue,
Optional<Version> requestVersion) throws Exception {
out.printf("negativeTest(%s, %s): starting", uriString, contentDispositionValue);
@ -330,8 +330,8 @@ public class AsFileDownloadTest {
return builder;
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
tempDir = Paths.get("asFileDownloadTest.tmp.dir");
if (Files.exists(tempDir))
throw new AssertionError("Unexpected test work dir existence: " + tempDir.toString());
@ -380,8 +380,8 @@ public class AsFileDownloadTest {
h3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop(0);
httpsTestServer.stop(0);
http2TestServer.stop();
@ -474,11 +474,11 @@ public class AsFileDownloadTest {
for (String name : List.of(headerName.toUpperCase(Locale.ROOT),
headerName.toLowerCase(Locale.ROOT))) {
assertTrue(headers.firstValue(name).isPresent());
assertEquals(headers.firstValue(name).get(), headerValue.get(0));
assertEquals(headers.allValues(name).size(), headerValue.size());
assertEquals(headers.allValues(name), headerValue);
assertEquals(headers.map().get(name).size(), headerValue.size());
assertEquals(headers.map().get(name), headerValue);
assertEquals(headerValue.get(0), headers.firstValue(name).get());
assertEquals(headerValue.size(), headers.allValues(name).size());
assertEquals(headerValue, headers.allValues(name));
assertEquals(headerValue.size(), headers.map().get(name).size());
assertEquals(headerValue, headers.map().get(name));
}
}
} catch (Throwable t) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2022, 2026, 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
@ -29,7 +29,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* ReferenceTracker
* @run testng/othervm
* @run junit/othervm
* -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* AsyncExecutorShutdown
@ -68,10 +68,6 @@ import javax.net.ssl.SSLContext;
import jdk.test.lib.RandomFactory;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
@ -81,9 +77,14 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class AsyncExecutorShutdown implements HttpServerAdapters {
@ -92,27 +93,26 @@ public class AsyncExecutorShutdown implements HttpServerAdapters {
}
static final Random RANDOM = RandomFactory.getRandom();
ExecutorService readerService;
private static ExecutorService readerService;
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 6 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer h2h3TestServer; // HTTP/2 ( h2+h3 )
HttpTestServer h3TestServer; // HTTP/2 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String h2h3URI;
String h3URI;
String h2h3Head;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 6 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer h2h3TestServer; // HTTP/2 ( h2+h3 )
private static HttpTestServer h3TestServer; // HTTP/2 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String h2h3URI;
private static String h3URI;
private static String h2h3Head;
static final String MESSAGE = "AsyncExecutorShutdown message body";
static final int ITERATIONS = 3;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ h2h3URI, HTTP_3, h2h3TestServer.h3DiscoveryConfig() },
{ h3URI, HTTP_3, h3TestServer.h3DiscoveryConfig() },
@ -124,7 +124,7 @@ public class AsyncExecutorShutdown implements HttpServerAdapters {
}
static final AtomicLong requestCounter = new AtomicLong();
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
static Throwable getCause(Throwable t) {
while (t instanceof CompletionException || t instanceof ExecutionException) {
@ -165,7 +165,8 @@ public class AsyncExecutorShutdown implements HttpServerAdapters {
throw new AssertionError(what + ": Unexpected exception: " + cause, cause);
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testConcurrent(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- starting (%s, %s, %s) ----%n%n", uriString, version, config);
ExecutorService executorService = Executors.newCachedThreadPool();
@ -206,14 +207,14 @@ public class AsyncExecutorShutdown implements HttpServerAdapters {
responseCF = client.sendAsync(request, BodyHandlers.ofInputStream())
.thenApply((response) -> {
out.println(si + ": Got response: " + response);
assertEquals(response.statusCode(), 200);
if (si >= head) assertEquals(response.version(), version);
assertEquals(200, response.statusCode());
if (si >= head) assertEquals(version, response.version());
return response;
});
bodyCF = responseCF.thenApplyAsync(HttpResponse::body, readerService)
.thenApply(AsyncExecutorShutdown::readBody)
.thenApply((s) -> {
assertEquals(s, MESSAGE);
assertEquals(MESSAGE, s);
return s;
});
} catch (RejectedExecutionException x) {
@ -275,7 +276,8 @@ public class AsyncExecutorShutdown implements HttpServerAdapters {
CompletableFuture.allOf(bodies.toArray(new CompletableFuture<?>[0])).get();
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testSequential(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- starting (%s, %s, %s) ----%n%n", uriString, version, config);
ExecutorService executorService = Executors.newCachedThreadPool();
@ -316,13 +318,13 @@ public class AsyncExecutorShutdown implements HttpServerAdapters {
responseCF = client.sendAsync(request, BodyHandlers.ofInputStream())
.thenApply((response) -> {
out.println(si + ": Got response: " + response);
assertEquals(response.statusCode(), 200);
if (si > 0) assertEquals(response.version(), version);
assertEquals(200, response.statusCode());
if (si > 0) assertEquals(version, response.version());
return response;
});
bodyCF = responseCF.thenApplyAsync(HttpResponse::body, readerService)
.thenApply(AsyncExecutorShutdown::readBody)
.thenApply((s) -> {assertEquals(s, MESSAGE); return s;})
.thenApply((s) -> {assertEquals(MESSAGE, s); return s;})
.thenApply((s) -> {out.println(si + ": Got body: " + s); return s;});
} catch (RejectedExecutionException x) {
out.println(i + ": Got expected exception: " + x);
@ -397,7 +399,7 @@ public class AsyncExecutorShutdown implements HttpServerAdapters {
.HEAD()
.build();
var resp = client.send(request, BodyHandlers.discarding());
assertEquals(resp.statusCode(), 200);
assertEquals(200, resp.statusCode());
}
static void shutdown(ExecutorService executorService) {
@ -409,8 +411,8 @@ public class AsyncExecutorShutdown implements HttpServerAdapters {
}
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
out.println("\n**** Setup ****\n");
readerService = Executors.newCachedThreadPool();
@ -445,8 +447,8 @@ public class AsyncExecutorShutdown implements HttpServerAdapters {
h3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
Thread.sleep(100);
AssertionError fail = TRACKER.checkShutdown(5000);
try {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2026, 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
@ -31,7 +31,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* ReferenceTracker
* @run testng/othervm
* @run junit/othervm
* -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* AsyncShutdownNow
@ -70,10 +70,6 @@ import javax.net.ssl.SSLContext;
import jdk.test.lib.RandomFactory;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
@ -84,10 +80,15 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.ALT_SVC;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class AsyncShutdownNow implements HttpServerAdapters {
@ -96,27 +97,26 @@ public class AsyncShutdownNow implements HttpServerAdapters {
}
static final Random RANDOM = RandomFactory.getRandom();
ExecutorService readerService;
private static ExecutorService readerService;
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer h2h3TestServer; // HTTP/3 ( h2 + h3 )
HttpTestServer h3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String h2h3URI;
String h2h3Head;
String h3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer h2h3TestServer; // HTTP/3 ( h2 + h3 )
private static HttpTestServer h3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String h2h3URI;
private static String h2h3Head;
private static String h3URI;
static final String MESSAGE = "AsyncShutdownNow message body";
static final int ITERATIONS = 3;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ h2h3URI, HTTP_3, h2h3TestServer.h3DiscoveryConfig()},
{ h3URI, HTTP_3, h3TestServer.h3DiscoveryConfig()},
@ -168,11 +168,11 @@ public class AsyncShutdownNow implements HttpServerAdapters {
out.println(step + ": Got response: " + response);
out.printf("%s: expect status 200 and version %s (%s) for %s%n", step, version, config,
response.request().uri());
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
if (step == 0 && version == HTTP_3 && firstVersionMayNotMatch) {
out.printf("%s: version not checked%n", step);
} else {
assertEquals(response.version(), version);
assertEquals(version, response.version());
out.printf("%s: got expected version %s%n", step, response.version());
}
return this;
@ -185,7 +185,7 @@ public class AsyncShutdownNow implements HttpServerAdapters {
.HEAD()
.build();
var resp = client.send(request, BodyHandlers.discarding());
assertEquals(resp.statusCode(), 200);
assertEquals(200, resp.statusCode());
}
static boolean hasExpectedMessage(IOException io) {
@ -223,7 +223,8 @@ public class AsyncShutdownNow implements HttpServerAdapters {
throw new AssertionError(what + ": Unexpected exception: " + cause, cause);
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testConcurrent(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- starting concurrent (%s, %s, %s) ----%n%n", uriString, version, config);
HttpClient client = newClientBuilderForH3()
@ -260,7 +261,7 @@ public class AsyncShutdownNow implements HttpServerAdapters {
bodyCF = responseCF.thenApplyAsync(HttpResponse::body, readerService)
.thenApply(AsyncShutdownNow::readBody)
.thenApply((s) -> {
assertEquals(s, MESSAGE);
assertEquals(MESSAGE, s);
return s;
});
long sleep = RANDOM.nextLong(5);
@ -320,7 +321,8 @@ public class AsyncShutdownNow implements HttpServerAdapters {
return failed;
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testSequential(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- starting sequential (%s, %s, %s) ----%n%n",
uriString, version, config);
@ -354,7 +356,7 @@ public class AsyncShutdownNow implements HttpServerAdapters {
bodyCF = responseCF.thenApplyAsync(HttpResponse::body, readerService)
.thenApply(AsyncShutdownNow::readBody)
.thenApply((s) -> {
assertEquals(s, MESSAGE);
assertEquals(MESSAGE, s);
return s;
})
.thenApply((s) -> {
@ -403,8 +405,8 @@ public class AsyncShutdownNow implements HttpServerAdapters {
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
out.println("\n**** Setup ****\n");
readerService = Executors.newCachedThreadPool();
@ -439,8 +441,8 @@ public class AsyncShutdownNow implements HttpServerAdapters {
h3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
Thread.sleep(100);
AssertionError fail = TRACKER.checkShutdown(5000);
try {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, 2026, 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
@ -40,10 +40,6 @@ import jdk.httpclient.test.lib.common.HttpServerAdapters;
import com.sun.net.httpserver.HttpsServer;
import jdk.httpclient.test.lib.common.TestServerConfigurator;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.net.ssl.SSLContext;
@ -54,7 +50,12 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.ANY;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.Http3DiscoveryMode.ALT_SVC;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static org.testng.Assert.*;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
@ -63,7 +64,7 @@ import static org.testng.Assert.*;
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters jdk.test.lib.net.SimpleSSLContext
* DigestEchoServer ReferenceTracker jdk.httpclient.test.lib.common.TestServerConfigurator
* @run testng/othervm -Dtest.requiresHost=true
* @run junit/othervm -Dtest.requiresHost=true
* -Djdk.httpclient.HttpClient.log=requests,headers,errors,quic
* -Djdk.internal.httpclient.debug=false
* AuthFilterCacheTest
@ -81,29 +82,28 @@ public class AuthFilterCacheTest implements HttpServerAdapters {
SSLContext.setDefault(context);
}
HttpTestServer http1Server;
HttpTestServer http2Server;
HttpTestServer https1Server;
HttpTestServer https2Server;
HttpTestServer h3onlyServer;
HttpTestServer h3altSvcServer;
DigestEchoServer.TunnelingProxy proxy;
URI http1URI;
URI https1URI;
URI http2URI;
URI https2URI;
URI h3onlyURI;
URI h3altSvcURI;
InetSocketAddress proxyAddress;
ProxySelector proxySelector;
MyAuthenticator auth;
HttpClient client;
ExecutorService serverExecutor = Executors.newCachedThreadPool();
ExecutorService virtualExecutor = Executors.newThreadPerTaskExecutor(Thread.ofVirtual()
private static HttpTestServer http1Server;
private static HttpTestServer http2Server;
private static HttpTestServer https1Server;
private static HttpTestServer https2Server;
private static HttpTestServer h3onlyServer;
private static HttpTestServer h3altSvcServer;
private static DigestEchoServer.TunnelingProxy proxy;
private static URI http1URI;
private static URI https1URI;
private static URI http2URI;
private static URI https2URI;
private static URI h3onlyURI;
private static URI h3altSvcURI;
private static InetSocketAddress proxyAddress;
private static ProxySelector proxySelector;
private static MyAuthenticator auth;
private static HttpClient client;
private static ExecutorService serverExecutor = Executors.newCachedThreadPool();
private static ExecutorService virtualExecutor = Executors.newThreadPerTaskExecutor(Thread.ofVirtual()
.name("HttpClient-Worker", 0).factory());
@DataProvider(name = "uris")
Object[][] testURIs() {
static Object[][] testURIs() {
Object[][] uris = new Object[][]{
{List.of(http1URI.resolve("direct/orig/"),
https1URI.resolve("direct/orig/"),
@ -117,8 +117,8 @@ public class AuthFilterCacheTest implements HttpServerAdapters {
return uris;
}
public HttpClient newHttpClient(ProxySelector ps, Authenticator auth) {
HttpClient.Builder builder = newClientBuilderForH3()
public static HttpClient newHttpClient(ProxySelector ps, Authenticator auth) {
HttpClient.Builder builder = HttpServerAdapters.createClientBuilderForH3()
.executor(virtualExecutor)
.sslContext(context)
.authenticator(auth)
@ -126,8 +126,8 @@ public class AuthFilterCacheTest implements HttpServerAdapters {
return builder.build();
}
@BeforeClass
public void setUp() throws Exception {
@BeforeAll
public static void setUp() throws Exception {
try {
InetSocketAddress sa =
new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
@ -189,8 +189,8 @@ public class AuthFilterCacheTest implements HttpServerAdapters {
.version(HTTP_2).build();
System.out.println("Sending head request: " + headRequest);
var headResponse = client.send(headRequest, BodyHandlers.ofString());
assertEquals(headResponse.statusCode(), 200);
assertEquals(headResponse.version(), HTTP_2);
assertEquals(200, headResponse.statusCode());
assertEquals(HTTP_2, headResponse.version());
System.out.println("Setup: done");
} catch (Exception x) {
@ -202,8 +202,8 @@ public class AuthFilterCacheTest implements HttpServerAdapters {
}
}
@AfterClass
public void tearDown() {
@AfterAll
public static void tearDown() {
proxy = stop(proxy, DigestEchoServer.TunnelingProxy::stop);
http1Server = stop(http1Server, HttpTestServer::stop);
https1Server = stop(https1Server, HttpTestServer::stop);
@ -378,7 +378,8 @@ public class AuthFilterCacheTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("testURIs")
public void test(List<URI> uris) throws Exception {
System.out.println("Servers listening at "
+ uris.stream().map(URI::toString)

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -26,7 +26,7 @@
* @summary Basic test for redirect and redirect policies
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm
* @run junit/othervm
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* -Djdk.internal.httpclient.debug=true
* BasicRedirectTest
@ -49,10 +49,6 @@ import java.util.Optional;
import java.util.stream.Collectors;
import javax.net.ssl.SSLContext;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
@ -61,39 +57,42 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.ALT_SVC;
import static java.net.http.HttpOption.Http3DiscoveryMode.ANY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class BasicRedirectTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpURIToMoreSecure; // redirects HTTP to HTTPS
String httpURIToH3MoreSecure; // redirects HTTP to HTTPS/3
String httpsURI;
String httpsURIToLessSecure; // redirects HTTPS to HTTP
String http2URI;
String http2URIToMoreSecure; // redirects HTTP to HTTPS
String http2URIToH3MoreSecure; // redirects HTTP to HTTPS/3
String https2URI;
String https2URIToLessSecure; // redirects HTTPS to HTTP
String https3URI;
String https3HeadURI;
String http3URIToLessSecure; // redirects HTTP3 to HTTP
String http3URIToH2cLessSecure; // redirects HTTP3 to h2c
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpURIToMoreSecure; // redirects HTTP to HTTPS
private static String httpURIToH3MoreSecure; // redirects HTTP to HTTPS/3
private static String httpsURI;
private static String httpsURIToLessSecure; // redirects HTTPS to HTTP
private static String http2URI;
private static String http2URIToMoreSecure; // redirects HTTP to HTTPS
private static String http2URIToH3MoreSecure; // redirects HTTP to HTTPS/3
private static String https2URI;
private static String https2URIToLessSecure; // redirects HTTPS to HTTP
private static String https3URI;
private static String https3HeadURI;
private static String http3URIToLessSecure; // redirects HTTP3 to HTTP
private static String http3URIToH2cLessSecure; // redirects HTTP3 to h2c
static final String MESSAGE = "Is fearr Gaeilge briste, na Bearla cliste";
static final int ITERATIONS = 3;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ httpURI, Redirect.ALWAYS, Optional.empty() },
{ httpsURI, Redirect.ALWAYS, Optional.empty() },
@ -121,8 +120,8 @@ public class BasicRedirectTest implements HttpServerAdapters {
};
}
HttpClient createClient(Redirect redirectPolicy, Optional<Version> version) throws Exception {
var clientBuilder = newClientBuilderForH3()
static HttpClient createClient(Redirect redirectPolicy, Optional<Version> version) throws Exception {
var clientBuilder = HttpServerAdapters.createClientBuilderForH3()
.followRedirects(redirectPolicy)
.sslContext(sslContext);
HttpClient client = version.map(clientBuilder::version)
@ -135,23 +134,24 @@ public class BasicRedirectTest implements HttpServerAdapters {
var get = builder.copy().GET().build();
out.printf("%n---- sending initial head request (%s) -----%n", head.uri());
var resp = client.send(head, BodyHandlers.ofString());
assertEquals(resp.statusCode(), 200);
assertEquals(resp.version(), HTTP_2);
assertEquals(200, resp.statusCode());
assertEquals(HTTP_2, resp.version());
out.println("HEADERS: " + resp.headers());
var length = resp.headers().firstValueAsLong("Content-Length")
.orElseThrow(AssertionError::new);
if (length < 0) throw new AssertionError("negative length " + length);
out.printf("%n---- sending initial HTTP/3 GET request (%s) -----%n", get.uri());
resp = client.send(get, BodyHandlers.ofString());
assertEquals(resp.statusCode(), 200);
assertEquals(resp.version(), HTTP_3);
assertEquals(resp.body().getBytes(UTF_8).length, length,
assertEquals(200, resp.statusCode());
assertEquals(HTTP_3, resp.version());
assertEquals(length, resp.body().getBytes(UTF_8).length,
"body \"" + resp.body() + "\": ");
}
return client;
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void test(String uriString, Redirect redirectPolicy, Optional<Version> clientVersion) throws Exception {
out.printf("%n---- starting positive (%s, %s, %s) ----%n", uriString, redirectPolicy,
clientVersion.map(Version::name).orElse("empty"));
@ -169,8 +169,8 @@ public class BasicRedirectTest implements HttpServerAdapters {
out.println(" Got body Path: " + response.body());
out.println(" Got response.request: " + response.request());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), MESSAGE);
assertEquals(200, response.statusCode());
assertEquals(MESSAGE, response.body());
// asserts redirected URI in response.request().uri()
assertTrue(response.uri().getPath().endsWith("message"));
assertPreviousRedirectResponses(request, response, clientVersion);
@ -193,7 +193,7 @@ public class BasicRedirectTest implements HttpServerAdapters {
versions.add(response.version());
assertTrue(300 <= response.statusCode() && response.statusCode() <= 309,
"Expected 300 <= code <= 309, got:" + response.statusCode());
assertEquals(response.body(), null, "Unexpected body: " + response.body());
assertEquals(null, response.body(), "Unexpected body: " + response.body());
String locationHeader = response.headers().firstValue("Location")
.orElseThrow(() -> new RuntimeException("no previous Location"));
assertTrue(uri.toString().endsWith(locationHeader),
@ -202,7 +202,7 @@ public class BasicRedirectTest implements HttpServerAdapters {
} while (response.previousResponse().isPresent());
// initial
assertEquals(initialRequest, response.request(),
assertEquals(response.request(), initialRequest,
String.format("Expected initial request [%s] to equal last prev req [%s]",
initialRequest, response.request()));
if (clientVersion.stream().anyMatch(HTTP_3::equals)) {
@ -214,8 +214,7 @@ public class BasicRedirectTest implements HttpServerAdapters {
// -- negatives
@DataProvider(name = "negative")
public Object[][] negative() {
public static Object[][] negative() {
return new Object[][] {
{ httpURI, Redirect.NEVER, Optional.empty() },
{ httpsURI, Redirect.NEVER, Optional.empty() },
@ -238,7 +237,8 @@ public class BasicRedirectTest implements HttpServerAdapters {
};
}
@Test(dataProvider = "negative")
@ParameterizedTest
@MethodSource("negative")
void testNegatives(String uriString, Redirect redirectPolicy, Optional<Version> clientVersion)
throws Exception {
out.printf("%n---- starting negative (%s, %s, %s) ----%n", uriString, redirectPolicy,
@ -257,8 +257,8 @@ public class BasicRedirectTest implements HttpServerAdapters {
out.println(" Got body Path: " + response.body());
out.println(" Got response.request: " + response.request());
assertEquals(response.statusCode(), 302);
assertEquals(response.body(), "XY");
assertEquals(302, response.statusCode());
assertEquals("XY", response.body());
// asserts original URI in response.request().uri()
assertTrue(response.uri().equals(uri));
assertFalse(response.previousResponse().isPresent());
@ -268,8 +268,8 @@ public class BasicRedirectTest implements HttpServerAdapters {
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpTestServer.create(HTTP_1_1);
httpTestServer.addHandler(new BasicHttpRedirectHandler(), "/http1/same/");
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/same/redirect";
@ -325,8 +325,8 @@ public class BasicRedirectTest implements HttpServerAdapters {
createClient(Redirect.NEVER, Optional.of(HTTP_3));
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop();
httpsTestServer.stop();
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, 2026, 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
@ -25,7 +25,7 @@
* @test
* @summary Basic test for the standard BodySubscribers default behavior
* @bug 8225583 8334028
* @run testng BodySubscribersTest
* @run junit BodySubscribersTest
*/
import java.net.http.HttpResponse.BodySubscriber;
@ -34,16 +34,18 @@ import java.nio.file.Path;
import java.util.List;
import java.util.concurrent.Flow;
import java.util.function.Supplier;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpResponse.BodySubscribers.*;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.file.StandardOpenOption.CREATE;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.expectThrows;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.Assertions;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class BodySubscribersTest {
@ -78,8 +80,7 @@ public class BodySubscribersTest {
@Override public void onComplete() { fail(); }
}
@DataProvider(name = "bodySubscriberSuppliers")
public Object[][] bodySubscriberSuppliers() { ;
public static Object[][] bodySubscriberSuppliers() { ;
List<Supplier<BodySubscriber<?>>> list = List.of(
BSSupplier.create("ofByteArray", () -> ofByteArray()),
BSSupplier.create("ofInputStream", () -> ofInputStream()),
@ -102,7 +103,8 @@ public class BodySubscribersTest {
return list.stream().map(x -> new Object[] { x }).toArray(Object[][]::new);
}
@Test(dataProvider = "bodySubscriberSuppliers")
@ParameterizedTest
@MethodSource("bodySubscriberSuppliers")
void nulls(Supplier<BodySubscriber<?>> bodySubscriberSupplier) {
BodySubscriber<?> bodySubscriber = bodySubscriberSupplier.get();
boolean subscribed = false;
@ -111,18 +113,18 @@ public class BodySubscribersTest {
assertNotNull(bodySubscriber.getBody());
assertNotNull(bodySubscriber.getBody());
assertNotNull(bodySubscriber.getBody());
expectThrows(NPE, () -> bodySubscriber.onSubscribe(null));
expectThrows(NPE, () -> bodySubscriber.onSubscribe(null));
expectThrows(NPE, () -> bodySubscriber.onSubscribe(null));
Assertions.assertThrows(NPE, () -> bodySubscriber.onSubscribe(null));
Assertions.assertThrows(NPE, () -> bodySubscriber.onSubscribe(null));
Assertions.assertThrows(NPE, () -> bodySubscriber.onSubscribe(null));
expectThrows(NPE, () -> bodySubscriber.onNext(null));
expectThrows(NPE, () -> bodySubscriber.onNext(null));
expectThrows(NPE, () -> bodySubscriber.onNext(null));
expectThrows(NPE, () -> bodySubscriber.onNext(null));
Assertions.assertThrows(NPE, () -> bodySubscriber.onNext(null));
Assertions.assertThrows(NPE, () -> bodySubscriber.onNext(null));
Assertions.assertThrows(NPE, () -> bodySubscriber.onNext(null));
Assertions.assertThrows(NPE, () -> bodySubscriber.onNext(null));
expectThrows(NPE, () -> bodySubscriber.onError(null));
expectThrows(NPE, () -> bodySubscriber.onError(null));
expectThrows(NPE, () -> bodySubscriber.onError(null));
Assertions.assertThrows(NPE, () -> bodySubscriber.onError(null));
Assertions.assertThrows(NPE, () -> bodySubscriber.onError(null));
Assertions.assertThrows(NPE, () -> bodySubscriber.onError(null));
if (!subscribed) {
out.println("subscribing");
@ -138,7 +140,8 @@ public class BodySubscribersTest {
} while (true);
}
@Test(dataProvider = "bodySubscriberSuppliers")
@ParameterizedTest
@MethodSource("bodySubscriberSuppliers")
void subscribeMoreThanOnce(Supplier<BodySubscriber<?>> bodySubscriberSupplier) {
BodySubscriber<?> bodySubscriber = bodySubscriberSupplier.get();
bodySubscriber.onSubscribe(new Flow.Subscription() {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -32,33 +32,34 @@ import java.util.concurrent.SubmissionPublisher;
import java.util.function.IntSupplier;
import java.util.stream.IntStream;
import java.net.http.HttpResponse.BodySubscriber;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.Long.MAX_VALUE;
import static java.lang.Long.MIN_VALUE;
import static java.lang.System.out;
import static java.nio.ByteBuffer.wrap;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.net.http.HttpResponse.BodySubscribers.buffering;
import static org.testng.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
* @summary Direct test for HttpResponse.BodySubscriber.buffering() cancellation
* @run testng/othervm BufferingSubscriberCancelTest
* @run junit/othervm BufferingSubscriberCancelTest
*/
public class BufferingSubscriberCancelTest {
@DataProvider(name = "bufferSizes")
public Object[][] bufferSizes() {
public static Object[][] bufferSizes() {
return new Object[][]{
// bufferSize should be irrelevant
{1}, {100}, {511}, {512}, {513}, {1024}, {2047}, {2048}
};
}
@Test(dataProvider = "bufferSizes")
@ParameterizedTest
@MethodSource("bufferSizes")
public void cancelWithoutAnyItemsPublished(int bufferSize) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(1);
SubmissionPublisher<List<ByteBuffer>> publisher =
@ -85,8 +86,7 @@ public class BufferingSubscriberCancelTest {
executor.shutdown();
}
@DataProvider(name = "sizeAndItems")
public Object[][] sizeAndItems() {
public static Object[][] sizeAndItems() {
return new Object[][] {
// bufferSize and item bytes must be equal to count onNext calls
// bufferSize items
@ -103,7 +103,8 @@ public class BufferingSubscriberCancelTest {
};
}
@Test(dataProvider = "sizeAndItems")
@ParameterizedTest
@MethodSource("sizeAndItems")
public void cancelWithItemsPublished(int bufferSize, List<ByteBuffer> items)
throws Exception
{
@ -125,12 +126,13 @@ public class BufferingSubscriberCancelTest {
IntStream.range(0, ITERATION_TIMES+1).forEach(x -> publisher.submit(items));
assertEqualsWithRetry(publisher::getNumberOfSubscribers, 0);
assertEquals(exposingSubscriber.onNextInvocations, ITERATION_TIMES);
assertEquals(ITERATION_TIMES, exposingSubscriber.onNextInvocations);
executor.shutdown();
}
// same as above but with more racy conditions, do not wait on the gate
@Test(dataProvider = "sizeAndItems")
@ParameterizedTest
@MethodSource("sizeAndItems")
public void cancelWithItemsPublishedNoWait(int bufferSize, List<ByteBuffer> items)
throws Exception
{
@ -212,6 +214,6 @@ public class BufferingSubscriberCancelTest {
return;
Thread.sleep(100);
}
assertEquals(actual, expected); // will fail with the usual testng message
assertEquals(expected, actual); // will fail with the usual testng message
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -32,30 +32,31 @@ import java.util.concurrent.Phaser;
import java.util.concurrent.SubmissionPublisher;
import java.util.stream.IntStream;
import java.net.http.HttpResponse.BodySubscriber;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.Long.MAX_VALUE;
import static java.lang.Long.MIN_VALUE;
import static java.nio.ByteBuffer.wrap;
import static java.net.http.HttpResponse.BodySubscribers.buffering;
import static org.testng.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
* @summary Test for HttpResponse.BodySubscriber.buffering() onError/onComplete
* @run testng/othervm BufferingSubscriberErrorCompleteTest
* @run junit/othervm BufferingSubscriberErrorCompleteTest
*/
public class BufferingSubscriberErrorCompleteTest {
@DataProvider(name = "illegalDemand")
public Object[][] illegalDemand() {
public static Object[][] illegalDemand() {
return new Object[][]{
{0L}, {-1L}, {-5L}, {-100L}, {-101L}, {-100_001L}, {MIN_VALUE}
};
}
@Test(dataProvider = "illegalDemand")
@ParameterizedTest
@MethodSource("illegalDemand")
public void illegalRequest(long demand) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(1);
SubmissionPublisher<List<ByteBuffer>> publisher =
@ -72,18 +73,17 @@ public class BufferingSubscriberErrorCompleteTest {
s.request(demand);
gate.arriveAndAwaitAdvance();
assertEquals(previous + 1, exposingSubscriber.onErrorInvocations);
assertEquals(exposingSubscriber.onErrorInvocations, previous + 1);
assertTrue(exposingSubscriber.throwable instanceof IllegalArgumentException,
"Expected IAE, got:" + exposingSubscriber.throwable);
furtherCancelsRequestsShouldBeNoOp(s);
assertEquals(exposingSubscriber.onErrorInvocations, 1);
assertEquals(1, exposingSubscriber.onErrorInvocations);
executor.shutdown();
}
@DataProvider(name = "bufferAndItemSizes")
public Object[][] bufferAndItemSizes() {
public static Object[][] bufferAndItemSizes() {
List<Object[]> values = new ArrayList<>();
for (int bufferSize : new int[] { 1, 5, 10, 100, 1000 })
@ -93,7 +93,8 @@ public class BufferingSubscriberErrorCompleteTest {
return values.stream().toArray(Object[][]::new);
}
@Test(dataProvider = "bufferAndItemSizes")
@ParameterizedTest
@MethodSource("bufferAndItemSizes")
public void onErrorFromPublisher(int bufferSize,
int numberOfItems)
throws Exception
@ -117,19 +118,19 @@ public class BufferingSubscriberErrorCompleteTest {
Subscription s = exposingSubscriber.subscription;
assertEquals(exposingSubscriber.onErrorInvocations, 1);
assertEquals(exposingSubscriber.onCompleteInvocations, 0);
assertEquals(exposingSubscriber.throwable, t);
assertEquals(exposingSubscriber.throwable.getMessage(),
"a message from me to me");
assertEquals(1, exposingSubscriber.onErrorInvocations);
assertEquals(0, exposingSubscriber.onCompleteInvocations);
assertEquals(t, exposingSubscriber.throwable);
assertEquals("a message from me to me", exposingSubscriber.throwable.getMessage());
furtherCancelsRequestsShouldBeNoOp(s);
assertEquals(exposingSubscriber.onErrorInvocations, 1);
assertEquals(exposingSubscriber.onCompleteInvocations, 0);
assertEquals(1, exposingSubscriber.onErrorInvocations);
assertEquals(0, exposingSubscriber.onCompleteInvocations);
executor.shutdown();
}
@Test(dataProvider = "bufferAndItemSizes")
@ParameterizedTest
@MethodSource("bufferAndItemSizes")
public void onCompleteFromPublisher(int bufferSize,
int numberOfItems)
throws Exception
@ -152,14 +153,14 @@ public class BufferingSubscriberErrorCompleteTest {
Subscription s = exposingSubscriber.subscription;
assertEquals(exposingSubscriber.onErrorInvocations, 0);
assertEquals(exposingSubscriber.onCompleteInvocations, 1);
assertEquals(exposingSubscriber.throwable, null);
assertEquals(0, exposingSubscriber.onErrorInvocations);
assertEquals(1, exposingSubscriber.onCompleteInvocations);
assertEquals(null, exposingSubscriber.throwable);
furtherCancelsRequestsShouldBeNoOp(s);
assertEquals(exposingSubscriber.onErrorInvocations, 0);
assertEquals(exposingSubscriber.onCompleteInvocations, 1);
assertEquals(exposingSubscriber.throwable, null);
assertEquals(0, exposingSubscriber.onErrorInvocations);
assertEquals(1, exposingSubscriber.onCompleteInvocations);
assertEquals(null, exposingSubscriber.throwable);
executor.shutdown();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -38,14 +38,15 @@ import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse.BodySubscriber;
import java.net.http.HttpResponse.BodySubscribers;
import jdk.test.lib.RandomFactory;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.Long.MAX_VALUE;
import static java.lang.Long.min;
import static java.lang.System.out;
import static java.util.concurrent.CompletableFuture.delayedExecutor;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.testng.Assert.*;
import org.junit.jupiter.api.Assertions;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
@ -54,7 +55,7 @@ import static org.testng.Assert.*;
* @key randomness
* @library /test/lib
* @build jdk.test.lib.RandomFactory
* @run testng/othervm/timeout=480 -Djdk.internal.httpclient.debug=true BufferingSubscriberTest
* @run junit/othervm/timeout=480 -Djdk.internal.httpclient.debug=true BufferingSubscriberTest
*/
public class BufferingSubscriberTest {
@ -80,37 +81,41 @@ public class BufferingSubscriberTest {
time = time + ms + "ms";
out.println(what + "\t ["+time+"]\t "+ String.format(fmt,args));
}
@DataProvider(name = "negatives")
public Object[][] negatives() {
public static Object[][] negatives() {
return new Object[][] { { 0 }, { -1 }, { -1000 } };
}
@Test(dataProvider = "negatives", expectedExceptions = IllegalArgumentException.class)
@ParameterizedTest
@MethodSource("negatives")
public void subscriberThrowsIAE(int bufferSize) {
printStamp(START, "subscriberThrowsIAE(%d)", bufferSize);
try {
BodySubscriber<?> bp = BodySubscribers.ofByteArray();
BodySubscribers.buffering(bp, bufferSize);
} finally {
printStamp(END, "subscriberThrowsIAE(%d)", bufferSize);
}
Assertions.assertThrows(IllegalArgumentException.class, () -> {
printStamp(START, "subscriberThrowsIAE(%d)", bufferSize);
try {
BodySubscriber<?> bp = BodySubscribers.ofByteArray();
BodySubscribers.buffering(bp, bufferSize);
} finally {
printStamp(END, "subscriberThrowsIAE(%d)", bufferSize);
}
});
}
@Test(dataProvider = "negatives", expectedExceptions = IllegalArgumentException.class)
@ParameterizedTest
@MethodSource("negatives")
public void handlerThrowsIAE(int bufferSize) {
printStamp(START, "handlerThrowsIAE(%d)", bufferSize);
try {
BodyHandler<?> bp = BodyHandlers.ofByteArray();
BodyHandlers.buffering(bp, bufferSize);
} finally {
printStamp(END, "handlerThrowsIAE(%d)", bufferSize);
}
Assertions.assertThrows(IllegalArgumentException.class, () -> {
printStamp(START, "handlerThrowsIAE(%d)", bufferSize);
try {
BodyHandler<?> bp = BodyHandlers.ofByteArray();
BodyHandlers.buffering(bp, bufferSize);
} finally {
printStamp(END, "handlerThrowsIAE(%d)", bufferSize);
}
});
}
// ---
@DataProvider(name = "config")
public Object[][] config() {
public static Object[][] config() {
return new Object[][] {
// iterations delayMillis numBuffers bufferSize maxBufferSize minBufferSize
{ 1, 0, 1, 1, 2, 1 },
@ -129,7 +134,8 @@ public class BufferingSubscriberTest {
};
}
@Test(dataProvider = "config")
@ParameterizedTest
@MethodSource("config")
public void test(int iterations,
int delayMillis,
int numBuffers,
@ -282,8 +288,8 @@ public class BufferingSubscriberTest {
}
count++;
onNextInvocations++;
assertNotEquals(sz, 0L, "Unexpected empty buffers");
items.stream().forEach(b -> assertEquals(b.position(), 0));
assertNotEquals(0L, sz, "Unexpected empty buffers");
items.stream().forEach(b -> assertEquals(0, b.position()));
assertFalse(noMoreOnNext);
if (sz != bufferSize) {
@ -296,20 +302,20 @@ public class BufferingSubscriberTest {
"Possibly received last buffer: sz=%d, accumulated=%d, total=%d",
sz, totalBytesReceived, totalBytesReceived + sz);
} else {
assertEquals(sz, bufferSize, "Expected to receive exactly bufferSize");
assertEquals(bufferSize, sz, "Expected to receive exactly bufferSize");
}
lastSeenSize = sz;
// Ensure expected contents
for (ByteBuffer b : items) {
while (b.hasRemaining()) {
assertEquals(b.get(), (byte) (index % 100));
assertEquals((byte) (index % 100), b.get());
index++;
}
}
totalBytesReceived += sz;
assertEquals(totalBytesReceived, index);
assertEquals(index, totalBytesReceived);
if (delayMillis > 0 && ((expectedTotalSize - totalBytesReceived) > bufferSize))
delayedExecutor.execute(this::requestMore);
else

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2026, 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
@ -28,7 +28,7 @@
* @bug 8309118
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters
* @run testng/othervm/timeout=40 -Djdk.internal.httpclient.debug=false -Djdk.httpclient.HttpClient.log=trace,errors,headers
* @run junit/othervm/timeout=40 -Djdk.internal.httpclient.debug=false -Djdk.httpclient.HttpClient.log=trace,errors,headers
* CancelledPartialResponseTest
*/
@ -47,11 +47,6 @@ import jdk.internal.net.http.common.HttpHeadersBuilder;
import jdk.internal.net.http.frame.ResetFrame;
import jdk.internal.net.http.http3.Http3Error;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.TestException;
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 javax.net.ssl.SSLSession;
@ -74,16 +69,22 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.fail;
public class CancelledPartialResponseTest {
Http2TestServer http2TestServer;
private static Http2TestServer http2TestServer;
HttpTestServer http3TestServer;
private static HttpTestServer http3TestServer;
// "NoError" urls complete with an exception. "NoError" or "Error" here refers to the error code in the RST_STREAM frame
// and not the outcome of the test.
URI warmup, h2PartialResponseResetNoError, h2PartialResponseResetError, h2FullResponseResetNoError, h2FullResponseResetError;
URI h3PartialResponseStopSending, h3FullResponseStopSending;
private static URI warmup, h2PartialResponseResetNoError, h2PartialResponseResetError, h2FullResponseResetNoError, h2FullResponseResetError;
private static URI h3PartialResponseStopSending, h3FullResponseStopSending;
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
@ -91,8 +92,7 @@ public class CancelledPartialResponseTest {
static PrintStream out = System.out;
// TODO: Investigate further if checking against HTTP/3 Full Response is necessary
@DataProvider(name = "testData")
public Object[][] testData() {
public static Object[][] testData() {
return new Object[][] {
{ HTTP_2, h2PartialResponseResetNoError },
{ HTTP_2, h2PartialResponseResetError }, // Checks RST_STREAM is processed if client sees no END_STREAM
@ -104,7 +104,8 @@ public class CancelledPartialResponseTest {
}
@Test(dataProvider = "testData")
@ParameterizedTest
@MethodSource("testData")
public void test(Version version, URI uri) {
out.printf("\nTesting with Version: %s, URI: %s\n", version, uri.toASCIIString());
err.printf("\nTesting with Version: %s, URI: %s\n", version, uri.toASCIIString());
@ -161,8 +162,8 @@ public class CancelledPartialResponseTest {
}
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
http2TestServer = new Http2TestServer(false, 0);
http3TestServer = HttpTestServer.create(Http3DiscoveryMode.HTTP_3_URI_ONLY, sslContext);
@ -187,8 +188,8 @@ public class CancelledPartialResponseTest {
http3TestServer.start();
}
@AfterTest
public void teardown() {
@AfterAll
public static void teardown() {
http2TestServer.stop();
}
@ -246,10 +247,10 @@ public class CancelledPartialResponseTest {
switch (exchange.getRequestURI().getPath()) {
case "/partialResponse/codeNoError" -> testExchange.addResetToOutputQ(ResetFrame.NO_ERROR);
case "/partialResponse/codeError" -> testExchange.addResetToOutputQ(ResetFrame.PROTOCOL_ERROR);
default -> throw new TestException("Invalid Request Path");
default -> fail("Invalid Request Path");
}
} else {
throw new TestException("Wrong Exchange type used");
fail("Wrong Exchange type used");
}
}
}
@ -268,10 +269,10 @@ public class CancelledPartialResponseTest {
switch (exchange.getRequestURI().getPath()) {
case "/fullResponse/codeNoError" -> testExchange.addResetToOutputQ(ResetFrame.NO_ERROR);
case "/fullResponse/codeError" -> testExchange.addResetToOutputQ(ResetFrame.PROTOCOL_ERROR);
default -> throw new TestException("Invalid Request Path");
default -> fail("Invalid Request Path");
}
} else {
throw new TestException("Wrong Exchange type used");
fail("Wrong Exchange type used");
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2026, 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
@ -25,10 +25,6 @@ import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.internal.net.http.common.OperationTrackers.Tracker;
import jdk.test.lib.RandomFactory;
import jdk.test.lib.net.SimpleSSLContext;
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;
@ -57,15 +53,20 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.ALT_SVC;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext
* @compile ReferenceTracker.java
* @run testng/othervm -Djdk.internal.httpclient.debug=true CancelledResponse2
* @run junit/othervm -Djdk.internal.httpclient.debug=true CancelledResponse2
*/
// -Djdk.internal.httpclient.debug=true
public class CancelledResponse2 implements HttpServerAdapters {
@ -74,17 +75,16 @@ public class CancelledResponse2 implements HttpServerAdapters {
private static final Random RANDOM = RandomFactory.getRandom();
private static final int MAX_CLIENT_DELAY = 160;
HttpTestServer h2TestServer;
URI h2TestServerURI;
URI h2h3TestServerURI;
URI h2h3HeadTestServerURI;
URI h3TestServerURI;
HttpTestServer h2h3TestServer;
HttpTestServer h3TestServer;
private static HttpTestServer h2TestServer;
private static URI h2TestServerURI;
private static URI h2h3TestServerURI;
private static URI h2h3HeadTestServerURI;
private static URI h3TestServerURI;
private static HttpTestServer h2h3TestServer;
private static HttpTestServer h3TestServer;
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
@DataProvider(name = "versions")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][]{
{ HTTP_2, null, h2TestServerURI },
{ HTTP_3, null, h2h3TestServerURI },
@ -101,7 +101,8 @@ public class CancelledResponse2 implements HttpServerAdapters {
out.println("Unexpected exception: " + x);
}
}
@Test(dataProvider = "versions")
@ParameterizedTest
@MethodSource("positive")
public void test(Version version, Http3DiscoveryMode config, URI uri) throws Exception {
for (int i = 0; i < 5; i++) {
HttpClient httpClient = newClientBuilderForH3().sslContext(sslContext).version(version).build();
@ -147,11 +148,11 @@ public class CancelledResponse2 implements HttpServerAdapters {
.HEAD()
.build();
var resp = client.send(request, HttpResponse.BodyHandlers.discarding());
assertEquals(resp.statusCode(), 200);
assertEquals(200, resp.statusCode());
}
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
h2TestServer = HttpTestServer.create(HTTP_2, sslContext);
h2TestServer.addHandler(new CancelledResponseHandler(), "/h2");
h2TestServerURI = URI.create("https://" + h2TestServer.serverAuthority() + "/h2");
@ -172,8 +173,8 @@ public class CancelledResponse2 implements HttpServerAdapters {
h3TestServer.start();
}
@AfterTest
public void teardown() {
@AfterAll
public static void teardown() {
h2TestServer.stop();
h2h3TestServer.stop();
h3TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -29,7 +29,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* jdk.httpclient.test.lib.common.TestServerConfigurator
* @run testng/othervm
* @run junit/othervm
* -Djdk.internal.httpclient.debug=true
* ConcurrentResponses
*/
@ -75,29 +75,30 @@ import jdk.httpclient.test.lib.http2.Http2TestServer;
import jdk.httpclient.test.lib.http2.Http2TestExchange;
import jdk.httpclient.test.lib.http2.Http2Handler;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.net.http.HttpResponse.BodyHandlers.discarding;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ConcurrentResponses {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpsServer httpsTestServer; // HTTPS/1.1
Http2TestServer http2TestServer; // HTTP/2 ( h2c )
Http2TestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer https3TestServer;
String httpFixedURI, httpsFixedURI, httpChunkedURI, httpsChunkedURI;
String http2FixedURI, https2FixedURI, http2VariableURI, https2VariableURI;
String https3FixedURI, https3VariableURI;
private static HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpsServer httpsTestServer; // HTTPS/1.1
private static Http2TestServer http2TestServer; // HTTP/2 ( h2c )
private static Http2TestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer https3TestServer;
private static String httpFixedURI, httpsFixedURI, httpChunkedURI, httpsChunkedURI;
private static String http2FixedURI, https2FixedURI, http2VariableURI, https2VariableURI;
private static String https3FixedURI, https3VariableURI;
static final int CONCURRENT_REQUESTS = 13;
static final AtomicInteger IDS = new AtomicInteger();
@ -131,7 +132,7 @@ public class ConcurrentResponses {
*/
static final <T> CompletionStage<HttpResponse<T>>
assert200ResponseCode(HttpResponse<T> response) {
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
return CompletableFuture.completedFuture(response);
}
@ -141,12 +142,11 @@ public class ConcurrentResponses {
*/
static final <T> CompletionStage<HttpResponse<T>>
assertbody(HttpResponse<T> response, T body) {
assertEquals(response.body(), body);
assertEquals(body, response.body());
return CompletableFuture.completedFuture(response);
}
@DataProvider(name = "uris")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ httpFixedURI },
{ httpsFixedURI },
@ -164,7 +164,8 @@ public class ConcurrentResponses {
// The ofString implementation accumulates data, below a certain threshold
// into the byte buffers it is given.
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testAsString(String uri) throws Exception {
int id = IDS.getAndIncrement();
ExecutorService virtualExecutor = Executors.newThreadPerTaskExecutor(Thread.ofVirtual()
@ -204,7 +205,8 @@ public class ConcurrentResponses {
// The custom subscriber aggressively attacks any area, between the limit
// and the capacity, in the byte buffers it is given, by writing 'X' into it.
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testWithCustomSubscriber(String uri) throws Exception {
int id = IDS.getAndIncrement();
ExecutorService virtualExecutor = Executors.newThreadPerTaskExecutor(Thread.ofVirtual()
@ -301,8 +303,8 @@ public class ConcurrentResponses {
+ server.getAddress().getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
httpTestServer = HttpServer.create(sa, 0);
httpTestServer.createContext("/http1/fixed", new Http1FixedHandler());
@ -342,8 +344,8 @@ public class ConcurrentResponses {
https3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop(0);
httpsTestServer.stop(0);
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -25,7 +25,7 @@
* @test
* @summary Expect ConnectException for all non-security related connect errors
* @bug 8204864
* @run testng/othervm -Djdk.net.hosts.file=HostFileDoesNotExist ConnectExceptionTest
* @run junit/othervm -Djdk.net.hosts.file=HostFileDoesNotExist ConnectExceptionTest
*/
import java.io.IOException;
@ -42,11 +42,12 @@ import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ConnectExceptionTest {
@ -64,8 +65,7 @@ public class ConnectExceptionTest {
@Override public String toString() { return "NO_PROXY"; }
};
@DataProvider(name = "uris")
public Object[][] uris() {
public static Object[][] uris() {
return new Object[][]{
{ "http://test.invalid/", NO_PROXY },
{ "https://test.invalid/", NO_PROXY },
@ -74,7 +74,8 @@ public class ConnectExceptionTest {
};
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("uris")
void testSynchronousGET(String uriString, ProxySelector proxy) throws Exception {
out.printf("%n---%ntestSynchronousGET starting uri:%s, proxy:%s%n", uriString, proxy);
HttpClient client = HttpClient.newBuilder().proxy(proxy).build();
@ -90,7 +91,8 @@ public class ConnectExceptionTest {
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("uris")
void testSynchronousPOST(String uriString, ProxySelector proxy) throws Exception {
out.printf("%n---%ntestSynchronousPOST starting uri:%s, proxy:%s%n", uriString, proxy);
HttpClient client = HttpClient.newBuilder().proxy(proxy).build();
@ -108,7 +110,8 @@ public class ConnectExceptionTest {
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("uris")
void testAsynchronousGET(String uriString, ProxySelector proxy) throws Exception {
out.printf("%n---%ntestAsynchronousGET starting uri:%s, proxy:%s%n", uriString, proxy);
HttpClient client = HttpClient.newBuilder().proxy(proxy).build();
@ -129,7 +132,8 @@ public class ConnectExceptionTest {
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("uris")
void testAsynchronousPOST(String uriString, ProxySelector proxy) throws Exception {
out.printf("%n---%ntestAsynchronousPOST starting uri:%s, proxy:%s%n", uriString, proxy);
HttpClient client = HttpClient.newBuilder().proxy(proxy).build();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -23,7 +23,9 @@
import java.net.http.HttpClient.Version;
import java.time.Duration;
import org.testng.annotations.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
@ -31,14 +33,15 @@ import org.testng.annotations.Test;
* @bug 8208391
* @library /test/lib
* @build AbstractConnectTimeoutHandshake
* @run testng/othervm ConnectTimeoutHandshakeAsync
* @run junit/othervm ConnectTimeoutHandshakeAsync
*/
public class ConnectTimeoutHandshakeAsync
extends AbstractConnectTimeoutHandshake
{
@Test(dataProvider = "variants")
@Override
@ParameterizedTest
@MethodSource("variants")
public void timeoutAsync(Version requestVersion,
String method,
Duration connectTimeout,

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -23,7 +23,9 @@
import java.net.http.HttpClient.Version;
import java.time.Duration;
import org.testng.annotations.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
@ -31,14 +33,15 @@ import org.testng.annotations.Test;
* @bug 8208391
* @library /test/lib
* @build AbstractConnectTimeoutHandshake
* @run testng/othervm ConnectTimeoutHandshakeSync
* @run junit/othervm ConnectTimeoutHandshakeSync
*/
public class ConnectTimeoutHandshakeSync
extends AbstractConnectTimeoutHandshake
{
@Test(dataProvider = "variants")
@Override
@ParameterizedTest
@MethodSource("variants")
public void timeoutSync(Version requestVersion,
String method,
Duration connectTimeout,

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2022, 2026, 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
@ -30,7 +30,7 @@
* @build jdk.test.lib.net.SimpleSSLContext
* jdk.httpclient.test.lib.common.HttpServerAdapters
* @bug 8283544 8358942
* @run testng/othervm
* @run junit/othervm
* -Djdk.httpclient.allowRestrictedHeaders=content-length
* -Djdk.internal.httpclient.debug=true
* ContentLengthHeaderTest
@ -39,10 +39,6 @@
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.io.InputStream;
@ -59,19 +55,22 @@ import java.util.Optional;
import javax.net.ssl.SSLContext;
import jdk.test.lib.net.URIBuilder;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ContentLengthHeaderTest implements HttpServerAdapters {
final String NO_BODY_PATH = "/no_body";
final String BODY_PATH = "/body";
static final String NO_BODY_PATH = "/no_body";
static final String BODY_PATH = "/body";
static HttpTestServer testContentLengthServerH1;
static HttpTestServer testContentLengthServerH2;
@ -79,13 +78,13 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
static PrintStream testLog = System.err;
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpClient hc;
URI testContentLengthURIH1;
URI testContentLengthURIH2;
URI testContentLengthURIH3;
private static HttpClient hc;
private static URI testContentLengthURIH1;
private static URI testContentLengthURIH2;
private static URI testContentLengthURIH3;
@BeforeTest
public void setup() throws IOException, URISyntaxException, InterruptedException {
@BeforeAll
public static void setup() throws IOException, URISyntaxException, InterruptedException {
testContentLengthServerH1 = HttpTestServer.create(HTTP_1_1);
testContentLengthServerH2 = HttpTestServer.create(HTTP_2, sslContext);
testContentLengthServerH3 = HttpTestServer.create(HTTP_3, sslContext);
@ -128,7 +127,7 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
+ testContentLengthServerH3.getH3AltService().get().getAddress());
testLog.println("Request URI for Client: " + testContentLengthURIH3);
hc = newClientBuilderForH3()
hc = HttpServerAdapters.createClientBuilderForH3()
.proxy(HttpClient.Builder.NO_PROXY)
.sslContext(sslContext)
.build();
@ -139,12 +138,12 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.build();
// populate alt-service registry
var resp = hc.send(firstReq, BodyHandlers.ofString());
assertEquals(resp.statusCode(), 200);
assertEquals(200, resp.statusCode());
testLog.println("**** setup done ****");
}
@AfterTest
public void teardown() {
@AfterAll
public static void teardown() {
testLog.println("**** tearing down ****");
if (testContentLengthServerH1 != null)
testContentLengthServerH1.stop();
@ -154,8 +153,7 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
testContentLengthServerH3.stop();
}
@DataProvider(name = "bodies")
Object[][] bodies() {
static Object[][] bodies() {
return new Object[][]{
{HTTP_1_1, URI.create(testContentLengthURIH1 + BODY_PATH)},
{HTTP_2, URI.create(testContentLengthURIH2 + BODY_PATH)},
@ -163,15 +161,13 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
};
}
@DataProvider(name = "h1body")
Object[][] h1body() {
static Object[][] h1body() {
return new Object[][]{
{HTTP_1_1, URI.create(testContentLengthURIH1 + BODY_PATH)}
};
}
@DataProvider(name = "nobodies")
Object[][] nobodies() {
static Object[][] nobodies() {
return new Object[][]{
{HTTP_1_1, URI.create(testContentLengthURIH1 + NO_BODY_PATH)},
{HTTP_2, URI.create(testContentLengthURIH2 + NO_BODY_PATH)},
@ -179,8 +175,9 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
};
}
@Test(dataProvider = "nobodies")
@ParameterizedTest
// A GET request with no request body should have no Content-length header
@MethodSource("nobodies")
public void getWithNoBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking GET with no request body");
HttpRequest req = HttpRequest.newBuilder()
@ -189,12 +186,13 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "nobodies")
@ParameterizedTest
// A GET request with empty request body should have no Content-length header
@MethodSource("nobodies")
public void getWithEmptyBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking GET with no request body");
HttpRequest req = HttpRequest.newBuilder()
@ -203,12 +201,13 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "bodies")
@ParameterizedTest
// A GET request with empty request body and explicitly added Content-length header
@MethodSource("bodies")
public void getWithZeroContentLength(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking GET with no request body");
HttpRequest req = HttpRequest.newBuilder()
@ -218,13 +217,14 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "bodies")
@ParameterizedTest
// A GET request with a request body should have a Content-length header
// in HTTP/1.1
@MethodSource("bodies")
public void getWithBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking GET with request body");
HttpRequest req = HttpRequest.newBuilder()
@ -233,12 +233,13 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "nobodies")
@ParameterizedTest
// A DELETE request with no request body should have no Content-length header
@MethodSource("nobodies")
public void deleteWithNoBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking DELETE with no request body");
HttpRequest req = HttpRequest.newBuilder()
@ -247,12 +248,13 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "nobodies")
@ParameterizedTest
// A DELETE request with empty request body should have no Content-length header
@MethodSource("nobodies")
public void deleteWithEmptyBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking DELETE with no request body");
HttpRequest req = HttpRequest.newBuilder()
@ -261,13 +263,14 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "bodies")
@ParameterizedTest
// A DELETE request with a request body should have a Content-length header
// in HTTP/1.1
@MethodSource("bodies")
public void deleteWithBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking DELETE with request body");
HttpRequest req = HttpRequest.newBuilder()
@ -276,12 +279,13 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "nobodies")
@ParameterizedTest
// A HEAD request with no request body should have no Content-length header
@MethodSource("nobodies")
public void headWithNoBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking HEAD with no request body");
HttpRequest req = HttpRequest.newBuilder()
@ -290,12 +294,13 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "nobodies")
@ParameterizedTest
// A HEAD request with empty request body should have no Content-length header
@MethodSource("nobodies")
public void headWithEmptyBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking HEAD with no request body");
HttpRequest req = HttpRequest.newBuilder()
@ -304,13 +309,14 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "bodies")
@ParameterizedTest
// A HEAD request with a request body should have a Content-length header
// in HTTP/1.1
@MethodSource("bodies")
public void headWithBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking HEAD with request body");
HttpRequest req = HttpRequest.newBuilder()
@ -321,13 +327,14 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
// Sending this request invokes sendResponseHeaders which emits a warning about including
// a Content-length header with a HEAD request
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "h1body")
@ParameterizedTest
// A POST request with empty request body should have a Content-length header
// in HTTP/1.1
@MethodSource("h1body")
public void postWithEmptyBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking POST with request body");
HttpRequest req = HttpRequest.newBuilder()
@ -336,13 +343,14 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "bodies")
@ParameterizedTest
// A POST request with a request body should have a Content-length header
// in HTTP/1.1
@MethodSource("bodies")
public void postWithBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking POST with request body");
HttpRequest req = HttpRequest.newBuilder()
@ -351,13 +359,14 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "h1body")
@ParameterizedTest
// A PUT request with empty request body should have a Content-length header
// in HTTP/1.1
@MethodSource("h1body")
public void putWithEmptyBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking PUT with request body");
HttpRequest req = HttpRequest.newBuilder()
@ -366,13 +375,14 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
@Test(dataProvider = "bodies")
@ParameterizedTest
// A PUT request with a request body should have a Content-length header
// in HTTP/1.1
@MethodSource("bodies")
public void putWithBody(Version version, URI uri) throws IOException, InterruptedException {
testLog.println(version + " Checking PUT with request body");
HttpRequest req = HttpRequest.newBuilder()
@ -381,8 +391,8 @@ public class ContentLengthHeaderTest implements HttpServerAdapters {
.uri(uri)
.build();
HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));
assertEquals(resp.statusCode(), 200, resp.body());
assertEquals(resp.version(), version);
assertEquals(200, resp.statusCode(), resp.body());
assertEquals(version, resp.version());
}
public static void handleResponse(long expected, HttpTestExchange ex, String body, int rCode) throws IOException {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -27,17 +27,13 @@
* @summary Test for multiple vs single cookie header for HTTP/2 vs HTTP/1.1
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm
* @run junit/othervm
* -Djdk.tls.acknowledgeCloseNotify=true
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* CookieHeaderTest
*/
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLContext;
@ -78,26 +74,31 @@ import static java.net.http.HttpClient.Version.HTTP_2;
import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class CookieHeaderTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 6 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
DummyServer httpDummyServer;
DummyServer httpsDummyServer;
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
String httpDummy;
String httpsDummy;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 6 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static DummyServer httpDummyServer;
private static DummyServer httpsDummyServer;
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
private static String httpDummy;
private static String httpsDummy;
static final String MESSAGE = "Basic CookieHeaderTest message body";
static final int ITERATIONS = 3;
@ -110,8 +111,7 @@ public class CookieHeaderTest implements HttpServerAdapters {
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
}
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ httpURI, HTTP_1_1 },
{ httpsURI, HTTP_1_1 },
@ -129,7 +129,8 @@ public class CookieHeaderTest implements HttpServerAdapters {
static final AtomicLong requestCounter = new AtomicLong();
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void test(String uriString, HttpClient.Version version) throws Exception {
out.printf("%n---- starting (%s) ----%n", uriString);
ConcurrentHashMap<String, List<String>> cookieHeaders
@ -169,14 +170,15 @@ public class CookieHeaderTest implements HttpServerAdapters {
+ ", version=" + response.version());
out.println(" Got body Path: " + response.body());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), MESSAGE);
assertEquals(response.headers().allValues("X-Request-Cookie"),
cookies.stream()
.filter(s -> !s.startsWith("LOC"))
.collect(Collectors.toList()));
assertEquals(200, response.statusCode());
assertEquals(MESSAGE, response.body());
List<String> expectedCookieList = cookies.stream()
.filter(s -> !s.startsWith("LOC")).toList();
List<String> actualCookieList = response.headers()
.allValues("X-Request-Cookie");
assertEquals(expectedCookieList, actualCookieList);
if (version == HTTP_3 && i > 0) {
assertEquals(response.version(), HTTP_3);
assertEquals(HTTP_3, response.version());
}
requestBuilder = HttpRequest.newBuilder(uri)
.header("X-uuid", "uuid-" + requestCounter.incrementAndGet());
@ -192,8 +194,8 @@ public class CookieHeaderTest implements HttpServerAdapters {
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpTestServer.create(HTTP_1_1);
httpTestServer.addHandler(new CookieValidationHandler(), "/http1/cookie/");
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/cookie/retry";
@ -228,8 +230,8 @@ public class CookieHeaderTest implements HttpServerAdapters {
httpsDummyServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop();
httpsTestServer.stop();
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -26,7 +26,7 @@
* @summary Checks correct handling of Publishers that call onComplete without demand
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm CustomRequestPublisher
* @run junit/othervm CustomRequestPublisher
*/
import java.net.InetAddress;
@ -51,10 +51,6 @@ import java.net.http.HttpResponse;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
@ -62,27 +58,31 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class CustomRequestPublisher implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
Supplier<BodyPublisher> fixedSupplier = () -> new FixedLengthBodyPublisher();
Supplier<BodyPublisher> unknownSupplier = () -> new UnknownLengthBodyPublisher();
@ -114,12 +114,12 @@ public class CustomRequestPublisher implements HttpServerAdapters {
/** Asserts HTTP Version, and SSLSession presence when applicable. */
static void assertVersionAndSession(int step, HttpResponse response, String uri) {
if (uri.contains("http2") || uri.contains("https2")) {
assertEquals(response.version(), HTTP_2);
assertEquals(HTTP_2, response.version());
} else if (uri.contains("http1") || uri.contains("https1")) {
assertEquals(response.version(), HTTP_1_1);
assertEquals(HTTP_1_1, response.version());
} else if (uri.contains("http3")) {
if (step == 0) assertNotEquals(response.version(), HTTP_1_1);
else assertEquals(response.version(), HTTP_3,
if (step == 0) assertNotEquals(HTTP_1_1, response.version());
else assertEquals(HTTP_3, response.version(),
"unexpected response version on step " + step);
} else {
fail("Unknown HTTP version in test for: " + uri);
@ -160,7 +160,8 @@ public class CustomRequestPublisher implements HttpServerAdapters {
return builder;
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
void test(String uri, Supplier<BodyPublisher> bpSupplier, boolean sameClient)
throws Exception
{
@ -180,13 +181,14 @@ public class CustomRequestPublisher implements HttpServerAdapters {
out.println("Got body: " + resp.body());
assertTrue(resp.statusCode() == 200,
"Expected 200, got:" + resp.statusCode());
assertEquals(resp.body(), bodyPublisher.bodyAsString());
assertEquals(bodyPublisher.bodyAsString(), resp.body());
assertVersionAndSession(i, resp, uri);
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
void testAsync(String uri, Supplier<BodyPublisher> bpSupplier, boolean sameClient)
throws Exception
{
@ -207,7 +209,7 @@ public class CustomRequestPublisher implements HttpServerAdapters {
out.println("Got body: " + resp.body());
assertTrue(resp.statusCode() == 200,
"Expected 200, got:" + resp.statusCode());
assertEquals(resp.body(), bodyPublisher.bodyAsString());
assertEquals(bodyPublisher.bodyAsString(), resp.body());
assertVersionAndSession(0, resp, uri);
}
@ -337,8 +339,8 @@ public class CustomRequestPublisher implements HttpServerAdapters {
}
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
httpTestServer = HttpTestServer.create(HTTP_1_1);
httpTestServer.addHandler(new HttpTestEchoHandler(), "/http1/echo");
@ -367,8 +369,8 @@ public class CustomRequestPublisher implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop();
httpsTestServer.stop();
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -27,7 +27,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.http2.Http2TestServer
* jdk.httpclient.test.lib.common.TestServerConfigurator
* @run testng/othervm CustomResponseSubscriber
* @run junit/othervm CustomResponseSubscriber
*/
import java.io.IOException;
@ -59,37 +59,37 @@ import jdk.httpclient.test.lib.http2.Http2Handler;
import javax.net.ssl.SSLContext;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class CustomResponseSubscriber {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpsServer httpsTestServer; // HTTPS/1.1
Http2TestServer http2TestServer; // HTTP/2 ( h2c )
Http2TestServer https2TestServer; // HTTP/2 ( h2 )
String httpURI_fixed;
String httpURI_chunk;
String httpsURI_fixed;
String httpsURI_chunk;
String http2URI_fixed;
String http2URI_chunk;
String https2URI_fixed;
String https2URI_chunk;
private static HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpsServer httpsTestServer; // HTTPS/1.1
private static Http2TestServer http2TestServer; // HTTP/2 ( h2c )
private static Http2TestServer https2TestServer; // HTTP/2 ( h2 )
private static String httpURI_fixed;
private static String httpURI_chunk;
private static String httpsURI_fixed;
private static String httpsURI_chunk;
private static String http2URI_fixed;
private static String http2URI_chunk;
private static String https2URI_fixed;
private static String https2URI_chunk;
static final int ITERATION_COUNT = 10;
// a shared executor helps reduce the amount of threads created by the test
static final Executor executor = Executors.newCachedThreadPool();
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ httpURI_fixed, false },
{ httpURI_chunk, false },
@ -118,7 +118,8 @@ public class CustomResponseSubscriber {
.build();
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsString(String uri, boolean sameClient) throws Exception {
HttpClient client = null;
for (int i=0; i< ITERATION_COUNT; i++) {
@ -130,14 +131,14 @@ public class CustomResponseSubscriber {
BodyHandler<String> handler = new CRSBodyHandler();
HttpResponse<String> response = client.send(req, handler);
String body = response.body();
assertEquals(body, "");
assertEquals("", body);
}
}
static class CRSBodyHandler implements BodyHandler<String> {
@Override
public BodySubscriber<String> apply(HttpResponse.ResponseInfo rinfo) {
assertEquals(rinfo.statusCode(), 200);
assertEquals(200, rinfo.statusCode());
return new CRSBodySubscriber();
}
}
@ -185,8 +186,8 @@ public class CustomResponseSubscriber {
+ server.getAddress().getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
// HTTP/1.1
HttpHandler h1_fixedLengthHandler = new HTTP1_FixedLengthHandler();
HttpHandler h1_chunkHandler = new HTTP1_ChunkedHandler();
@ -226,8 +227,8 @@ public class CustomResponseSubscriber {
https2TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop(0);
httpsTestServer.stop(0);
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -29,7 +29,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters jdk.test.lib.net.SimpleSSLContext
* DependentActionsTest
* @run testng/othervm -Djdk.internal.httpclient.debug=true
* @run junit/othervm -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.quic.maxPtoBackoff=9
* DependentActionsTest
*/
@ -39,12 +39,6 @@ import java.io.InputStreamReader;
import java.lang.StackWalker.StackFrame;
import jdk.httpclient.test.lib.http3.Http3TestServer;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.SkipException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.net.ssl.SSLContext;
import java.io.IOException;
@ -89,28 +83,35 @@ import static java.net.http.HttpClient.Version.HTTP_2;
import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.util.stream.Collectors.toList;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class DependentActionsTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI_fixed;
String httpURI_chunk;
String httpsURI_fixed;
String httpsURI_chunk;
String http2URI_fixed;
String http2URI_chunk;
String https2URI_fixed;
String https2URI_chunk;
String http3URI_fixed;
String http3URI_chunk;
String http3URI_head;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI_fixed;
private static String httpURI_chunk;
private static String httpsURI_fixed;
private static String httpsURI_chunk;
private static String http2URI_fixed;
private static String http2URI_chunk;
private static String https2URI_fixed;
private static String https2URI_chunk;
private static String http3URI_fixed;
private static String http3URI_chunk;
private static String http3URI_head;
static final StackWalker WALKER =
StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
@ -132,7 +133,7 @@ public class DependentActionsTest implements HttpServerAdapters {
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
}
private volatile HttpClient sharedClient;
private static volatile HttpClient sharedClient;
static class TestExecutor implements Executor {
final AtomicLong tasks = new AtomicLong();
@ -158,7 +159,7 @@ public class DependentActionsTest implements HttpServerAdapters {
}
}
@AfterClass
@AfterAll
static final void printFailedTests() {
out.println("\n=========================");
try {
@ -179,7 +180,7 @@ public class DependentActionsTest implements HttpServerAdapters {
}
}
private String[] uris() {
private static String[] uris() {
return new String[] {
httpURI_fixed,
httpURI_chunk,
@ -206,8 +207,7 @@ public class DependentActionsTest implements HttpServerAdapters {
}
}
@DataProvider(name = "noStalls")
public Object[][] noThrows() {
public static Object[][] noThrows() {
String[] uris = uris();
Object[][] result = new Object[uris.length * 2][];
int i = 0;
@ -220,8 +220,7 @@ public class DependentActionsTest implements HttpServerAdapters {
return result;
}
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
String[] uris = uris();
Object[][] result = new Object[uris.length * 2][];
int i = 0;
@ -237,20 +236,21 @@ public class DependentActionsTest implements HttpServerAdapters {
return result;
}
private HttpClient makeNewClient() {
private static HttpClient makeNewClient() {
clientCount.incrementAndGet();
return newClientBuilderForH3()
return HttpServerAdapters.createClientBuilderForH3()
.proxy(Builder.NO_PROXY)
.executor(executor)
.sslContext(sslContext)
.build();
}
HttpClient newHttpClient(boolean share) {
private static final Object zis = new Object();
static HttpClient newHttpClient(boolean share) {
if (!share) return makeNewClient();
HttpClient shared = sharedClient;
if (shared != null) return shared;
synchronized (this) {
synchronized (zis) {
shared = sharedClient;
if (shared == null) {
shared = sharedClient = makeNewClient();
@ -259,7 +259,8 @@ public class DependentActionsTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "noStalls")
@ParameterizedTest
@MethodSource("noThrows")
public void testNoStalls(String uri, boolean sameClient)
throws Exception {
HttpClient client = null;
@ -279,11 +280,12 @@ public class DependentActionsTest implements HttpServerAdapters {
BodyHandlers.ofString());
HttpResponse<String> response = client.send(req, handler);
String body = response.body();
assertEquals(URI.create(body).getPath(), URI.create(uri).getPath());
assertEquals(URI.create(uri).getPath(), URI.create(body).getPath());
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsStringAsync(String uri,
boolean sameClient,
Supplier<Staller> s)
@ -296,7 +298,8 @@ public class DependentActionsTest implements HttpServerAdapters {
this::finish, this::extractString, staller);
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsLinesAsync(String uri,
boolean sameClient,
Supplier<Staller> s)
@ -309,7 +312,8 @@ public class DependentActionsTest implements HttpServerAdapters {
this::finish, this::extractStream, staller);
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsInputStreamAsync(String uri,
boolean sameClient,
Supplier<Staller> s)
@ -329,11 +333,8 @@ public class DependentActionsTest implements HttpServerAdapters {
Staller staller)
throws Exception
{
if (errorRef.get() != null) {
SkipException sk = new SkipException("skipping due to previous failure: " + name);
sk.setStackTrace(new StackTraceElement[0]);
throw sk;
}
Assumptions.assumeTrue(errorRef.get() == null,
"skipping due to previous failure: " + name);
out.printf("%n%s%s%n", now(), name);
try {
testDependent(uri, sameClient, handlers, finisher, extractor, staller);
@ -376,7 +377,7 @@ public class DependentActionsTest implements HttpServerAdapters {
// it's possible that the first request still went through HTTP/2
// if the config was HTTP3_ANY. Retry it - the next time we should
// have HTTP/3
assertEquals(resp.version(), HTTP_3,
assertEquals(HTTP_3, resp.version(),
"expected second request to go through HTTP/3 (serverConfig="
+ http3TestServer.h3DiscoveryConfig() + ")");
}
@ -479,10 +480,10 @@ public class DependentActionsTest implements HttpServerAdapters {
throw new RuntimeException("Test failed in "
+ w + ": " + response, error);
}
assertEquals(result, List.of(response.request().uri().getPath()));
assertEquals(List.of(response.request().uri().getPath()), result);
var uriStr = response.request().uri().toString();
if (HTTP_3 != version(uriStr) || http3TestServer.h3DiscoveryConfig() != Http3DiscoveryMode.ANY) {
assertEquals(response.version(), version(uriStr), uriStr);
assertEquals(version(uriStr), response.version(), uriStr);
}
return response;
} finally {
@ -619,7 +620,7 @@ public class DependentActionsTest implements HttpServerAdapters {
return null;
}
HttpRequest.Builder newRequestBuilder(String uri) {
static HttpRequest.Builder newRequestBuilder(String uri) {
var builder = HttpRequest.newBuilder(URI.create(uri));
if (version(uri) == HTTP_3) {
builder.version(HTTP_3);
@ -628,21 +629,21 @@ public class DependentActionsTest implements HttpServerAdapters {
return builder;
}
HttpResponse<String> headRequest(HttpClient client)
static HttpResponse<String> headRequest(HttpClient client)
throws IOException, InterruptedException
{
var request = newRequestBuilder(http3URI_head)
.HEAD().version(HTTP_2).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), HTTP_2);
assertEquals(200, response.statusCode());
assertEquals(HTTP_2, response.version());
System.out.println("\n--- HEAD request succeeded ----\n");
System.err.println("\n--- HEAD request succeeded ----\n");
return response;
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
// HTTP/1.1
HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler();
HttpTestHandler h1_chunkHandler = new HTTP_ChunkedHandler();
@ -703,8 +704,8 @@ public class DependentActionsTest implements HttpServerAdapters {
headRequest(newHttpClient(true));
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
sharedClient = null;
httpTestServer.stop();
httpsTestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -29,7 +29,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters jdk.test.lib.net.SimpleSSLContext
* DependentPromiseActionsTest
* @run testng/othervm -Djdk.internal.httpclient.debug=true DependentPromiseActionsTest
* @run junit/othervm -Djdk.internal.httpclient.debug=true DependentPromiseActionsTest
*/
import java.io.BufferedReader;
@ -37,11 +37,6 @@ import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.lang.StackWalker.StackFrame;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.net.ssl.SSLContext;
import java.io.IOException;
@ -93,21 +88,26 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class DependentPromiseActionsTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String http2URI_fixed;
String http2URI_chunk;
String https2URI_fixed;
String https2URI_chunk;
String http3URI_fixed;
String http3URI_chunk;
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String http2URI_fixed;
private static String http2URI_chunk;
private static String https2URI_fixed;
private static String https2URI_chunk;
private static String http3URI_fixed;
private static String http3URI_chunk;
static final StackWalker WALKER =
StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
@ -129,7 +129,7 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
}
private volatile HttpClient sharedClient;
private static volatile HttpClient sharedClient;
static class TestExecutor implements Executor {
final AtomicLong tasks = new AtomicLong();
@ -155,7 +155,7 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
}
}
@AfterClass
@AfterAll
static final void printFailedTests() {
out.println("\n=========================");
try {
@ -176,7 +176,7 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
}
}
private String[] uris() {
private static String[] uris() {
return new String[] {
http3URI_fixed,
http3URI_chunk,
@ -201,8 +201,7 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
}
}
@DataProvider(name = "noStalls")
public Object[][] noThrows() {
public static Object[][] noThrows() {
String[] uris = uris();
Object[][] result = new Object[uris.length * 2][];
int i = 0;
@ -215,8 +214,7 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
return result;
}
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
String[] uris = uris();
Object[][] result = new Object[uris.length * 2][];
int i = 0;
@ -271,7 +269,8 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
return builder.build();
}
@Test(dataProvider = "noStalls")
@ParameterizedTest
@MethodSource("noThrows")
public void testNoStalls(String rootUri, boolean sameClient)
throws Exception {
if (!FAILURES.isEmpty()) return;
@ -287,7 +286,7 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
HttpRequest req = request(uri);
BodyHandler<Stream<String>> handler =
new StallingBodyHandler((w) -> {},
new StallingBodyHandler<>((w) -> {},
BodyHandlers.ofLines());
Map<HttpRequest, CompletableFuture<HttpResponse<Stream<String>>>> pushPromises =
new ConcurrentHashMap<>();
@ -304,13 +303,13 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
HttpResponse<Stream<String>> response =
client.sendAsync(req, BodyHandlers.ofLines(), pushHandler).get();
String body = response.body().collect(Collectors.joining("|"));
assertEquals(URI.create(body).getPath(), URI.create(uri).getPath());
assertEquals(URI.create(uri).getPath(), URI.create(body).getPath());
for (HttpRequest promised : pushPromises.keySet()) {
out.printf("%s Received promise: %s%n\tresponse: %s%n",
now(), promised, pushPromises.get(promised).get());
String promisedBody = pushPromises.get(promised).get().body()
.collect(Collectors.joining("|"));
assertEquals(promisedBody, promised.uri().toASCIIString());
assertEquals(promised.uri().toASCIIString(), promisedBody);
}
assertEquals(3, pushPromises.size());
}
@ -321,8 +320,9 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
public void testAsStringAsync(String uri,
@ParameterizedTest
@MethodSource("variants")
void testAsStringAsync(String uri,
boolean sameClient,
Supplier<Staller> stallers)
throws Exception
@ -334,8 +334,9 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
SubscriberType.EAGER);
}
@Test(dataProvider = "variants")
public void testAsLinesAsync(String uri,
@ParameterizedTest
@MethodSource("variants")
void testAsLinesAsync(String uri,
boolean sameClient,
Supplier<Staller> stallers)
throws Exception
@ -347,8 +348,9 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
SubscriberType.LAZZY);
}
@Test(dataProvider = "variants")
public void testAsInputStreamAsync(String uri,
@ParameterizedTest
@MethodSource("variants")
void testAsInputStreamAsync(String uri,
boolean sameClient,
Supplier<Staller> stallers)
throws Exception
@ -362,7 +364,7 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
private <T,U> void testDependent(String name, String uri, boolean sameClient,
Supplier<BodyHandler<T>> handlers,
Finisher finisher,
Finisher<T> finisher,
Extractor<T> extractor,
Supplier<Staller> stallers,
SubscriberType subscriberType)
@ -384,7 +386,7 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
private <T,U> void testDependent(String rootUri, boolean sameClient,
Supplier<BodyHandler<T>> handlers,
Finisher finisher,
Finisher<T> finisher,
Extractor<T> extractor,
Supplier<Staller> stallers,
SubscriberType subscriberType)
@ -424,7 +426,7 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
enum Where {
ON_PUSH_PROMISE, BODY_HANDLER, ON_SUBSCRIBE, ON_NEXT, ON_COMPLETE, ON_ERROR, GET_BODY, BODY_CF;
public Consumer<Where> select(Consumer<Where> consumer) {
return new Consumer<Where>() {
return new Consumer<>() {
@Override
public void accept(Where where) {
if (Where.this == where) {
@ -475,10 +477,10 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
staller.acquire();
assert staller.willStall();
try {
BodyHandler handler = new StallingBodyHandler<>(
BodyHandler<T> handler = new StallingBodyHandler<>(
where.select(staller), handlers.get());
CompletableFuture<HttpResponse<T>> cf = acceptor.apply(handler);
Tuple<T> tuple = new Tuple(failed, cf, staller);
Tuple<T> tuple = new Tuple<>(failed, cf, staller);
promiseMap.putIfAbsent(pushPromiseRequest, tuple);
CompletableFuture<?> done = cf.whenComplete(
(r, t) -> checkThreadAndStack(thread, failed, r, t));
@ -567,7 +569,7 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
throw new RuntimeException("Test failed in "
+ w + ": " + uri, error);
}
assertEquals(result, List.of(response.request().uri().toASCIIString()));
assertEquals(List.of(response.request().uri().toASCIIString()), result);
} finally {
staller.reset();
}
@ -582,10 +584,10 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
for (HttpRequest req : ph.promiseMap.keySet()) {
finish(w, ph.promiseMap.get(req), extractor);
}
assertEquals(ph.promiseMap.size(), 3,
assertEquals(3, ph.promiseMap.size(),
"Expected 3 push promises for " + w + " in "
+ response.request().uri());
assertEquals(result, List.of(response.request().uri().toASCIIString()));
assertEquals(List.of(response.request().uri().toASCIIString()), result);
}
@ -699,8 +701,8 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
// HTTP/2
HttpTestHandler fixedLengthHandler = new HTTP_FixedLengthHandler();
HttpTestHandler chunkedHandler = new HTTP_ChunkedHandler();
@ -729,8 +731,8 @@ public class DependentPromiseActionsTest implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
if (sharedClient != null) {
sharedClient.close();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -29,7 +29,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters jdk.test.lib.net.SimpleSSLContext
* EncodedCharsInURI
* @run testng/othervm
* @run junit/othervm
* -Djdk.tls.acknowledgeCloseNotify=true
* -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=headers,errors EncodedCharsInURI
@ -38,11 +38,6 @@
import jdk.httpclient.test.lib.http3.Http3TestServer;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLContext;
@ -83,32 +78,37 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class EncodedCharsInURI implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
DummyServer httpDummyServer; // HTTP/1.1 [ 2 servers ]
DummyServer httpsDummyServer; // HTTPS/1.1
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI_fixed;
String httpURI_chunk;
String httpsURI_fixed;
String httpsURI_chunk;
String http2URI_fixed;
String http2URI_chunk;
String https2URI_fixed;
String https2URI_chunk;
String http3URI_fixed;
String http3URI_chunk;
String http3URI_head;
String httpDummy;
String httpsDummy;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static DummyServer httpDummyServer; // HTTP/1.1 [ 2 servers ]
private static DummyServer httpsDummyServer; // HTTPS/1.1
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI_fixed;
private static String httpURI_chunk;
private static String httpsURI_fixed;
private static String httpsURI_chunk;
private static String http2URI_fixed;
private static String http2URI_chunk;
private static String https2URI_fixed;
private static String https2URI_chunk;
private static String http3URI_fixed;
private static String http3URI_chunk;
private static String http3URI_head;
private static String httpDummy;
private static String httpsDummy;
static final int ITERATION_COUNT = 1;
// a shared executor helps reduce the amount of threads created by the test
@ -126,7 +126,7 @@ public class EncodedCharsInURI implements HttpServerAdapters {
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
}
private volatile HttpClient sharedClient;
private static volatile HttpClient sharedClient;
static class TestExecutor implements Executor {
final AtomicLong tasks = new AtomicLong();
@ -152,7 +152,7 @@ public class EncodedCharsInURI implements HttpServerAdapters {
}
}
@AfterClass
@AfterAll
static final void printFailedTests() {
out.println("\n=========================");
try {
@ -172,7 +172,7 @@ public class EncodedCharsInURI implements HttpServerAdapters {
}
}
private String[] uris() {
private static String[] uris() {
return new String[] {
httpDummy,
httpsDummy,
@ -189,8 +189,7 @@ public class EncodedCharsInURI implements HttpServerAdapters {
};
}
@DataProvider(name = "noThrows")
public Object[][] noThrows() {
public static Object[][] noThrows() {
String[] uris = uris();
Object[][] result = new Object[uris.length * 2][];
//Object[][] result = new Object[uris.length][];
@ -216,7 +215,7 @@ public class EncodedCharsInURI implements HttpServerAdapters {
return null;
}
HttpRequest.Builder newRequestBuilder(String uri) {
static HttpRequest.Builder newRequestBuilder(String uri) {
var builder = HttpRequest.newBuilder(URI.create(uri));
if (version(uri) == HTTP_3) {
builder.version(HTTP_3);
@ -225,7 +224,7 @@ public class EncodedCharsInURI implements HttpServerAdapters {
return builder;
}
HttpResponse<String> headRequest(HttpClient client)
static HttpResponse<String> headRequest(HttpClient client)
throws IOException, InterruptedException
{
out.println("\n" + now() + "--- Sending HEAD request ----\n");
@ -234,27 +233,28 @@ public class EncodedCharsInURI implements HttpServerAdapters {
var request = newRequestBuilder(http3URI_head)
.HEAD().version(HTTP_2).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), HTTP_2);
assertEquals(200, response.statusCode());
assertEquals(HTTP_2, response.version());
out.println("\n" + now() + "--- HEAD request succeeded ----\n");
err.println("\n" + now() + "--- HEAD request succeeded ----\n");
return response;
}
private HttpClient makeNewClient() {
private static HttpClient makeNewClient() {
clientCount.incrementAndGet();
return newClientBuilderForH3()
return HttpServerAdapters.createClientBuilderForH3()
.executor(executor)
.proxy(NO_PROXY)
.sslContext(sslContext)
.build();
}
HttpClient newHttpClient(boolean share) {
private static final Object zis = new Object();
static HttpClient newHttpClient(boolean share) {
if (!share) return makeNewClient();
HttpClient shared = sharedClient;
if (shared != null) return shared;
synchronized (this) {
synchronized (zis) {
shared = sharedClient;
if (shared == null) {
shared = sharedClient = makeNewClient();
@ -273,7 +273,8 @@ public class EncodedCharsInURI implements HttpServerAdapters {
}
}
@Test(dataProvider = "noThrows")
@ParameterizedTest
@MethodSource("noThrows")
public void testEncodedChars(String uri, boolean sameClient)
throws Exception {
HttpClient client = null;
@ -302,13 +303,13 @@ public class EncodedCharsInURI implements HttpServerAdapters {
} else {
out.println("Found expected " + body + " in " + uri);
}
assertEquals(response.version(), version(uri));
assertEquals(version(uri), response.version());
}
}
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
out.println(now() + "begin setup");
// HTTP/1.1
@ -387,8 +388,8 @@ public class EncodedCharsInURI implements HttpServerAdapters {
err.println(now() + "setup done");
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
sharedClient.close();
httpTestServer.stop();
httpsTestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -27,7 +27,7 @@
* @bug 8198716
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm
* @run junit/othervm
* -Djdk.httpclient.HttpClient.log=reqeusts,headers
* EscapedOctetsInURI
*/
@ -52,10 +52,6 @@ import java.util.List;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.httpclient.test.lib.http3.Http3TestServer;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.err;
import static java.lang.System.out;
@ -65,24 +61,29 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class EscapedOctetsInURI implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
String http3URI_head;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
private static String http3URI_head;
private volatile HttpClient sharedClient;
private static volatile HttpClient sharedClient;
static final String[][] pathsAndQueryStrings = new String[][] {
// partial-path URI query
@ -95,8 +96,7 @@ public class EscapedOctetsInURI implements HttpServerAdapters {
{ "/012/with%20space", "?target=http%3A%2F%2Fwww.w3.org%2Fns%2Foa%23hasBody" },
};
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
List<Object[]> list = new ArrayList<>();
for (boolean sameClient : new boolean[] { false, true }) {
@ -140,7 +140,7 @@ public class EscapedOctetsInURI implements HttpServerAdapters {
return null;
}
HttpRequest.Builder newRequestBuilder(String uri) {
static HttpRequest.Builder newRequestBuilder(String uri) {
var builder = HttpRequest.newBuilder(URI.create(uri));
if (version(uri) == HTTP_3) {
builder.version(HTTP_3);
@ -149,7 +149,7 @@ public class EscapedOctetsInURI implements HttpServerAdapters {
return builder;
}
HttpResponse<String> headRequest(HttpClient client)
static HttpResponse<String> headRequest(HttpClient client)
throws IOException, InterruptedException
{
out.println("\n" + now() + "--- Sending HEAD request ----\n");
@ -158,25 +158,26 @@ public class EscapedOctetsInURI implements HttpServerAdapters {
var request = newRequestBuilder(http3URI_head)
.HEAD().version(HTTP_2).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), HTTP_2);
assertEquals(200, response.statusCode());
assertEquals(HTTP_2, response.version());
out.println("\n" + now() + "--- HEAD request succeeded ----\n");
err.println("\n" + now() + "--- HEAD request succeeded ----\n");
return response;
}
private HttpClient makeNewClient() {
return newClientBuilderForH3()
private static HttpClient makeNewClient() {
return HttpServerAdapters.createClientBuilderForH3()
.proxy(NO_PROXY)
.sslContext(sslContext)
.build();
}
HttpClient newHttpClient(boolean share) {
private static final Object zis = new Object();
static HttpClient newHttpClient(boolean share) {
if (!share) return makeNewClient();
HttpClient shared = sharedClient;
if (shared != null) return shared;
synchronized (this) {
synchronized (zis) {
shared = sharedClient;
if (shared == null) {
shared = sharedClient = makeNewClient();
@ -193,7 +194,8 @@ public class EscapedOctetsInURI implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
void test(String uriString, boolean sameClient) throws Exception {
System.out.println("\n--- Starting ");
@ -217,19 +219,20 @@ public class EscapedOctetsInURI implements HttpServerAdapters {
out.println("Got response: " + resp);
out.println("Got body: " + resp.body());
assertEquals(resp.statusCode(), 200,
assertEquals(200, resp.statusCode(),
"Expected 200, got:" + resp.statusCode());
// the response body should contain the exact escaped request URI
URI retrievedURI = URI.create(resp.body());
assertEquals(retrievedURI.getRawPath(), uri.getRawPath());
assertEquals(retrievedURI.getRawQuery(), uri.getRawQuery());
assertEquals(resp.version(), version(uriString));
assertEquals(uri.getRawPath(), retrievedURI.getRawPath());
assertEquals(uri.getRawQuery(), retrievedURI.getRawQuery());
assertEquals(version(uriString), resp.version());
}
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
void testAsync(String uriString, boolean sameClient) throws Exception {
System.out.println("\n--- Starting ");
URI uri = URI.create(uriString);
@ -249,22 +252,22 @@ public class EscapedOctetsInURI implements HttpServerAdapters {
.thenApply(response -> {
out.println("Got response: " + response);
out.println("Got body: " + response.body());
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uriString));
assertEquals(200, response.statusCode());
assertEquals(version(uriString), response.version());
return response.body();
})
.thenApply(body -> URI.create(body))
.thenAccept(retrievedURI -> {
// the body should contain the exact escaped request URI
assertEquals(retrievedURI.getRawPath(), uri.getRawPath());
assertEquals(retrievedURI.getRawQuery(), uri.getRawQuery());
assertEquals(uri.getRawPath(), retrievedURI.getRawPath());
assertEquals(uri.getRawQuery(), retrievedURI.getRawQuery());
}).join();
}
}
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
out.println(now() + "begin setup");
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
@ -311,8 +314,8 @@ public class EscapedOctetsInURI implements HttpServerAdapters {
err.println(now() + "setup done");
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
sharedClient.close();
httpTestServer.stop();
httpsTestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2022, 2026, 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
@ -29,7 +29,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* ReferenceTracker
* @run testng/othervm
* @run junit/othervm
* -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* ExecutorShutdown
@ -65,10 +65,6 @@ import javax.net.ssl.SSLContext;
import jdk.test.lib.RandomFactory;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
@ -78,8 +74,13 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ExecutorShutdown implements HttpServerAdapters {
@ -89,25 +90,24 @@ public class ExecutorShutdown implements HttpServerAdapters {
static final Random RANDOM = RandomFactory.getRandom();
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 6 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer h2h3TestServer; // HTTP/2 ( h2+h3 )
HttpTestServer h3TestServer; // HTTP/2 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String h2h3URI;
String h3URI;
String h2h3Head;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 6 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer h2h3TestServer; // HTTP/2 ( h2+h3 )
private static HttpTestServer h3TestServer; // HTTP/2 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String h2h3URI;
private static String h3URI;
private static String h2h3Head;
static final String MESSAGE = "ExecutorShutdown message body";
static final int ITERATIONS = 3;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ h2h3URI, HTTP_3, h2h3TestServer.h3DiscoveryConfig() },
{ h3URI, HTTP_3, h3TestServer.h3DiscoveryConfig() },
@ -119,7 +119,7 @@ public class ExecutorShutdown implements HttpServerAdapters {
}
static final AtomicLong requestCounter = new AtomicLong();
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
static Throwable getCause(Throwable t) {
while (t instanceof CompletionException || t instanceof ExecutionException) {
@ -158,7 +158,8 @@ public class ExecutorShutdown implements HttpServerAdapters {
throw new AssertionError(what + ": Unexpected exception: " + cause, cause);
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testConcurrent(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- starting (%s) ----%n", uriString);
ExecutorService executorService = Executors.newCachedThreadPool();
@ -209,9 +210,9 @@ public class ExecutorShutdown implements HttpServerAdapters {
var cf = responseCF.thenApply((response) -> {
out.println(si + ": Got response: " + response);
out.println(si + ": Got body Path: " + response.body());
assertEquals(response.statusCode(), 200);
if (si >= head) assertEquals(response.version(), version);
assertEquals(response.body(), MESSAGE);
assertEquals(200, response.statusCode());
if (si >= head) assertEquals(version, response.version());
assertEquals(MESSAGE, response.body());
return response;
}).exceptionally((t) -> {
Throwable cause = getCause(t);
@ -228,7 +229,8 @@ public class ExecutorShutdown implements HttpServerAdapters {
}
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testSequential(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- starting (%s, %s, %s) ----%n%n", uriString, version, config);
ExecutorService executorService = Executors.newCachedThreadPool();
@ -272,9 +274,9 @@ public class ExecutorShutdown implements HttpServerAdapters {
responseCF.thenApply((response) -> {
out.println(si + ": Got response: " + response);
out.println(si + ": Got body Path: " + response.body());
assertEquals(response.statusCode(), 200);
if (si > 0) assertEquals(response.version(), version);
assertEquals(response.body(), MESSAGE);
assertEquals(200, response.statusCode());
if (si > 0) assertEquals(version, response.version());
assertEquals(MESSAGE, response.body());
return response;
}).handle((r,t) -> {
if (t != null) {
@ -305,11 +307,11 @@ public class ExecutorShutdown implements HttpServerAdapters {
.HEAD()
.build();
var resp = client.send(request, BodyHandlers.discarding());
assertEquals(resp.statusCode(), 200);
assertEquals(200, resp.statusCode());
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
out.println("\n**** Setup ****\n");
httpTestServer = HttpTestServer.create(HTTP_1_1);
httpTestServer.addHandler(new ServerRequestHandler(), "/http1/exec/");
@ -342,8 +344,8 @@ public class ExecutorShutdown implements HttpServerAdapters {
h3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
Thread.sleep(100);
AssertionError fail = TRACKER.check(5000);
try {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -28,7 +28,7 @@
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.common.TestServerConfigurator
* @modules java.net.http/jdk.internal.net.http.common
* jdk.httpserver
* @run testng/othervm ExpectContinue
* @run junit/othervm ExpectContinue
*/
import com.sun.net.httpserver.HttpExchange;
@ -51,23 +51,24 @@ import javax.net.ssl.SSLContext;
import jdk.httpclient.test.lib.common.TestServerConfigurator;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ExpectContinue {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpServer httpTestServer; // HTTP/1.1 [ 2 servers ]
HttpsServer httpsTestServer; // HTTPS/1.1
String httpURI;
String httpsURI;
private static HttpServer httpTestServer; // HTTP/1.1 [ 2 servers ]
private static HttpsServer httpsTestServer; // HTTPS/1.1
private static String httpURI;
private static String httpsURI;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ httpURI, false, "Billy" },
{ httpURI, false, "Bob" },
@ -76,7 +77,8 @@ public class ExpectContinue {
};
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void test(String uriString, boolean expectedContinue, String data)
throws Exception
{
@ -94,17 +96,18 @@ public class ExpectContinue {
HttpResponse<String> response = client.send(request,
BodyHandlers.ofString());
System.out.println("First response: " + response);
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), data);
assertEquals(200, response.statusCode());
assertEquals(data, response.body());
// again with the same request, to ensure no Expect header duplication
response = client.send(request, BodyHandlers.ofString());
System.out.println("Second response: " + response);
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), data);
assertEquals(200, response.statusCode());
assertEquals(data, response.body());
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testAsync(String uriString, boolean expectedContinue, String data) {
out.printf("test(%s, %s, %s): starting%n", uriString, expectedContinue, data);
HttpClient client = HttpClient.newBuilder()
@ -120,14 +123,14 @@ public class ExpectContinue {
HttpResponse<String> response = client.sendAsync(request,
BodyHandlers.ofString()).join();
System.out.println("First response: " + response);
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), data);
assertEquals(200, response.statusCode());
assertEquals(data, response.body());
// again with the same request, to ensure no Expect header duplication
response = client.sendAsync(request, BodyHandlers.ofString()).join();
System.out.println("Second response: " + response);
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), data);
assertEquals(200, response.statusCode());
assertEquals(data, response.body());
}
// -- Infrastructure
@ -137,8 +140,8 @@ public class ExpectContinue {
+ server.getAddress().getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
httpTestServer = HttpServer.create(sa, 0);
httpTestServer.createContext("/http1/ec", new Http1ExpectContinueHandler());
@ -153,8 +156,8 @@ public class ExpectContinue {
httpsTestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop(0);
httpsTestServer.stop(0);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022, 2024, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2022, 2026, 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
@ -27,7 +27,7 @@
* @bug 8286171 8307648
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters
* @run testng/othervm -Djdk.internal.httpclient.debug=true -Djdk.httpclient.HttpClient.log=errors ExpectContinueTest
* @run junit/othervm -Djdk.internal.httpclient.debug=true -Djdk.httpclient.HttpClient.log=errors ExpectContinueTest
*/
@ -40,11 +40,6 @@ import jdk.httpclient.test.lib.http2.Http2TestServerConnection;
import jdk.httpclient.test.lib.http2.Http2TestServerConnection.ResponseHeaders;
import jdk.internal.net.http.common.HttpHeadersBuilder;
import jdk.internal.net.http.frame.HeaderFrame;
import org.testng.TestException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLSession;
@ -79,23 +74,29 @@ import jdk.httpclient.test.lib.common.HttpServerAdapters;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.*;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ExpectContinueTest implements HttpServerAdapters {
HttpTestServer http1TestServer; // HTTP/1.1
Http1HangServer http1HangServer;
Http2TestServer http2TestServer; // HTTP/2
private static HttpTestServer http1TestServer; // HTTP/1.1
private static Http1HangServer http1HangServer;
private static Http2TestServer http2TestServer; // HTTP/2
URI getUri, postUri, forcePostUri, hangUri;
URI h2postUri, h2forcePostUri, h2hangUri, h2endStreamUri, h2warmupURI;
private static URI getUri, postUri, forcePostUri, hangUri;
private static URI h2postUri, h2forcePostUri, h2hangUri, h2endStreamUri, h2warmupURI;
static PrintStream err = new PrintStream(System.err);
static PrintStream out = new PrintStream(System.out);
static final String EXPECTATION_FAILED_417 = "417 Expectation Failed";
@DataProvider(name = "uris")
public Object[][] urisData() {
public static Object[][] urisData() {
return new Object[][]{
// URI, Expected Status Code, Will finish with Exception, Protocol Version
{ postUri, 200, false, HTTP_1_1 },
@ -107,7 +108,8 @@ public class ExpectContinueTest implements HttpServerAdapters {
{ h2endStreamUri, 200, true, HTTP_2 }, // Error
};
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("urisData")
public void test(URI uri, int expectedStatusCode, boolean exceptionally, HttpClient.Version version)
throws CancellationException, InterruptedException, ExecutionException, IOException {
@ -135,8 +137,8 @@ public class ExpectContinueTest implements HttpServerAdapters {
}
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
InetSocketAddress saHang = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
http1TestServer = HttpTestServer.create(HTTP_1_1);
http1TestServer.addHandler(new GetHandler(), "/http1/get");
@ -173,8 +175,8 @@ public class ExpectContinueTest implements HttpServerAdapters {
http1HangServer.start();
http2TestServer.start();
}
@AfterTest
public void teardown() throws IOException {
@AfterAll
public static void teardown() throws IOException {
http1TestServer.stop();
http1HangServer.close();
http2TestServer.stop();
@ -372,11 +374,11 @@ public class ExpectContinueTest implements HttpServerAdapters {
}
if (exceptionally && testThrowable != null) {
err.println("Finished exceptionally Test throwable: " + testThrowable);
assertEquals(testThrowable.getClass(), ProtocolException.class);
assertEquals(ProtocolException.class, testThrowable.getClass());
} else if (exceptionally) {
throw new TestException("Expected case to finish with an IOException but testException is null");
fail("Expected case to finish with an IOException but testException is null");
} else if (resp != null) {
assertEquals(resp.statusCode(), expectedStatusCode);
assertEquals(expectedStatusCode, resp.statusCode());
err.println("Request completed successfully for path " + path);
err.println("Response Headers: " + resp.headers());
err.println("Response Status Code: " + resp.statusCode());

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2026, 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
@ -29,14 +29,10 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters
* jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm FilePublisherTest
* @run junit/othervm FilePublisherTest
*/
import jdk.test.lib.net.SimpleSSLContext;
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;
@ -58,22 +54,27 @@ import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class FilePublisherTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
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;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
FileSystem zipFs;
Path defaultFsPath;
Path zipFsPath;
private static FileSystem zipFs;
private static Path defaultFsPath;
private static Path zipFsPath;
// Default file system set up
static final String DEFAULT_FS_MSG = "default fs";
@ -84,12 +85,11 @@ public class FilePublisherTest implements HttpServerAdapters {
Files.createFile(file);
Files.writeString(file, DEFAULT_FS_MSG);
}
assertEquals(Files.readString(file), DEFAULT_FS_MSG);
assertEquals(DEFAULT_FS_MSG, Files.readString(file));
return file;
}
@DataProvider(name = "defaultFsData")
public Object[][] defaultFsData() {
public static Object[][] defaultFsData() {
return new Object[][]{
{ httpURI, defaultFsPath, DEFAULT_FS_MSG, true },
{ httpsURI, defaultFsPath, DEFAULT_FS_MSG, true },
@ -102,7 +102,8 @@ public class FilePublisherTest implements HttpServerAdapters {
};
}
@Test(dataProvider = "defaultFsData")
@ParameterizedTest
@MethodSource("defaultFsData")
public void testDefaultFs(String uriString,
Path path,
String expectedMsg,
@ -126,12 +127,11 @@ public class FilePublisherTest implements HttpServerAdapters {
Files.createFile(file);
Files.writeString(file, ZIP_FS_MSG);
}
assertEquals(Files.readString(file), ZIP_FS_MSG);
assertEquals(ZIP_FS_MSG, Files.readString(file));
return file;
}
@DataProvider(name = "zipFsData")
public Object[][] zipFsData() {
public static Object[][] zipFsData() {
return new Object[][]{
{ httpURI, zipFsPath, ZIP_FS_MSG, true },
{ httpsURI, zipFsPath, ZIP_FS_MSG, true },
@ -144,7 +144,8 @@ public class FilePublisherTest implements HttpServerAdapters {
};
}
@Test(dataProvider = "zipFsData")
@ParameterizedTest
@MethodSource("zipFsData")
public void testZipFs(String uriString,
Path path,
String expectedMsg,
@ -176,13 +177,13 @@ public class FilePublisherTest implements HttpServerAdapters {
var resp = client.send(req, HttpResponse.BodyHandlers.ofString());
out.println("Got response: " + resp);
out.println("Got body: " + resp.body());
assertEquals(resp.statusCode(), 200);
assertEquals(resp.body(), expectedMsg);
assertEquals(200, resp.statusCode());
assertEquals(expectedMsg, resp.body());
}
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
defaultFsPath = defaultFsFile();
zipFs = newZipFs();
zipFsPath = zipFsFile(zipFs);
@ -209,8 +210,8 @@ public class FilePublisherTest implements HttpServerAdapters {
https2TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop();
httpsTestServer.stop();
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -42,10 +42,6 @@ import java.net.http.HttpResponse;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.test.lib.net.SimpleSSLContext;
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 static java.net.http.HttpOption.H3_DISCOVERY;
@ -53,8 +49,14 @@ import static java.util.stream.Collectors.joining;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.net.http.HttpRequest.BodyPublishers.fromPublisher;
import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
@ -62,25 +64,24 @@ import static org.testng.Assert.fail;
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters
* jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm -Djdk.internal.httpclient.debug=err FlowAdapterPublisherTest
* @run junit/othervm -Djdk.internal.httpclient.debug=err FlowAdapterPublisherTest
*/
public class FlowAdapterPublisherTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
@DataProvider(name = "uris")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ httpURI },
{ httpsURI },
@ -120,7 +121,8 @@ public class FlowAdapterPublisherTest implements HttpServerAdapters {
return builder;
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testByteBufferPublisherUnknownLength(String uri) {
String[] body = new String[] { "You know ", "it's summer ", "in Ireland ",
"when the ", "rain gets ", "warmer." };
@ -131,13 +133,14 @@ public class FlowAdapterPublisherTest implements HttpServerAdapters {
HttpResponse<String> response = client.sendAsync(request, ofString(UTF_8)).join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, Arrays.stream(body).collect(joining()));
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals(Arrays.stream(body).collect(joining()), text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testByteBufferPublisherFixedLength(String uri) {
String[] body = new String[] { "You know ", "it's summer ", "in Ireland ",
"when the ", "rain gets ", "warmer." };
@ -149,15 +152,16 @@ public class FlowAdapterPublisherTest implements HttpServerAdapters {
HttpResponse<String> response = client.sendAsync(request, ofString(UTF_8)).join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, Arrays.stream(body).collect(joining()));
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals(Arrays.stream(body).collect(joining()), text);
}
}
// Flow.Publisher<MappedByteBuffer>
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testMappedByteBufferPublisherUnknownLength(String uri) {
String[] body = new String[] { "God invented ", "whiskey to ", "keep the ",
"Irish from ", "ruling the ", "world." };
@ -168,13 +172,14 @@ public class FlowAdapterPublisherTest implements HttpServerAdapters {
HttpResponse<String> response = client.sendAsync(request, ofString(UTF_8)).join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, Arrays.stream(body).collect(joining()));
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals(Arrays.stream(body).collect(joining()), text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testMappedByteBufferPublisherFixedLength(String uri) {
String[] body = new String[] { "God invented ", "whiskey to ", "keep the ",
"Irish from ", "ruling the ", "world." };
@ -186,9 +191,9 @@ public class FlowAdapterPublisherTest implements HttpServerAdapters {
HttpResponse<String> response = client.sendAsync(request, ofString(UTF_8)).join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, Arrays.stream(body).collect(joining()));
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals(Arrays.stream(body).collect(joining()), text);
}
}
@ -196,7 +201,8 @@ public class FlowAdapterPublisherTest implements HttpServerAdapters {
// not ideal, but necessary to discern correct behavior. They should be
// updated if the exception message is updated.
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testPublishTooFew(String uri) throws InterruptedException {
String[] body = new String[] { "You know ", "it's summer ", "in Ireland ",
"when the ", "rain gets ", "warmer." };
@ -214,7 +220,8 @@ public class FlowAdapterPublisherTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testPublishTooMany(String uri) throws InterruptedException {
String[] body = new String[] { "You know ", "it's summer ", "in Ireland ",
"when the ", "rain gets ", "warmer." };
@ -356,8 +363,8 @@ public class FlowAdapterPublisherTest implements HttpServerAdapters {
}
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpTestServer.create(Version.HTTP_1_1);
httpTestServer.addHandler(new HttpEchoHandler(), "/http1/echo");
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/echo";
@ -385,8 +392,8 @@ public class FlowAdapterPublisherTest implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop();
httpsTestServer.stop();
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -53,17 +53,19 @@ import java.net.http.HttpResponse.BodySubscribers;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.test.lib.net.SimpleSSLContext;
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 static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
@ -72,22 +74,22 @@ import static org.testng.Assert.assertTrue;
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters
* jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm -Djdk.internal.httpclient.debug=true FlowAdapterSubscriberTest
* @run junit/othervm -Djdk.internal.httpclient.debug=true FlowAdapterSubscriberTest
*/
public class FlowAdapterSubscriberTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
static final StackWalker WALKER =
StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
@ -101,8 +103,7 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
}
@DataProvider(name = "uris")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ httpURI },
{ httpsURI },
@ -154,7 +155,7 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
assertThrows(NPE, () -> BodySubscribers.fromSubscriber(new ListSubscriber(), null));
assertThrows(NPE, () -> BodySubscribers.fromSubscriber(null, null));
Subscriber subscriber = BodySubscribers.fromSubscriber(new ListSubscriber());
Subscriber<?> subscriber = BodySubscribers.fromSubscriber(new ListSubscriber());
assertThrows(NPE, () -> subscriber.onSubscribe(null));
assertThrows(NPE, () -> subscriber.onNext(null));
assertThrows(NPE, () -> subscriber.onError(null));
@ -162,7 +163,8 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
// List<ByteBuffer>
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testListWithFinisher(String uri) {
System.out.printf(now() + "testListWithFinisher(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -174,13 +176,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber, Supplier::get)).join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "May the luck of the Irish be with you!");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("May the luck of the Irish be with you!", text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testListWithoutFinisher(String uri) {
System.out.printf(now() + "testListWithoutFinisher(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -192,13 +195,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber)).join();
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "May the luck of the Irish be with you!");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("May the luck of the Irish be with you!", text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testListWithFinisherBlocking(String uri) throws Exception {
System.out.printf(now() + "testListWithFinisherBlocking(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -210,13 +214,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber, Supplier::get));
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "May the luck of the Irish be with you!");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("May the luck of the Irish be with you!", text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testListWithoutFinisherBlocking(String uri) throws Exception {
System.out.printf(now() + "testListWithoutFinisherBlocking(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -228,15 +233,16 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber));
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "May the luck of the Irish be with you!");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("May the luck of the Irish be with you!", text);
}
}
// Collection<ByteBuffer>
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testCollectionWithFinisher(String uri) {
System.out.printf(now() + "testCollectionWithFinisher(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -248,13 +254,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber, CollectionSubscriber::get)).join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "What's the craic?");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("What's the craic?", text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testCollectionWithoutFinisher(String uri) {
System.out.printf(now() + "testCollectionWithoutFinisher(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -266,13 +273,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber)).join();
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "What's the craic?");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("What's the craic?", text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testCollectionWithFinisherBlocking(String uri) throws Exception {
System.out.printf(now() + "testCollectionWithFinisherBlocking(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -284,13 +292,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber, CollectionSubscriber::get));
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "What's the craic?");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("What's the craic?", text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testCollectionWithoutFinisherBlocking(String uri) throws Exception {
System.out.printf(now() + "testCollectionWithoutFinisherBlocking(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -302,15 +311,16 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber));
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "What's the craic?");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("What's the craic?", text);
}
}
// Iterable<ByteBuffer>
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testIterableWithFinisher(String uri) {
System.out.printf(now() + "testIterableWithFinisher(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -322,13 +332,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber, Supplier::get)).join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "We're sucking diesel now!");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("We're sucking diesel now!", text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testIterableWithoutFinisher(String uri) {
System.out.printf(now() + "testIterableWithoutFinisher(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -340,13 +351,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber)).join();
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "We're sucking diesel now!");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("We're sucking diesel now!", text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testIterableWithFinisherBlocking(String uri) throws Exception {
System.out.printf(now() + "testIterableWithFinisherBlocking(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -358,13 +370,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber, Supplier::get));
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "We're sucking diesel now!");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("We're sucking diesel now!", text);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testIterableWithoutFinisherBlocking(String uri) throws Exception {
System.out.printf(now() + "testIterableWithoutFinisherBlocking(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -376,15 +389,16 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber));
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(text, "We're sucking diesel now!");
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertEquals("We're sucking diesel now!", text);
}
}
// Subscriber<Object>
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testObjectWithFinisher(String uri) {
System.out.printf(now() + "testObjectWithFinisher(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -396,13 +410,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber, ObjectSubscriber::get)).join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertTrue(text.length() != 0); // what else can be asserted!
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testObjectWithoutFinisher(String uri) {
System.out.printf(now() + "testObjectWithoutFinisher(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -414,13 +429,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber)).join();
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertTrue(text.length() != 0); // what else can be asserted!
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testObjectWithFinisherBlocking(String uri) throws Exception {
System.out.printf(now() + "testObjectWithFinisherBlocking(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -432,13 +448,14 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber, ObjectSubscriber::get));
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertTrue(text.length() != 0); // what else can be asserted!
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testObjectWithoutFinisherBlocking(String uri) throws Exception {
System.out.printf(now() + "testObjectWithoutFinisherBlocking(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -450,8 +467,8 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
BodyHandlers.fromSubscriber(subscriber));
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uri));
assertEquals(200, response.statusCode());
assertEquals(version(uri), response.version());
assertTrue(text.length() != 0); // what else can be asserted!
}
}
@ -459,7 +476,8 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
// -- mapping using convenience handlers
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void mappingFromByteArray(String uri) throws Exception {
System.out.printf(now() + "mappingFromByteArray(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -470,12 +488,13 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
bas -> new String(bas.getBody().toCompletableFuture().join(), UTF_8)))
.thenApply(FlowAdapterSubscriberTest::assert200ResponseCode)
.thenApply(HttpResponse::body)
.thenAccept(body -> assertEquals(body, "We're sucking diesel now!"))
.thenAccept(body -> assertEquals("We're sucking diesel now!", body))
.join();
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void mappingFromInputStream(String uri) throws Exception {
System.out.printf(now() + "mappingFromInputStream(%s) starting%n", uri);
try (HttpClient client = newHttpClient(uri)) {
@ -512,7 +531,7 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
finisher))
.thenApply(FlowAdapterSubscriberTest::assert200ResponseCode)
.thenApply(HttpResponse::body)
.thenAccept(body -> assertEquals(body, "May the wind always be at your back."))
.thenAccept(body -> assertEquals("May the wind always be at your back.", body))
.join();
var error = failed.get();
if (error != null) throw error;
@ -626,13 +645,13 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
}
static final <T> HttpResponse<T> assert200ResponseCode(HttpResponse<T> response) {
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(response.request().uri().toString()));
assertEquals(200, response.statusCode());
assertEquals(version(response.request().uri().toString()), response.version());
return response;
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpTestServer.create(Version.HTTP_1_1);
httpTestServer.addHandler(new HttpEchoHandler(), "/http1/echo");
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/echo";
@ -660,8 +679,8 @@ public class FlowAdapterSubscriberTest implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop();
httpsTestServer.stop();
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, 2026, 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
@ -27,15 +27,11 @@
* @summary Tests that you can map an InputStream to a GZIPInputStream
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.common.HttpServerAdapters ReferenceTracker
* @run testng/othervm GZIPInputStreamTest
* @run junit/othervm GZIPInputStreamTest
*/
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.SimpleSSLContext;
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;
@ -46,7 +42,6 @@ import java.net.InetAddress;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpOption.Http3DiscoveryMode;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodyHandlers;
@ -68,21 +63,26 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class GZIPInputStreamTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer https3TestServer; // HTTP/3
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String https3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer https3TestServer; // HTTP/3
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String https3URI;
static final int ITERATION_COUNT = 3;
// a shared executor helps reduce the amount of threads created by the test
@ -154,8 +154,7 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ httpURI, false },
{ httpURI, true },
@ -170,7 +169,7 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
};
}
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
HttpClient newHttpClient() {
return TRACKER.track(newClientBuilderForH3()
.executor(executor)
@ -192,7 +191,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
.build());
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testPlainSyncAsString(String uri, boolean sameClient) throws Exception {
out.println("\nSmoke test: verify that the result we get from the server is correct.");
out.println("Uses plain send() and `asString` to get the plain string.");
@ -209,7 +209,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testPlainSyncAsInputStream(String uri, boolean sameClient) throws Exception {
out.println("Uses plain send() and `asInputStream` - calls readAllBytes() from main thread");
out.println("Uses single threaded executor");
@ -225,7 +226,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testGZIPSyncAsInputStream(String uri, boolean sameClient) throws Exception {
out.println("Uses plain send() and `asInputStream` - " +
"creates GZIPInputStream and calls readAllBytes() from main thread");
@ -243,7 +245,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testGZIPSyncAsGZIPInputStream(String uri, boolean sameClient) throws Exception {
out.println("Uses plain send() and a mapping subscriber to "+
"create the GZIPInputStream. Calls readAllBytes() from main thread");
@ -262,7 +265,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testGZIPSyncAsGZIPInputStreamSupplier(String uri, boolean sameClient) throws Exception {
out.println("Uses plain send() and a mapping subscriber to "+
"create a Supplier<GZIPInputStream>. Calls Supplier.get() " +
@ -276,7 +280,7 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
HttpRequest req = buildRequest(URI.create(uri + "/gz/LoremIpsum.txt.gz"));
// This is dangerous, because the finisher will block.
// We support this, but the executor must have enough threads.
BodyHandler<Supplier<InputStream>> handler = new BodyHandler<Supplier<InputStream>>() {
BodyHandler<Supplier<InputStream>> handler = new BodyHandler<>() {
public HttpResponse.BodySubscriber<Supplier<InputStream>> apply(
HttpResponse.ResponseInfo responseInfo)
{
@ -304,7 +308,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testPlainAsyncAsInputStreamBlocks(String uri, boolean sameClient) throws Exception {
out.println("Uses sendAsync() and `asInputStream`. Registers a dependent action "+
"that calls readAllBytes()");
@ -331,7 +336,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testGZIPAsyncAsGZIPInputStreamBlocks(String uri, boolean sameClient) throws Exception {
out.println("Uses sendAsync() and a mapping subscriber to create a GZIPInputStream. " +
"Registers a dependent action that calls readAllBytes()");
@ -358,7 +364,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testGZIPSyncAsGZIPInputStreamBlocks(String uri, boolean sameClient) throws Exception {
out.println("Uses sendAsync() and a mapping subscriber to create a GZIPInputStream," +
"which is mapped again using a mapping subscriber " +
@ -386,7 +393,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testGZIPSyncAsGZIPInputStreamSupplierInline(String uri, boolean sameClient) throws Exception {
out.println("Uses plain send() and a mapping subscriber to "+
"create a Supplier<GZIPInputStream>. Calls Supplier.get() " +
@ -432,7 +440,7 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
if (!LOREM_IPSUM.equals(responseBody)) {
out.println("Response doesn't match");
out.println("[" + LOREM_IPSUM + "] != [" + responseBody + "]");
assertEquals(LOREM_IPSUM, responseBody);
assertEquals(responseBody, LOREM_IPSUM);
} else {
out.println("Received expected response.");
}
@ -487,8 +495,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
+ server.getAddress().getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
HttpTestHandler plainHandler = new LoremIpsumPlainHandler();
HttpTestHandler gzipHandler = new LoremIpsumGZIPHandler();
@ -526,8 +534,8 @@ public class GZIPInputStreamTest implements HttpServerAdapters {
https3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
Thread.sleep(100);
AssertionError fail = TRACKER.check(500);
try {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -27,14 +27,10 @@
* @summary Tests Client handles HEAD and 304 responses correctly.
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm -Djdk.httpclient.HttpClient.log=trace,headers,requests HeadTest
* @run junit/othervm -Djdk.httpclient.HttpClient.log=trace,headers,requests HeadTest
*/
import jdk.test.lib.net.SimpleSSLContext;
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;
@ -55,19 +51,24 @@ import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static jdk.httpclient.test.lib.common.HttpServerAdapters.createClientBuilderForH3;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class HeadTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer https3TestServer; // HTTP/3
String httpURI, httpsURI;
String http2URI, https2URI;
String https3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer https3TestServer; // HTTP/3
private static String httpURI, httpsURI;
private static String http2URI, https2URI;
private static String https3URI;
static final String CONTENT_LEN = "300";
@ -80,8 +81,7 @@ public class HeadTest implements HttpServerAdapters {
static final int HTTP_OK = 200;
static final PrintStream out = System.out;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
// HTTP/1.1
{ httpURI, "GET", HTTP_NOT_MODIFIED, HTTP_1_1 },
@ -103,7 +103,8 @@ public class HeadTest implements HttpServerAdapters {
};
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void test(String uriString, String method,
int expResp, Version version) throws Exception {
out.printf("%n---- starting (%s) ----%n", uriString);
@ -136,17 +137,17 @@ public class HeadTest implements HttpServerAdapters {
out.println(" Got response: " + response);
assertEquals(response.statusCode(), expResp);
assertEquals(response.body(), "");
assertEquals(response.headers().firstValue("Content-length").get(), CONTENT_LEN);
assertEquals(response.version(), request.version().get());
assertEquals(expResp, response.statusCode());
assertEquals("", response.body());
assertEquals(CONTENT_LEN, response.headers().firstValue("Content-length").get());
assertEquals(request.version().get(), response.version());
}
}
// -- Infrastructure
// TODO: See if test performs better with Vthreads, see H3SimplePost and H3SimpleGet
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpTestServer.create(HTTP_1_1);
httpTestServer.addHandler(new HeadHandler(), "/");
httpURI = "http://" + httpTestServer.serverAuthority() + "/";
@ -173,8 +174,8 @@ public class HeadTest implements HttpServerAdapters {
https3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop();
httpsTestServer.stop();
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2026, 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
@ -26,7 +26,7 @@
* @bug 8153142 8195138
* @modules java.net.http
* jdk.httpserver
* @run testng/othervm HeadersTest1
* @run junit/othervm HeadersTest1
*/
import java.io.IOException;
@ -48,13 +48,13 @@ import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.testng.annotations.Test;
import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
public class HeadersTest1 {
@ -106,7 +106,7 @@ public class HeadersTest1 {
for (String headerName : headernames) {
List<String> v2 = hd.allValues(headerName);
assertNotNull(v2);
assertEquals(new HashSet<>(v2), Set.of("resp1", "resp2"));
assertEquals(Set.of("resp1", "resp2"), new HashSet<>(v2));
TestKit.assertUnmodifiableList(v2);
}
@ -130,7 +130,7 @@ public class HeadersTest1 {
// quote
List<String> quote = hd.allValues("X-Quote-Response");
assertEquals(quote, List.of(QUOTED));
assertEquals(List.of(QUOTED), quote);
} finally {
server.stop(0);
e.shutdownNow();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -51,9 +51,10 @@ import java.net.http.HttpClient.Version;
import java.util.concurrent.atomic.AtomicInteger;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.Test;
import static java.time.Duration.*;
import static org.testng.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
/*
* @test
@ -61,7 +62,7 @@ import static org.testng.Assert.*;
* @summary HttpClient[.Builder] API and behaviour checks
* @library /test/lib
* @build jdk.test.lib.net.SimpleSSLContext
* @run testng HttpClientBuilderTest
* @run junit HttpClientBuilderTest
*/
public class HttpClientBuilderTest {
@ -83,10 +84,10 @@ public class HttpClientBuilderTest {
assertFalse(client.connectTimeout().isPresent());
assertFalse(client.executor().isPresent());
assertFalse(client.proxy().isPresent());
assertTrue(client.sslParameters() != null);
assertTrue(client.followRedirects().equals(HttpClient.Redirect.NEVER));
assertTrue(client.sslContext() == SSLContext.getDefault());
assertTrue(client.version().equals(HttpClient.Version.HTTP_2));
assertNotNull(client.sslParameters());
assertEquals(Redirect.NEVER, client.followRedirects());
assertSame(SSLContext.getDefault(), client.sslContext());
assertEquals(Version.HTTP_2, client.version());
}
}
}
@ -133,18 +134,18 @@ public class HttpClientBuilderTest {
Authenticator a = new TestAuthenticator();
builder.authenticator(a);
try (var closer = closeable(builder)) {
assertTrue(closer.build().authenticator().get() == a);
assertSame(a, closer.build().authenticator().get());
}
Authenticator b = new TestAuthenticator();
builder.authenticator(b);
try (var closer = closeable(builder)) {
assertTrue(closer.build().authenticator().get() == b);
assertSame(b, closer.build().authenticator().get());
}
assertThrows(NPE, () -> builder.authenticator(null));
Authenticator c = new TestAuthenticator();
builder.authenticator(c);
try (var closer = closeable(builder)) {
assertTrue(closer.build().authenticator().get() == c);
assertSame(c, closer.build().authenticator().get());
}
}
@ -154,18 +155,18 @@ public class HttpClientBuilderTest {
CookieHandler a = new CookieManager();
builder.cookieHandler(a);
try (var closer = closeable(builder)) {
assertTrue(closer.build().cookieHandler().get() == a);
assertSame(a, closer.build().cookieHandler().get());
}
CookieHandler b = new CookieManager();
builder.cookieHandler(b);
try (var closer = closeable(builder)) {
assertTrue(closer.build().cookieHandler().get() == b);
assertSame(b, closer.build().cookieHandler().get());
}
assertThrows(NPE, () -> builder.cookieHandler(null));
CookieManager c = new CookieManager();
builder.cookieHandler(c);
try (var closer = closeable(builder)) {
assertTrue(closer.build().cookieHandler().get() == c);
assertSame(c, closer.build().cookieHandler().get());
}
}
@ -175,18 +176,18 @@ public class HttpClientBuilderTest {
Duration a = Duration.ofSeconds(5);
builder.connectTimeout(a);
try (var closer = closeable(builder)) {
assertTrue(closer.build().connectTimeout().get() == a);
assertSame(a, closer.build().connectTimeout().get());
}
Duration b = Duration.ofMinutes(1);
builder.connectTimeout(b);
try (var closer = closeable(builder)) {
assertTrue(closer.build().connectTimeout().get() == b);
assertSame(b, closer.build().connectTimeout().get());
}
assertThrows(NPE, () -> builder.cookieHandler(null));
Duration c = Duration.ofHours(100);
builder.connectTimeout(c);
try (var closer = closeable(builder)) {
assertTrue(closer.build().connectTimeout().get() == c);
assertSame(c, closer.build().connectTimeout().get());
}
assertThrows(IAE, () -> builder.connectTimeout(ZERO));
@ -205,18 +206,18 @@ public class HttpClientBuilderTest {
TestExecutor a = new TestExecutor();
builder.executor(a);
try (var closer = closeable(builder)) {
assertTrue(closer.build().executor().get() == a);
assertSame(a, closer.build().executor().get());
}
TestExecutor b = new TestExecutor();
builder.executor(b);
try (var closer = closeable(builder)) {
assertTrue(closer.build().executor().get() == b);
assertSame(b, closer.build().executor().get());
}
assertThrows(NPE, () -> builder.executor(null));
TestExecutor c = new TestExecutor();
builder.executor(c);
try (var closer = closeable(builder)) {
assertTrue(closer.build().executor().get() == c);
assertSame(c, closer.build().executor().get());
}
}
@ -226,18 +227,18 @@ public class HttpClientBuilderTest {
ProxySelector a = ProxySelector.of(null);
builder.proxy(a);
try (var closer = closeable(builder)) {
assertTrue(closer.build().proxy().get() == a);
assertSame(a, closer.build().proxy().get());
}
ProxySelector b = ProxySelector.of(InetSocketAddress.createUnresolved("foo", 80));
builder.proxy(b);
try (var closer = closeable(builder)) {
assertTrue(closer.build().proxy().get() == b);
assertSame(b, closer.build().proxy().get());
}
assertThrows(NPE, () -> builder.proxy(null));
ProxySelector c = ProxySelector.of(InetSocketAddress.createUnresolved("bar", 80));
builder.proxy(c);
try (var closer = closeable(builder)) {
assertTrue(closer.build().proxy().get() == c);
assertSame(c, closer.build().proxy().get());
}
}
@ -249,16 +250,16 @@ public class HttpClientBuilderTest {
builder.sslParameters(a);
a.setCipherSuites(new String[] { "Z" });
try (var closer = closeable(builder)) {
assertTrue(closer.build().sslParameters() != (a));
assertNotSame(a, closer.build().sslParameters());
}
try (var closer = closeable(builder)) {
assertTrue(closer.build().sslParameters().getCipherSuites()[0].equals("A"));
assertEquals("A", closer.build().sslParameters().getCipherSuites()[0]);
}
SSLParameters b = new SSLParameters();
b.setEnableRetransmissions(true);
builder.sslParameters(b);
try (var closer = closeable(builder)) {
assertTrue(closer.build().sslParameters() != b);
assertNotSame(b, closer.build().sslParameters());
}
try (var closer = closeable(builder)) {
assertTrue(closer.build().sslParameters().getEnableRetransmissions());
@ -269,21 +270,21 @@ public class HttpClientBuilderTest {
builder.sslParameters(c);
c.setProtocols(new String[] { "D" });
try (var closer = closeable(builder)) {
assertTrue(closer.build().sslParameters().getProtocols()[0].equals("C"));
assertEquals("C", closer.build().sslParameters().getProtocols()[0]);
}
SSLParameters d = new SSLParameters();
d.setSignatureSchemes(new String[] { "C" });
builder.sslParameters(d);
d.setSignatureSchemes(new String[] { "D" });
try (var closer = closeable(builder)) {
assertTrue(closer.build().sslParameters().getSignatureSchemes()[0].equals("C"));
assertEquals("C", closer.build().sslParameters().getSignatureSchemes()[0]);
}
SSLParameters e = new SSLParameters();
e.setNamedGroups(new String[] { "C" });
builder.sslParameters(e);
e.setNamedGroups(new String[] { "D" });
try (var closer = closeable(builder)) {
assertTrue(closer.build().sslParameters().getNamedGroups()[0].equals("C"));
assertEquals("C", closer.build().sslParameters().getNamedGroups()[0]);
}
// test defaults for needClientAuth and wantClientAuth
builder.sslParameters(new SSLParameters());
@ -321,18 +322,18 @@ public class HttpClientBuilderTest {
SSLContext a = SimpleSSLContext.findSSLContext();
builder.sslContext(a);
try (var closer = closeable(builder)) {
assertTrue(closer.build().sslContext() == a);
assertSame(a, closer.build().sslContext());
}
SSLContext b = SimpleSSLContext.findSSLContext();
builder.sslContext(b);
try (var closer = closeable(builder)) {
assertTrue(closer.build().sslContext() == b);
assertSame(b, closer.build().sslContext());
}
assertThrows(NPE, () -> builder.sslContext(null));
SSLContext c = SimpleSSLContext.findSSLContext();
builder.sslContext(c);
try (var closer = closeable(builder)) {
assertTrue(closer.build().sslContext() == c);
assertSame(c, closer.build().sslContext());
}
}
@ -341,16 +342,16 @@ public class HttpClientBuilderTest {
HttpClient.Builder builder = HttpClient.newBuilder();
builder.followRedirects(Redirect.ALWAYS);
try (var closer = closeable(builder)) {
assertTrue(closer.build().followRedirects() == Redirect.ALWAYS);
assertSame(Redirect.ALWAYS, closer.build().followRedirects());
}
builder.followRedirects(Redirect.NEVER);
try (var closer = closeable(builder)) {
assertTrue(closer.build().followRedirects() == Redirect.NEVER);
assertSame(Redirect.NEVER, closer.build().followRedirects());
}
assertThrows(NPE, () -> builder.followRedirects(null));
builder.followRedirects(Redirect.NORMAL);
try (var closer = closeable(builder)) {
assertTrue(closer.build().followRedirects() == Redirect.NORMAL);
assertSame(Redirect.NORMAL, closer.build().followRedirects());
}
}
@ -358,37 +359,37 @@ public class HttpClientBuilderTest {
public void testVersion() {
HttpClient.Builder builder = HttpClient.newBuilder();
try (var closer = closeable(builder)) {
assertTrue(closer.build().version() == Version.HTTP_2);
assertSame(Version.HTTP_2, closer.build().version());
}
builder.version(Version.HTTP_3);
try (var closer = closeable(builder)) {
assertTrue(closer.build().version() == Version.HTTP_3);
assertSame(Version.HTTP_3, closer.build().version());
}
builder.version(Version.HTTP_2);
try (var closer = closeable(builder)) {
assertTrue(closer.build().version() == Version.HTTP_2);
assertSame(Version.HTTP_2, closer.build().version());
}
builder.version(Version.HTTP_1_1);
try (var closer = closeable(builder)) {
assertTrue(closer.build().version() == Version.HTTP_1_1);
assertSame(Version.HTTP_1_1, closer.build().version());
}
assertThrows(NPE, () -> builder.version(null));
builder.version(Version.HTTP_3);
try (var closer = closeable(builder)) {
assertTrue(closer.build().version() == Version.HTTP_3);
assertSame(Version.HTTP_3, closer.build().version());
}
builder.version(Version.HTTP_2);
try (var closer = closeable(builder)) {
assertTrue(closer.build().version() == Version.HTTP_2);
assertSame(Version.HTTP_2, closer.build().version());
}
builder.version(Version.HTTP_1_1);
try (var closer = closeable(builder)) {
assertTrue(closer.build().version() == Version.HTTP_1_1);
assertSame(Version.HTTP_1_1, closer.build().version());
}
}
@Test
static void testPriority() throws Exception {
void testPriority() throws Exception {
HttpClient.Builder builder = HttpClient.newBuilder();
assertThrows(IAE, () -> builder.priority(-1));
assertThrows(IAE, () -> builder.priority(0));
@ -489,7 +490,7 @@ public class HttpClientBuilderTest {
static final URI uri = URI.create("http://foo.com/");
@Test
static void testHttpClientSendArgs() throws Exception {
void testHttpClientSendArgs() throws Exception {
try (HttpClient client = HttpClient.newHttpClient()) {
HttpRequest request = HttpRequest.newBuilder(uri).build();
@ -527,21 +528,21 @@ public class HttpClientBuilderTest {
// ---
@Test
static void testUnsupportedWebSocket() throws Exception {
void testUnsupportedWebSocket() throws Exception {
// @implSpec The default implementation of this method throws
// {@code UnsupportedOperationException}.
assertThrows(UOE, () -> (new MockHttpClient()).newWebSocketBuilder());
}
@Test
static void testDefaultShutdown() throws Exception {
void testDefaultShutdown() throws Exception {
try (HttpClient client = new MockHttpClient()) {
client.shutdown(); // does nothing
}
}
@Test
static void testDefaultShutdownNow() throws Exception {
void testDefaultShutdownNow() throws Exception {
try (HttpClient client = new MockHttpClient()) {
client.shutdownNow(); // calls shutdown, doesn't wait
}
@ -559,18 +560,18 @@ public class HttpClientBuilderTest {
}
// once from shutdownNow(), and once from close()
assertEquals(shutdownCalled.get(), 2);
assertEquals(2, shutdownCalled.get());
}
@Test
static void testDefaultIsTerminated() throws Exception {
void testDefaultIsTerminated() throws Exception {
try (HttpClient client = new MockHttpClient()) {
assertFalse(client.isTerminated());
}
}
@Test
static void testDefaultAwaitTermination() throws Exception {
void testDefaultAwaitTermination() throws Exception {
try (HttpClient client = new MockHttpClient()) {
assertTrue(client.awaitTermination(Duration.ofDays(1)));
}
@ -581,7 +582,7 @@ public class HttpClientBuilderTest {
}
@Test
static void testDefaultClose() {
void testDefaultClose() {
AtomicInteger shutdownCalled = new AtomicInteger();
AtomicInteger awaitTerminationCalled = new AtomicInteger();
AtomicInteger shutdownNowCalled = new AtomicInteger();
@ -616,9 +617,9 @@ public class HttpClientBuilderTest {
// awaitTermination() 0->1 -> false
// awaitTermination() 1->2 -> true
try (HttpClient client = mock) { }
assertEquals(shutdownCalled.get(), 1); // called by close()
assertEquals(shutdownNowCalled.get(), 0); // not called
assertEquals(awaitTerminationCalled.get(), 2); // called by close() twice
assertEquals(1, shutdownCalled.get()); // called by close()
assertEquals(0, shutdownNowCalled.get()); // not called
assertEquals(2, awaitTerminationCalled.get()); // called by close() twice
assertFalse(Thread.currentThread().isInterrupted());
// second time around:
@ -629,9 +630,9 @@ public class HttpClientBuilderTest {
// calls shutdown() 2->3
// awaitTermination() 3->4 -> true
try (HttpClient client = mock) { }
assertEquals(shutdownCalled.get(), 3); // called by close() and shutdownNow()
assertEquals(shutdownNowCalled.get(), 1); // called by close() due to interrupt
assertEquals(awaitTerminationCalled.get(), 4); // called by close twice
assertEquals(3, shutdownCalled.get()); // called by close() and shutdownNow()
assertEquals(1, shutdownNowCalled.get()); // called by close() due to interrupt
assertEquals(4, awaitTerminationCalled.get()); // called by close twice
assertTrue(Thread.currentThread().isInterrupted());
assertTrue(Thread.interrupted());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2026, 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
@ -31,7 +31,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* ReferenceTracker
* @run testng/othervm
* @run junit/othervm
* -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* HttpClientClose
@ -70,10 +70,6 @@ import javax.net.ssl.SSLContext;
import jdk.test.lib.RandomFactory;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
@ -84,10 +80,15 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.ALT_SVC;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class HttpClientClose implements HttpServerAdapters {
@ -96,27 +97,26 @@ public class HttpClientClose implements HttpServerAdapters {
}
static final Random RANDOM = RandomFactory.getRandom();
ExecutorService readerService;
private static ExecutorService readerService;
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer h2h3TestServer; // HTTP/3 ( h2 + h3 )
HttpTestServer h3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String h2h3URI;
String h2h3Head;
String h3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer h2h3TestServer; // HTTP/3 ( h2 + h3 )
private static HttpTestServer h3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String h2h3URI;
private static String h2h3Head;
private static String h3URI;
static final String MESSAGE = "HttpClientClose message body";
static final int ITERATIONS = 3;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ h2h3URI, HTTP_3, h2h3TestServer.h3DiscoveryConfig()},
{ h3URI, HTTP_3, h3TestServer.h3DiscoveryConfig()},
@ -128,7 +128,7 @@ public class HttpClientClose implements HttpServerAdapters {
}
static final AtomicLong requestCounter = new AtomicLong();
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
static String readBody(InputStream body) {
try (InputStream in = body) {
@ -138,7 +138,7 @@ public class HttpClientClose implements HttpServerAdapters {
}
}
private static record CancellingSubscriber<U>(ExchangeResult<?> result)
private record CancellingSubscriber<U>(ExchangeResult<?> result)
implements Subscriber<U> {
@Override
public void onSubscribe(Subscription subscription) {
@ -176,15 +176,15 @@ public class HttpClientClose implements HttpServerAdapters {
boolean firstVersionMayNotMatch) {
static <U> ExchangeResult<U> afterHead(int step, Version version, Http3DiscoveryMode config) {
return new ExchangeResult<U>(step, version, config, null, false);
return new ExchangeResult<>(step, version, config, null, false);
}
static <U> ExchangeResult<U> ofSequential(int step, Version version, Http3DiscoveryMode config) {
return new ExchangeResult<U>(step, version, config, null, true);
return new ExchangeResult<>(step, version, config, null, true);
}
ExchangeResult<T> withResponse(HttpResponse<T> response) {
return new ExchangeResult<T>(step(), version(), config(), response, firstVersionMayNotMatch());
return new ExchangeResult<>(step(), version(), config(), response, firstVersionMayNotMatch());
}
// Ensures that the input stream gets closed in case of assertion
@ -193,11 +193,11 @@ public class HttpClientClose implements HttpServerAdapters {
try {
out.printf("%s: expect status 200 and version %s (%s) for %s%n", step, version, config,
response.request().uri());
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
if (step == 0 && version == HTTP_3 && firstVersionMayNotMatch) {
out.printf("%s: version not checked%n", step);
} else {
assertEquals(response.version(), version);
assertEquals(version, response.version());
out.printf("%s: got expected version %s%n", step, response.version());
}
} catch (AssertionError error) {
@ -227,10 +227,11 @@ public class HttpClientClose implements HttpServerAdapters {
.HEAD()
.build();
var resp = client.send(request, BodyHandlers.discarding());
assertEquals(resp.statusCode(), 200);
assertEquals(200, resp.statusCode());
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testConcurrent(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- starting concurrent (%s, %s, %s) ----%n%n", uriString, version, config);
Throwable failed = null;
@ -266,7 +267,7 @@ public class HttpClientClose implements HttpServerAdapters {
bodyCF = responseCF
.thenApplyAsync((resp) -> readBody(si, resp), readerService)
.thenApply((s) -> {
assertEquals(s, MESSAGE);
assertEquals(MESSAGE, s);
return s;
});
long sleep = RANDOM.nextLong(5);
@ -289,7 +290,8 @@ public class HttpClientClose implements HttpServerAdapters {
failed == null ? "done" : failed.toString());
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testSequential(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- starting sequential (%s, %s, %s) ----%n%n", uriString, version, config);
Throwable failed = null;
@ -320,7 +322,7 @@ public class HttpClientClose implements HttpServerAdapters {
bodyCF = responseCF.thenApplyAsync(HttpResponse::body, readerService)
.thenApply(HttpClientClose::readBody)
.thenApply((s) -> {
assertEquals(s, MESSAGE);
assertEquals(MESSAGE, s);
return s;
})
.thenApply((s) -> {
@ -340,8 +342,8 @@ public class HttpClientClose implements HttpServerAdapters {
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
out.println("\n**** Setup ****\n");
readerService = Executors.newCachedThreadPool();
@ -376,8 +378,8 @@ public class HttpClientClose implements HttpServerAdapters {
h3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
Thread.sleep(100);
AssertionError fail = TRACKER.checkShutdown(5000);
try {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2026, 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
@ -21,8 +21,6 @@
* questions.
*/
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.ProtocolFamily;
import java.net.http.HttpClient;
@ -34,12 +32,15 @@ import java.nio.channels.Channel;
import java.nio.channels.spi.AbstractSelector;
import java.nio.channels.spi.SelectorProvider;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/*
* @test
* @bug 8248006
* @summary The test checks if UncheckedIOException is thrown
* @build HttpClientExceptionTest
* @run testng/othervm -Djava.nio.channels.spi.SelectorProvider=HttpClientExceptionTest$CustomSelectorProvider
* @run junit/othervm -Djava.nio.channels.spi.SelectorProvider=HttpClientExceptionTest$CustomSelectorProvider
* HttpClientExceptionTest
*/
@ -50,8 +51,8 @@ public class HttpClientExceptionTest {
@Test
public void testHttpClientException() {
for(int i = 0; i < ITERATIONS; i++) {
Assert.assertThrows(HttpClient.newBuilder()::build);
Assert.assertThrows(HttpClient::newHttpClient);
Assertions.assertThrows(Throwable.class, HttpClient.newBuilder()::build);
Assertions.assertThrows(Throwable.class, HttpClient::newHttpClient);
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2022, 2026, 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
@ -23,11 +23,6 @@
import jdk.test.lib.net.IPSupport;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.net.ssl.SSLContext;
import java.io.Closeable;
@ -50,6 +45,12 @@ import jdk.httpclient.test.lib.common.HttpServerAdapters;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
* @summary Tests HttpClient usage when configured with a local address to bind
@ -60,7 +61,7 @@ import static java.net.http.HttpClient.Version.HTTP_2;
* @build jdk.test.lib.net.SimpleSSLContext jdk.test.lib.net.IPSupport
* jdk.httpclient.test.lib.common.HttpServerAdapters
*
* @run testng/othervm
* @run junit/othervm
* -Djdk.httpclient.HttpClient.log=frames,ssl,requests,responses,errors
* -Djdk.internal.httpclient.debug=true
* -Dsun.net.httpserver.idleInterval=50000
@ -81,7 +82,7 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters {
private static final AtomicInteger IDS = new AtomicInteger();
// start various HTTP/HTTPS servers that will be invoked against in the tests
@BeforeClass
@BeforeAll
public static void beforeClass() throws Exception {
HttpServerAdapters.HttpTestHandler handler = (exchange) -> {
// the handler receives a request and sends back a 200 response with the
@ -126,7 +127,7 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters {
}
// stop each of the started servers
@AfterClass
@AfterAll
public static void afterClass() throws Exception {
// stop each of the server and accumulate any exception
// that might happen during stop and finally throw
@ -166,8 +167,7 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters {
return prevException;
}
@DataProvider(name = "params")
private Object[][] paramsProvider() throws Exception {
private static Object[][] paramsProvider() throws Exception {
final List<Object[]> testMethodParams = new ArrayList<>();
final URI[] requestURIs = new URI[]{httpURI, httpsURI, http2URI, https2URI};
final Predicate<URI> requiresSSLContext = (uri) -> uri.getScheme().equals("https");
@ -224,7 +224,7 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters {
// An object that holds a client and that can be closed
// Used when closing the client might require closing additional
// resources, such as an executor
sealed interface ClientCloseable extends Closeable {
public sealed interface ClientCloseable extends Closeable {
HttpClient client();
@ -261,7 +261,7 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters {
}
// A supplier of ClientCloseable
sealed interface ClientProvider extends Supplier<ClientCloseable> {
public sealed interface ClientProvider extends Supplier<ClientCloseable> {
ClientCloseable get();
@ -323,7 +323,8 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters {
* seen by the server side handler is the same one as that is set on the
* {@code client}
*/
@Test(dataProvider = "params")
@ParameterizedTest
@MethodSource("paramsProvider")
public void testSend(ClientProvider clientProvider, URI requestURI, InetAddress localAddress) throws Exception {
try (var c = clientProvider.get()) {
HttpClient client = c.client();
@ -332,10 +333,10 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters {
// GET request
var req = HttpRequest.newBuilder(requestURI).build();
var resp = client.send(req, HttpResponse.BodyHandlers.ofByteArray());
Assert.assertEquals(resp.statusCode(), 200, "Unexpected status code");
Assertions.assertEquals(200, resp.statusCode(), "Unexpected status code");
// verify the address only if a specific one was set on the client
if (localAddress != null && !localAddress.isAnyLocalAddress()) {
Assert.assertEquals(resp.body(), localAddress.getAddress(),
Assertions.assertArrayEquals(localAddress.getAddress(), resp.body(),
"Unexpected client address seen by the server handler");
}
}
@ -347,7 +348,8 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters {
* seen by the server side handler is the same one as that is set on the
* {@code client}
*/
@Test(dataProvider = "params")
@ParameterizedTest
@MethodSource("paramsProvider")
public void testSendAsync(ClientProvider clientProvider, URI requestURI, InetAddress localAddress) throws Exception {
try (var c = clientProvider.get()) {
HttpClient client = c.client();
@ -359,10 +361,10 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters {
var cf = client.sendAsync(req,
HttpResponse.BodyHandlers.ofByteArray());
var resp = cf.get();
Assert.assertEquals(resp.statusCode(), 200, "Unexpected status code");
Assertions.assertEquals(200, resp.statusCode(), "Unexpected status code");
// verify the address only if a specific one was set on the client
if (localAddress != null && !localAddress.isAnyLocalAddress()) {
Assert.assertEquals(resp.body(), localAddress.getAddress(),
Assertions.assertArrayEquals(localAddress.getAddress(), resp.body(),
"Unexpected client address seen by the server handler");
}
}
@ -374,7 +376,8 @@ public class HttpClientLocalAddrTest implements HttpServerAdapters {
* is used when multiple concurrent threads are involved in sending requests from
* the {@code client}
*/
@Test(dataProvider = "params")
@ParameterizedTest
@MethodSource("paramsProvider")
public void testMultiSendRequests(ClientProvider clientProvider,
URI requestURI,
InetAddress localAddress) throws Exception {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2026, 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
@ -32,7 +32,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* ReferenceTracker
* @run testng/othervm
* @run junit/othervm
* -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* HttpClientShutdown
@ -74,10 +74,6 @@ import javax.net.ssl.SSLContext;
import jdk.test.lib.RandomFactory;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
@ -88,10 +84,15 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.ALT_SVC;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class HttpClientShutdown implements HttpServerAdapters {
@ -100,27 +101,26 @@ public class HttpClientShutdown implements HttpServerAdapters {
}
static final Random RANDOM = RandomFactory.getRandom();
ExecutorService readerService;
private static ExecutorService readerService;
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer h2h3TestServer; // HTTP/3 ( h2 + h3 )
HttpTestServer h3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String h2h3URI;
String h2h3Head;
String h3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer h2h3TestServer; // HTTP/3 ( h2 + h3 )
private static HttpTestServer h3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String h2h3URI;
private static String h2h3Head;
private static String h3URI;
static final String MESSAGE = "HttpClientShutdown message body";
static final int ITERATIONS = 3;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ h2h3URI, HTTP_3, h2h3TestServer.h3DiscoveryConfig()},
{ h3URI, HTTP_3, h3TestServer.h3DiscoveryConfig()},
@ -216,11 +216,11 @@ public class HttpClientShutdown implements HttpServerAdapters {
try {
out.printf(now() + "%s: expect status 200 and version %s (%s) for %s%n", step, version, config,
response.request().uri());
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
if (step == 0 && version == HTTP_3 && firstVersionMayNotMatch) {
out.printf(now() + "%s: version not checked%n", step);
} else {
assertEquals(response.version(), version);
assertEquals(version, response.version());
out.printf(now() + "%s: got expected version %s%n", step, response.version());
}
} catch (AssertionError error) {
@ -238,7 +238,7 @@ public class HttpClientShutdown implements HttpServerAdapters {
.HEAD()
.build();
var resp = client.send(request, BodyHandlers.discarding());
assertEquals(resp.statusCode(), 200);
assertEquals(200, resp.statusCode());
}
static boolean hasExpectedMessage(IOException io) {
@ -272,7 +272,8 @@ public class HttpClientShutdown implements HttpServerAdapters {
throw new AssertionError(what + ": Unexpected exception: " + cause, cause);
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testConcurrent(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- %sstarting concurrent (%s, %s, %s) ----%n%n",
now(), uriString, version, config);
@ -310,7 +311,7 @@ public class HttpClientShutdown implements HttpServerAdapters {
bodyCF = responseCF.thenApplyAsync(HttpResponse::body, readerService)
.thenApply(HttpClientShutdown::readBody)
.thenApply((s) -> {
assertEquals(s, MESSAGE);
assertEquals(MESSAGE, s);
out.println(now() + si +": Got expected message: " + s);
return s;
});
@ -375,7 +376,8 @@ public class HttpClientShutdown implements HttpServerAdapters {
return failed;
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testSequential(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- %sstarting sequential (%s, %s, %s) ----%n%n",
now(), uriString, version, config);
@ -409,7 +411,7 @@ public class HttpClientShutdown implements HttpServerAdapters {
bodyCF = responseCF.thenApplyAsync(HttpResponse::body, readerService)
.thenApply(HttpClientShutdown::readBody)
.thenApply((s) -> {
assertEquals(s, MESSAGE);
assertEquals(MESSAGE, s);
return s;
})
.thenApply((s) -> {
@ -461,8 +463,8 @@ public class HttpClientShutdown implements HttpServerAdapters {
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
out.println("\n**** Setup ****\n");
readerService = Executors.newCachedThreadPool();
@ -498,8 +500,8 @@ public class HttpClientShutdown implements HttpServerAdapters {
start = System.nanoTime();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
Thread.sleep(100);
AssertionError fail = TRACKER.checkShutdown(5000);
try {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -24,7 +24,7 @@
/*
* @test
* @summary Tests for HttpHeaders.of factory method
* @run testng HttpHeadersOf
* @run junit HttpHeadersOf
*/
import java.net.http.HttpHeaders;
@ -33,13 +33,16 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.function.BiPredicate;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class HttpHeadersOf {
@ -59,12 +62,12 @@ public class HttpHeadersOf {
@Override public String toString() { return "REJECT_ALL"; }
};
@DataProvider(name = "predicates")
public Object[][] predicates() {
public static Object[][] predicates() {
return new Object[][] { { ACCEPT_ALL }, { REJECT_ALL } };
}
@Test(dataProvider = "predicates")
@ParameterizedTest
@MethodSource("predicates")
public void testNull(BiPredicate<String,String> filter) {
assertThrows(NPE, () -> HttpHeaders.of(null, null));
assertThrows(NPE, () -> HttpHeaders.of(null, filter));
@ -80,8 +83,7 @@ public class HttpHeadersOf {
}
@DataProvider(name = "filterMaps")
public Object[][] filterMaps() {
public static Object[][] filterMaps() {
List<Map<String, List<String>>> maps = List.of(
Map.of("A", List.of("B"), "X", List.of("Y", "Z")),
Map.of("A", List.of("B", "C"), "X", List.of("Y", "Z")),
@ -90,33 +92,33 @@ public class HttpHeadersOf {
return maps.stream().map(p -> new Object[] { p }).toArray(Object[][]::new);
}
@Test(dataProvider = "filterMaps")
@ParameterizedTest
@MethodSource("filterMaps")
public void testFilter(Map<String,List<String>> map) {
HttpHeaders headers = HttpHeaders.of(map, REJECT_ALL);
assertEquals(headers.map().size(), 0);
assertEquals(0, headers.map().size());
assertFalse(headers.firstValue("A").isPresent());
assertEquals(headers.allValues("A").size(), 0);
assertEquals(0, headers.allValues("A").size());
headers = HttpHeaders.of(map, (name, value) -> {
if (name.equals("A")) return true; else return false; });
assertEquals(headers.map().size(), 1);
assertEquals(1, headers.map().size());
assertTrue(headers.firstValue("A").isPresent());
assertEquals(headers.allValues("A"), map.get("A"));
assertEquals(headers.allValues("A").size(), map.get("A").size());
assertEquals(map.get("A"), headers.allValues("A"));
assertEquals(map.get("A").size(), headers.allValues("A").size());
assertFalse(headers.firstValue("X").isPresent());
headers = HttpHeaders.of(map, (name, value) -> {
if (name.equals("X")) return true; else return false; });
assertEquals(headers.map().size(), 1);
assertEquals(1, headers.map().size());
assertTrue(headers.firstValue("X").isPresent());
assertEquals(headers.allValues("X"), map.get("X"));
assertEquals(headers.allValues("X").size(), map.get("X").size());
assertEquals(map.get("X"), headers.allValues("X"));
assertEquals(map.get("X").size(), headers.allValues("X").size());
assertFalse(headers.firstValue("A").isPresent());
}
@DataProvider(name = "mapValues")
public Object[][] mapValues() {
public static Object[][] mapValues() {
List<Map<String, List<String>>> maps = List.of(
Map.of("A", List.of("B")),
Map.of("A", List.of("B", "C")),
@ -137,18 +139,19 @@ public class HttpHeadersOf {
return maps.stream().map(p -> new Object[] { p }).toArray(Object[][]::new);
}
@Test(dataProvider = "mapValues")
@ParameterizedTest
@MethodSource("mapValues")
public void testMapValues(Map<String,List<String>> map) {
HttpHeaders headers = HttpHeaders.of(map, ACCEPT_ALL);
assertEquals(headers.map().size(), map.size());
assertEquals(map.size(), headers.map().size());
assertTrue(headers.firstValue("A").isPresent());
assertTrue(headers.firstValue("a").isPresent());
assertEquals(headers.firstValue("A").get(), "B");
assertEquals(headers.firstValue("a").get(), "B");
assertEquals(headers.allValues("A"), map.get("A"));
assertEquals(headers.allValues("a"), map.get("A"));
assertEquals(headers.allValues("F").size(), 0);
assertEquals("B", headers.firstValue("A").get());
assertEquals("B", headers.firstValue("a").get());
assertEquals(map.get("A"), headers.allValues("A"));
assertEquals(map.get("A"), headers.allValues("a"));
assertEquals(0, headers.allValues("F").size());
assertTrue(headers.map().get("A").contains("B"));
assertFalse(headers.map().get("A").contains("F"));
assertThrows(NFE, () -> headers.firstValueAsLong("A"));
@ -167,8 +170,7 @@ public class HttpHeadersOf {
}
@DataProvider(name = "caseInsensitivity")
public Object[][] caseInsensitivity() {
public static Object[][] caseInsensitivity() {
List<Map<String, List<String>>> maps = List.of(
Map.of("Accept-Encoding", List.of("gzip, deflate")),
Map.of("accept-encoding", List.of("gzip, deflate")),
@ -179,7 +181,8 @@ public class HttpHeadersOf {
return maps.stream().map(p -> new Object[] { p }).toArray(Object[][]::new);
}
@Test(dataProvider = "caseInsensitivity")
@ParameterizedTest
@MethodSource("caseInsensitivity")
public void testCaseInsensitivity(Map<String,List<String>> map) {
HttpHeaders headers = HttpHeaders.of(map, ACCEPT_ALL);
@ -187,11 +190,11 @@ public class HttpHeadersOf {
"aCCept-EnCODing", "accepT-encodinG")) {
assertTrue(headers.firstValue(name).isPresent());
assertTrue(headers.allValues(name).contains("gzip, deflate"));
assertEquals(headers.firstValue(name).get(), "gzip, deflate");
assertEquals(headers.allValues(name).size(), 1);
assertEquals(headers.map().size(), 1);
assertEquals(headers.map().get(name).size(), 1);
assertEquals(headers.map().get(name).get(0), "gzip, deflate");
assertEquals("gzip, deflate", headers.firstValue(name).get());
assertEquals(1, headers.allValues(name).size());
assertEquals(1, headers.map().size());
assertEquals(1, headers.map().get(name).size());
assertEquals("gzip, deflate", headers.map().get(name).get(0));
}
}
@ -212,8 +215,8 @@ public class HttpHeadersOf {
HttpHeaders h2 = HttpHeaders.of(m2, ACCEPT_ALL);
if (!m1.equals(m2)) mapDiffer++;
if (m1.hashCode() != m2.hashCode()) mapHashDiffer++;
assertEquals(h1, h2, "HttpHeaders differ");
assertEquals(h1.hashCode(), h2.hashCode(),
assertEquals(h2, h1, "HttpHeaders differ");
assertEquals(h2.hashCode(), h1.hashCode(),
"hashCode differ for " + List.of(m1,m2));
}
}
@ -221,8 +224,7 @@ public class HttpHeadersOf {
assertTrue(mapHashDiffer > 0, "all maps had same hashCode!");
}
@DataProvider(name = "valueAsLong")
public Object[][] valueAsLong() {
public static Object[][] valueAsLong() {
return new Object[][] {
new Object[] { Map.of("Content-Length", List.of("10")), 10l },
new Object[] { Map.of("Content-Length", List.of("101")), 101l },
@ -232,15 +234,15 @@ public class HttpHeadersOf {
};
}
@Test(dataProvider = "valueAsLong")
@ParameterizedTest
@MethodSource("valueAsLong")
public void testValueAsLong(Map<String,List<String>> map, long expected) {
HttpHeaders headers = HttpHeaders.of(map, ACCEPT_ALL);
assertEquals(headers.firstValueAsLong("Content-Length").getAsLong(), expected);
assertEquals(expected, headers.firstValueAsLong("Content-Length").getAsLong());
}
@DataProvider(name = "duplicateNames")
public Object[][] duplicateNames() {
public static Object[][] duplicateNames() {
List<Map<String, List<String>>> maps = List.of(
Map.of("X-name", List.of(),
"x-name", List.of()),
@ -262,7 +264,8 @@ public class HttpHeadersOf {
return maps.stream().map(p -> new Object[] { p }).toArray(Object[][]::new);
}
@Test(dataProvider = "duplicateNames")
@ParameterizedTest
@MethodSource("duplicateNames")
public void testDuplicates(Map<String,List<String>> map) {
HttpHeaders headers;
try {
@ -275,8 +278,7 @@ public class HttpHeadersOf {
}
@DataProvider(name = "noSplittingJoining")
public Object[][] noSplittingJoining() {
public static Object[][] noSplittingJoining() {
List<Map<String, List<String>>> maps = List.of(
Map.of("A", List.of("B")),
Map.of("A", List.of("B", "C")),
@ -296,24 +298,24 @@ public class HttpHeadersOf {
return maps.stream().map(p -> new Object[] { p }).toArray(Object[][]::new);
}
@Test(dataProvider = "noSplittingJoining")
@ParameterizedTest
@MethodSource("noSplittingJoining")
public void testNoSplittingJoining(Map<String,List<String>> map) {
HttpHeaders headers = HttpHeaders.of(map, ACCEPT_ALL);
Map<String,List<String>> headersMap = headers.map();
assertEquals(headers.map().size(), map.size());
assertEquals(map.size(), headers.map().size());
for (Map.Entry<String,List<String>> entry : map.entrySet()) {
String headerName = entry.getKey();
List<String> headerValues = entry.getValue();
assertEquals(headerValues, headersMap.get(headerName));
assertEquals(headerValues, headers.allValues(headerName));
assertEquals(headerValues.get(0), headers.firstValue(headerName).get());
assertEquals(headersMap.get(headerName), headerValues);
assertEquals(headers.allValues(headerName), headerValues);
assertEquals(headers.firstValue(headerName).get(), headerValues.get(0));
}
}
@DataProvider(name = "trimming")
public Object[][] trimming() {
public static Object[][] trimming() {
List<Map<String, List<String>>> maps = List.of(
Map.of("A", List.of("B")),
Map.of(" A", List.of("B")),
@ -331,23 +333,23 @@ public class HttpHeadersOf {
return maps.stream().map(p -> new Object[] { p }).toArray(Object[][]::new);
}
@Test(dataProvider = "trimming")
@ParameterizedTest
@MethodSource("trimming")
public void testTrimming(Map<String,List<String>> map) {
HttpHeaders headers = HttpHeaders.of(map, (name, value) -> {
assertEquals(name, "A");
assertEquals(value, "B");
assertEquals("A", name);
assertEquals("B", value);
return true;
});
assertEquals(headers.map().size(), 1);
assertEquals(headers.firstValue("A").get(), "B");
assertEquals(headers.allValues("A"), List.of("B"));
assertTrue(headers.map().get("A").equals(List.of("B")));
assertEquals(1, headers.map().size());
assertEquals("B", headers.firstValue("A").get());
assertEquals(List.of("B"), headers.allValues("A"));
assertEquals(List.of("B"), headers.map().get("A"));
}
@DataProvider(name = "emptyKey")
public Object[][] emptyKey() {
public static Object[][] emptyKey() {
List<Map<String, List<String>>> maps = List.of(
Map.of("", List.of("B")),
Map.of(" ", List.of("B")),
@ -358,7 +360,8 @@ public class HttpHeadersOf {
return maps.stream().map(p -> new Object[] { p }).toArray(Object[][]::new);
}
@Test(dataProvider = "emptyKey")
@ParameterizedTest
@MethodSource("emptyKey")
public void testEmptyKey(Map<String,List<String>> map) {
HttpHeaders headers;
try {
@ -371,8 +374,7 @@ public class HttpHeadersOf {
}
@DataProvider(name = "emptyValue")
public Object[][] emptyValue() {
public static Object[][] emptyValue() {
List<Map<String, List<String>>> maps = List.of(
Map.of("A", List.of("")),
Map.of("A", List.of("", "")),
@ -383,40 +385,41 @@ public class HttpHeadersOf {
return maps.stream().map(p -> new Object[] { p }).toArray(Object[][]::new);
}
@Test(dataProvider = "emptyValue")
@ParameterizedTest
@MethodSource("emptyValue")
public void testEmptyValue(Map<String,List<String>> map) {
HttpHeaders headers = HttpHeaders.of(map, (name, value) -> {
assertEquals(value, "");
assertEquals("", value);
return true;
});
assertEquals(headers.map().size(), map.size());
assertEquals(headers.map().get("A").get(0), "");
headers.allValues("A").forEach(v -> assertEquals(v, ""));
assertEquals(headers.firstValue("A").get(), "");
assertEquals(map.size(), headers.map().size());
assertEquals("", headers.map().get("A").get(0));
headers.allValues("A").forEach(v -> assertEquals("", v));
assertEquals("", headers.firstValue("A").get());
}
@DataProvider(name = "noValues")
public Object[][] noValues() {
public static Object[][] noValues() {
List<Map<String, List<String>>> maps = List.of(
Map.of("A", List.of()),
Map.of("A", List.of(), "B", List.of()),
Map.of("A", List.of(), "B", List.of(), "C", List.of()),
Map.of("A", new ArrayList()),
Map.of("A", new LinkedList())
Map.of("A", new ArrayList<>()),
Map.of("A", new LinkedList<>())
);
return maps.stream().map(p -> new Object[] { p }).toArray(Object[][]::new);
}
@Test(dataProvider = "noValues")
@ParameterizedTest
@MethodSource("noValues")
public void testNoValues(Map<String,List<String>> map) {
HttpHeaders headers = HttpHeaders.of(map, (name, value) -> {
fail("UNEXPECTED call to filter");
return true;
});
assertEquals(headers.map().size(), 0);
assertEquals(headers.map().get("A"), null);
assertEquals(headers.allValues("A").size(), 0);
assertEquals(0, headers.map().size());
assertNull(headers.map().get("A"));
assertEquals(0, headers.allValues("A").size());
assertFalse(headers.firstValue("A").isPresent());
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2019, 2026, 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
@ -23,16 +23,13 @@
import com.sun.net.httpserver.HttpsServer;
import jdk.httpclient.test.lib.common.TestServerConfigurator;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.AfterClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static org.testng.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
import javax.net.ssl.SSLContext;
import java.io.IOException;
@ -63,7 +60,12 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
/**
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
* @bug 8232625
* @summary This test verifies that the HttpClient works correctly when redirecting a post request.
@ -71,7 +73,7 @@ import jdk.httpclient.test.lib.common.HttpServerAdapters;
* @build jdk.test.lib.net.SimpleSSLContext DigestEchoServer HttpRedirectTest
* jdk.httpclient.test.lib.common.HttpServerAdapters
* jdk.httpclient.test.lib.common.TestServerConfigurator
* @run testng/othervm -Dtest.requiresHost=true
* @run junit/othervm -Dtest.requiresHost=true
* -Djdk.httpclient.HttpClient.log=headers
* -Djdk.internal.httpclient.debug=false
* HttpRedirectTest
@ -85,33 +87,30 @@ public class HttpRedirectTest implements HttpServerAdapters {
SSLContext.setDefault(context);
}
final AtomicLong requestCounter = new AtomicLong();
final AtomicLong responseCounter = new AtomicLong();
HttpTestServer http1Server;
HttpTestServer http2Server;
HttpTestServer https1Server;
HttpTestServer https2Server;
HttpTestServer http3Server;
DigestEchoServer.TunnelingProxy proxy;
static final AtomicLong requestCounter = new AtomicLong();
private static HttpTestServer http1Server;
private static HttpTestServer http2Server;
private static HttpTestServer https1Server;
private static HttpTestServer https2Server;
private static HttpTestServer http3Server;
private static DigestEchoServer.TunnelingProxy proxy;
URI http1URI;
URI https1URI;
URI http2URI;
URI https2URI;
URI http3URI;
InetSocketAddress proxyAddress;
ProxySelector proxySelector;
HttpClient client;
List<CompletableFuture<?>> futures = new CopyOnWriteArrayList<>();
Set<URI> pending = new CopyOnWriteArraySet<>();
private static URI http1URI;
private static URI https1URI;
private static URI http2URI;
private static URI https2URI;
private static URI http3URI;
private static InetSocketAddress proxyAddress;
private static ProxySelector proxySelector;
private static HttpClient client;
final ExecutorService executor = new ThreadPoolExecutor(12, 60, 10,
static final ExecutorService executor = new ThreadPoolExecutor(12, 60, 10,
TimeUnit.SECONDS, new LinkedBlockingQueue<>()); // Shared by HTTP/1.1 servers
final ExecutorService clientexec = new ThreadPoolExecutor(6, 12, 1,
static final ExecutorService clientexec = new ThreadPoolExecutor(6, 12, 1,
TimeUnit.SECONDS, new LinkedBlockingQueue<>()); // Used by the client
public HttpClient newHttpClient(ProxySelector ps) {
HttpClient.Builder builder = newClientBuilderForH3()
public static HttpClient newHttpClient(ProxySelector ps) {
HttpClient.Builder builder = HttpServerAdapters.createClientBuilderForH3()
.sslContext(context)
.executor(clientexec)
.followRedirects(HttpClient.Redirect.ALWAYS)
@ -119,8 +118,7 @@ public class HttpRedirectTest implements HttpServerAdapters {
return builder.build();
}
@DataProvider(name="uris")
Object[][] testURIs() throws URISyntaxException {
static Object[][] testURIs() {
List<URI> uris = List.of(
http3URI.resolve("direct/orig/"),
http1URI.resolve("direct/orig/"),
@ -144,12 +142,11 @@ public class HttpRedirectTest implements HttpServerAdapters {
);
Object[][] tests = new Object[redirects.size() * uris.size()][3];
int count = 0;
for (int i=0; i < uris.size(); i++) {
URI u = uris.get(i);
for (int j=0; j < redirects.size() ; j++) {
int code = redirects.get(j).getKey();
String m = redirects.get(j).getValue();
tests[count][0] = u.resolve(code +"/");
for (URI u : uris) {
for (Map.Entry<Integer, String> redirect : redirects) {
int code = redirect.getKey();
String m = redirect.getValue();
tests[count][0] = u.resolve(code + "/");
tests[count][1] = code;
tests[count][2] = m;
count++;
@ -158,8 +155,8 @@ public class HttpRedirectTest implements HttpServerAdapters {
return tests;
}
@BeforeClass
public void setUp() throws Exception {
@BeforeAll
public static void setUp() throws Exception {
try {
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
@ -208,10 +205,8 @@ public class HttpRedirectTest implements HttpServerAdapters {
proxySelector = new HttpProxySelector(proxyAddress);
client = newHttpClient(proxySelector);
System.out.println("Setup: done");
} catch (Exception x) {
} catch (Exception | Error x) {
tearDown(); throw x;
} catch (Error e) {
tearDown(); throw e;
}
}
@ -222,19 +217,19 @@ public class HttpRedirectTest implements HttpServerAdapters {
client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
HttpResponse<String> resp = respCf.join();
if (method.equals("DO_NOT_FOLLOW")) {
assertEquals(resp.statusCode(), code, u + ": status code");
assertEquals(code, resp.statusCode(), u + ": status code");
} else {
assertEquals(resp.statusCode(), 200, u + ": status code");
assertEquals(200, resp.statusCode(), u + ": status code");
}
if (method.equals("POST")) {
assertEquals(resp.body(), REQUEST_BODY, u + ": body");
assertEquals(REQUEST_BODY, resp.body(), u + ": body");
} else if (code == 304) {
assertEquals(resp.body(), "", u + ": body");
assertEquals("", resp.body(), u + ": body");
} else if (method.equals("DO_NOT_FOLLOW")) {
assertNotEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
assertNotEquals(resp.body(), REQUEST_BODY, u + ": body");
assertNotEquals(GET_RESPONSE_BODY, resp.body(), u + ": body");
assertNotEquals(REQUEST_BODY, resp.body(), u + ": body");
} else {
assertEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
assertEquals(GET_RESPONSE_BODY, resp.body(), u + ": body");
}
}
@ -244,21 +239,21 @@ public class HttpRedirectTest implements HttpServerAdapters {
client.sendAsync(request, HttpResponse.BodyHandlers.ofString());
HttpResponse<String> resp = respCf.join();
if (method.equals("DO_NOT_FOLLOW")) {
assertEquals(resp.statusCode(), code, u + ": status code");
assertEquals(code, resp.statusCode(), u + ": status code");
} else {
assertEquals(resp.statusCode(), 200, u + ": status code");
assertEquals(200, resp.statusCode(), u + ": status code");
}
if (method.equals("POST")) {
assertEquals(resp.body(), REQUEST_BODY, u + ": body");
assertEquals(REQUEST_BODY, resp.body(), u + ": body");
} else if (code == 304) {
assertEquals(resp.body(), "", u + ": body");
assertEquals("", resp.body(), u + ": body");
} else if (method.equals("DO_NOT_FOLLOW")) {
assertNotEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
assertNotEquals(resp.body(), REQUEST_BODY, u + ": body");
assertNotEquals(GET_RESPONSE_BODY, resp.body(), u + ": body");
assertNotEquals(REQUEST_BODY, resp.body(), u + ": body");
} else if (code == 303) {
assertEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
assertEquals(GET_RESPONSE_BODY, resp.body(), u + ": body");
} else {
assertEquals(resp.body(), REQUEST_BODY, u + ": body");
assertEquals(REQUEST_BODY, resp.body(), u + ": body");
}
}
@ -270,7 +265,8 @@ public class HttpRedirectTest implements HttpServerAdapters {
return builder;
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("testURIs")
public void testPOST(URI uri, int code, String method) throws Exception {
URI u = uri.resolve("foo?n=" + requestCounter.incrementAndGet());
HttpRequest request = newRequestBuilder(u)
@ -279,7 +275,8 @@ public class HttpRedirectTest implements HttpServerAdapters {
testNonIdempotent(u, request, code, method);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("testURIs")
public void testPUT(URI uri, int code, String method) throws Exception {
URI u = uri.resolve("foo?n=" + requestCounter.incrementAndGet());
System.out.println("Testing with " + u);
@ -289,7 +286,8 @@ public class HttpRedirectTest implements HttpServerAdapters {
testIdempotent(u, request, code, method);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("testURIs")
public void testFoo(URI uri, int code, String method) throws Exception {
URI u = uri.resolve("foo?n=" + requestCounter.incrementAndGet());
System.out.println("Testing with " + u);
@ -300,7 +298,8 @@ public class HttpRedirectTest implements HttpServerAdapters {
testIdempotent(u, request, code, method);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("testURIs")
public void testGet(URI uri, int code, String method) throws Exception {
URI u = uri.resolve("foo?n=" + requestCounter.incrementAndGet());
System.out.println("Testing with " + u);
@ -312,24 +311,24 @@ public class HttpRedirectTest implements HttpServerAdapters {
HttpResponse<String> resp = respCf.join();
// body will be preserved except for 304 and 303: this is a GET.
if (method.equals("DO_NOT_FOLLOW")) {
assertEquals(resp.statusCode(), code, u + ": status code");
assertEquals(code, resp.statusCode(), u + ": status code");
} else {
assertEquals(resp.statusCode(), 200, u + ": status code");
assertEquals(200, resp.statusCode(), u + ": status code");
}
if (code == 304) {
assertEquals(resp.body(), "", u + ": body");
assertEquals("", resp.body(), u + ": body");
} else if (method.equals("DO_NOT_FOLLOW")) {
assertNotEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
assertNotEquals(resp.body(), REQUEST_BODY, u + ": body");
assertNotEquals(GET_RESPONSE_BODY, resp.body(), u + ": body");
assertNotEquals(REQUEST_BODY, resp.body(), u + ": body");
} else if (code == 303) {
assertEquals(resp.body(), GET_RESPONSE_BODY, u + ": body");
assertEquals(GET_RESPONSE_BODY, resp.body(), u + ": body");
} else {
assertEquals(resp.body(), REQUEST_BODY, u + ": body");
assertEquals(REQUEST_BODY, resp.body(), u + ": body");
}
}
@AfterClass
public void tearDown() {
@AfterAll
public static void tearDown() {
proxy = stop(proxy, DigestEchoServer.TunnelingProxy::stop);
http1Server = stop(http1Server, HttpTestServer::stop);
https1Server = stop(https1Server, HttpTestServer::stop);
@ -355,7 +354,7 @@ public class HttpRedirectTest implements HttpServerAdapters {
private interface Stoppable<T> { public void stop(T service) throws Exception; }
static <T> T stop(T service, Stoppable<T> stop) {
try { if (service != null) stop.stop(service); } catch (Throwable x) { };
try { if (service != null) stop.stop(service); } catch (Throwable x) { }
return null;
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2026, 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
@ -44,19 +44,21 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.ALT_SVC;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.Assertions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/**
/*
* @test
* @bug 8252304 8276559
* @summary HttpRequest.newBuilder(HttpRequest) API and behaviour checks
* @run testng/othervm HttpRequestNewBuilderTest
* @run junit/othervm HttpRequestNewBuilderTest
*/
public class HttpRequestNewBuilderTest {
static final Class<NullPointerException> NPE = NullPointerException.class;
@ -64,21 +66,19 @@ public class HttpRequestNewBuilderTest {
record NamedAssertion(String name, BiConsumer<HttpRequest, HttpRequest> test) { }
List<NamedAssertion> REQUEST_ASSERTIONS = List.of(
new NamedAssertion("uri", (r1, r2) -> assertEquals(r1.uri(), r2.uri())),
new NamedAssertion("timeout", (r1, r2) -> assertEquals(r1.timeout(), r2.timeout())),
new NamedAssertion("version", (r1, r2) -> assertEquals(r1.version(), r2.version())),
new NamedAssertion("headers", (r1, r2) -> assertEquals(r1.headers(), r2.headers())),
new NamedAssertion("options", (r1, r2) -> assertEquals(r1.getOption(H3_DISCOVERY), r2.getOption(H3_DISCOVERY))),
new NamedAssertion("expectContinue", (r1, r2) -> assertEquals(r1.expectContinue(), r2.expectContinue())),
static List<NamedAssertion> REQUEST_ASSERTIONS = List.of(new NamedAssertion("uri", (r1, r2) -> assertEquals(r2.uri(), r1.uri())),
new NamedAssertion("timeout", (r1, r2) -> assertEquals(r2.timeout(), r1.timeout())),
new NamedAssertion("version", (r1, r2) -> assertEquals(r2.version(), r1.version())),
new NamedAssertion("headers", (r1, r2) -> assertEquals(r2.headers(), r1.headers())),
new NamedAssertion("options", (r1, r2) -> assertEquals(r2.getOption(H3_DISCOVERY), r1.getOption(H3_DISCOVERY))),
new NamedAssertion("expectContinue", (r1, r2) -> assertEquals(r2.expectContinue(), r1.expectContinue())),
new NamedAssertion("method", (r1, r2) -> {
assertEquals(r1.method(), r2.method());
assertEquals(r2.method(), r1.method());
assertBodyPublisherEqual(r1, r2);
})
);
@DataProvider(name = "testRequests")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ HttpRequest.newBuilder(URI.create("https://uri-1/")).build() },
{ HttpRequest.newBuilder(URI.create("https://version-1/")).version(HTTP_1_1).build() },
@ -152,14 +152,14 @@ public class HttpRequestNewBuilderTest {
}
// test methods
void assertBodyPublisherEqual(HttpRequest r1, HttpRequest r2) {
static void assertBodyPublisherEqual(HttpRequest r1, HttpRequest r2) {
if (r1.bodyPublisher().isPresent()) {
assertTrue(r2.bodyPublisher().isPresent());
var bp1 = r1.bodyPublisher().get();
var bp2 = r2.bodyPublisher().get();
assertEquals(bp1.getClass(), bp2.getClass());
assertEquals(bp1.contentLength(), bp2.contentLength());
assertEquals(bp2.getClass(), bp1.getClass());
assertEquals(bp2.contentLength(), bp1.contentLength());
final class TestSubscriber implements Flow.Subscriber<ByteBuffer> {
final BodySubscriber<String> s;
@ -181,7 +181,7 @@ public class HttpRequestNewBuilderTest {
bp2.subscribe(new TestSubscriber(bs2));
var b2 = bs2.getBody().toCompletableFuture().join().getBytes();
assertEquals(b1, b2);
Assertions.assertArrayEquals(b2, b1);
} else {
assertFalse(r2.bodyPublisher().isPresent());
}
@ -199,9 +199,9 @@ public class HttpRequestNewBuilderTest {
var r = HttpRequest.newBuilder(request, (n, v) -> true)
.method(methodName, HttpRequest.BodyPublishers.ofString("testData"))
.build();
assertEquals(r.method(), methodName);
assertEquals(methodName, r.method());
assertTrue(r.bodyPublisher().isPresent());
assertEquals(r.bodyPublisher().get().contentLength(), 8);
assertEquals(8, r.bodyPublisher().get().contentLength());
assertAllOtherElementsEqual(r, request, "method");
// method w/o body
@ -209,9 +209,9 @@ public class HttpRequestNewBuilderTest {
var r1 = HttpRequest.newBuilder(request, (n, v) -> true)
.method(methodName, noBodyPublisher)
.build();
assertEquals(r1.method(), methodName);
assertEquals(methodName, r1.method());
assertTrue(r1.bodyPublisher().isPresent());
assertEquals(r1.bodyPublisher().get(), noBodyPublisher);
assertEquals(noBodyPublisher, r1.bodyPublisher().get());
assertAllOtherElementsEqual(r1, request, "method");
}
@ -223,113 +223,125 @@ public class HttpRequestNewBuilderTest {
assertThrows(NPE, () -> HttpRequest.newBuilder(null, null));
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
void testBuilder(HttpRequest request) {
var r = HttpRequest.newBuilder(request, (n, v) -> true).build();
assertEquals(r, request);
assertEquals(request, r);
assertAllOtherElementsEqual(r, request);
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testURI(HttpRequest request) {
URI newURI = URI.create("http://www.newURI.com/");
var r = HttpRequest.newBuilder(request, (n, v) -> true).uri(newURI).build();
assertEquals(r.uri(), newURI);
assertEquals(newURI, r.uri());
assertAllOtherElementsEqual(r, request, "uri");
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testTimeout(HttpRequest request) {
var r = HttpRequest.newBuilder(request, (n, v) -> true).timeout(Duration.ofSeconds(2)).build();
assertEquals(r.timeout().get().getSeconds(), 2);
assertEquals(2, r.timeout().get().getSeconds());
assertAllOtherElementsEqual(r, request, "timeout");
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testVersion(HttpRequest request) {
var r = HttpRequest.newBuilder(request, (n, v) -> true).version(HTTP_1_1).build();
assertEquals(r.version().get(), HTTP_1_1);
assertEquals(HTTP_1_1, r.version().get());
assertAllOtherElementsEqual(r, request, "version");
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testGET(HttpRequest request) {
var r = HttpRequest.newBuilder(request, (n, v) -> true)
.GET()
.build();
assertEquals(r.method(), "GET");
assertEquals("GET", r.method());
assertTrue(r.bodyPublisher().isEmpty());
assertAllOtherElementsEqual(r, request, "method");
testBodyPublisher("GET", request);
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testDELETE(HttpRequest request) {
var r = HttpRequest.newBuilder(request, (n, v) -> true)
.DELETE()
.build();
assertEquals(r.method(), "DELETE");
assertEquals("DELETE", r.method());
assertTrue(r.bodyPublisher().isEmpty());
assertAllOtherElementsEqual(r, request, "method");
testBodyPublisher("DELETE", request);
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testPOST(HttpRequest request) {
var r = HttpRequest.newBuilder(request, (n, v) -> true)
.POST(HttpRequest.BodyPublishers.ofString("testData"))
.build();
assertEquals(r.method(), "POST");
assertEquals("POST", r.method());
assertTrue(r.bodyPublisher().isPresent());
assertEquals(r.bodyPublisher().get().contentLength(), 8);
assertEquals(8, r.bodyPublisher().get().contentLength());
assertAllOtherElementsEqual(r, request, "method");
testBodyPublisher("POST", request);
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testPUT(HttpRequest request) {
var r = HttpRequest.newBuilder(request, (n, v) -> true)
.PUT(HttpRequest.BodyPublishers.ofString("testData"))
.build();
assertEquals(r.method(), "PUT");
assertEquals("PUT", r.method());
assertTrue(r.bodyPublisher().isPresent());
assertEquals(r.bodyPublisher().get().contentLength(), 8);
assertEquals(8, r.bodyPublisher().get().contentLength());
assertAllOtherElementsEqual(r, request, "method");
testBodyPublisher("PUT", request);
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testUserDefinedMethod(HttpRequest request) {
testBodyPublisher("TEST", request);
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testAddHeader(HttpRequest request) {
BiPredicate<String, String> filter = (n, v) -> true;
var r = HttpRequest.newBuilder(request, filter).headers("newName", "newValue").build();
assertEquals(r.headers().firstValue("newName").get(), "newValue");
assertEquals(r.headers().allValues("newName").size(), 1);
assertEquals("newValue", r.headers().firstValue("newName").get());
assertEquals(1, r.headers().allValues("newName").size());
assertAllOtherElementsEqual(r, request, "headers");
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testSetOption(HttpRequest request) {
BiPredicate<String, String> filter = (n, v) -> true;
var r = HttpRequest.newBuilder(request, filter).setOption(H3_DISCOVERY, ALT_SVC).build();
assertEquals(r.getOption(H3_DISCOVERY).get(), ALT_SVC);
assertEquals(ALT_SVC, r.getOption(H3_DISCOVERY).get());
assertAllOtherElementsEqual(r, request, "options");
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testRemoveHeader(HttpRequest request) {
if(!request.headers().map().isEmpty()) {
assertTrue(request.headers().map().containsKey("testName1"));
@ -338,13 +350,14 @@ public class HttpRequestNewBuilderTest {
var r = HttpRequest.newBuilder(request, filter).build();
assertFalse(r.headers().map().containsKey("testName1"));
assertEquals(r.headers().map(), HttpHeaders.of(request.headers().map(), filter).map());
assertEquals(HttpHeaders.of(request.headers().map(), filter).map(), r.headers().map());
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testRemoveOption(HttpRequest request) {
if(!request.getOption(H3_DISCOVERY).isEmpty()) {
assertEquals(request.getOption(H3_DISCOVERY).get(), ANY);
assertEquals(ANY, request.getOption(H3_DISCOVERY).get());
}
var r = HttpRequest.newBuilder(request, (a, b) -> true)
@ -353,7 +366,8 @@ public class HttpRequestNewBuilderTest {
assertAllOtherElementsEqual(r, request, "options");
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testRemoveSingleHeaderValue(HttpRequest request) {
if(!request.headers().map().isEmpty()) {
assertTrue(request.headers().allValues("testName1").contains("testValue1"));
@ -363,10 +377,12 @@ public class HttpRequestNewBuilderTest {
var r = HttpRequest.newBuilder(request, filter).build();
assertFalse(r.headers().map().containsValue("testValue1"));
assertEquals(r.headers().map(), HttpHeaders.of(request.headers().map(), filter).map());
assertFalse(r.headers().allValues("testName1").contains("testValue1"));
assertEquals(HttpHeaders.of(request.headers().map(), filter).map(), r.headers().map());
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testRemoveMultipleHeaders(HttpRequest request) {
BiPredicate<String, String> isTestName1Value1 = (n ,v) ->
n.equalsIgnoreCase("testName1") && v.equals("testValue1");
@ -375,34 +391,36 @@ public class HttpRequestNewBuilderTest {
var filter = (isTestName1Value1.or(isTestName2Value2)).negate();
var r = HttpRequest.newBuilder(request, filter).build();
assertEquals(r.headers().map(), HttpHeaders.of(request.headers().map(), filter).map());
assertEquals(HttpHeaders.of(request.headers().map(), filter).map(), r.headers().map());
BiPredicate<String, String> filter1 = (n, v) ->
!(n.equalsIgnoreCase("testName1") && (v.equals("testValue1") || v.equals("testValue2")));
var r1 = HttpRequest.newBuilder(request, filter1).build();
assertEquals(r1.headers().map(), HttpHeaders.of(request.headers().map(), filter1).map());
assertEquals(HttpHeaders.of(request.headers().map(), filter1).map(), r1.headers().map());
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testRemoveAllHeaders(HttpRequest request) {
if (!request.headers().map().isEmpty()) {
BiPredicate<String, String> filter = (n, v) -> false;
var r = HttpRequest.newBuilder(request, filter).build();
assertTrue(r.headers().map().isEmpty());
assertEquals(r.headers().map(), HttpHeaders.of(request.headers().map(), filter).map());
assertEquals(HttpHeaders.of(request.headers().map(), filter).map(), r.headers().map());
}
}
@Test(dataProvider = "testRequests")
@ParameterizedTest
@MethodSource("variants")
public void testRetainAllHeaders(HttpRequest request) {
if (!request.headers().map().isEmpty()) {
BiPredicate<String, String> filter = (n, v) -> true;
var r = HttpRequest.newBuilder(request, filter).build();
assertFalse(r.headers().map().isEmpty());
assertEquals(r.headers().map(), HttpHeaders.of(request.headers().map(), filter).map());
assertEquals(HttpHeaders.of(request.headers().map(), filter).map(), r.headers().map());
}
}
@ -414,7 +432,7 @@ public class HttpRequestNewBuilderTest {
BiPredicate<String, String> filter = (n, v) -> !n.equalsIgnoreCase("Foo-Bar");
var r = HttpRequest.newBuilder(request, filter).build();
assertFalse(r.headers().map().containsKey("Foo-Bar"));
assertEquals(r.headers().map(), HttpHeaders.of(request.headers().map(), filter).map());
assertEquals(HttpHeaders.of(request.headers().map(), filter).map(), r.headers().map());
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -38,15 +38,14 @@ import java.util.concurrent.Flow;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
/*
* @test
* @bug 8197564 8228970
* @summary Simple smoke test for BodySubscriber.asInputStream();
* @run testng/othervm HttpResponseInputStreamTest
* @run junit/othervm HttpResponseInputStreamTest
* @author daniel fuchs
*/
public class HttpResponseInputStreamTest {
@ -56,7 +55,7 @@ public class HttpResponseInputStreamTest {
static class TestException extends IOException {}
public static void main(String[] args) throws InterruptedException, ExecutionException {
testOnError();
new HttpResponseInputStreamTest().testOnError();
}
/**
@ -66,7 +65,7 @@ public class HttpResponseInputStreamTest {
* @throws ExecutionException
*/
@Test
public static void testOnError() throws InterruptedException, ExecutionException {
public void testOnError() throws InterruptedException, ExecutionException {
CountDownLatch latch = new CountDownLatch(1);
BodySubscriber<InputStream> isb = BodySubscribers.ofInputStream();
ErrorTestSubscription s = new ErrorTestSubscription(isb);
@ -160,7 +159,7 @@ public class HttpResponseInputStreamTest {
}
@Test
public static void testCloseAndSubscribe()
public void testCloseAndSubscribe()
throws InterruptedException, ExecutionException
{
BodySubscriber<InputStream> isb = BodySubscribers.ofInputStream();
@ -189,34 +188,34 @@ public class HttpResponseInputStreamTest {
}
@Test
public static void testReadParameters() throws InterruptedException, ExecutionException, IOException {
public void testReadParameters() throws InterruptedException, ExecutionException, IOException {
BodySubscriber<InputStream> isb = BodySubscribers.ofInputStream();
InputStream is = isb.getBody().toCompletableFuture().get();
Throwable ex;
// len == 0
assertEquals(is.read(new byte[16], 0, 0), 0);
assertEquals(is.read(new byte[16], 16, 0), 0);
assertEquals(0, is.read(new byte[16], 0, 0));
assertEquals(0, is.read(new byte[16], 16, 0));
// index == -1
ex = expectThrows(OOB, () -> is.read(new byte[16], -1, 10));
ex = assertThrows(OOB, () -> is.read(new byte[16], -1, 10));
System.out.println("OutOfBoundsException thrown as expected: " + ex);
// large offset
ex = expectThrows(OOB, () -> is.read(new byte[16], 17, 10));
ex = assertThrows(OOB, () -> is.read(new byte[16], 17, 10));
System.out.println("OutOfBoundsException thrown as expected: " + ex);
ex = expectThrows(OOB, () -> is.read(new byte[16], 10, 10));
ex = assertThrows(OOB, () -> is.read(new byte[16], 10, 10));
System.out.println("OutOfBoundsException thrown as expected: " + ex);
// null value
ex = expectThrows(NPE, () -> is.read(null, 0, 10));
ex = assertThrows(NPE, () -> is.read(null, 0, 10));
System.out.println("NullPointerException thrown as expected: " + ex);
}
@Test
public static void testSubscribeAndClose()
public void testSubscribeAndClose()
throws InterruptedException, ExecutionException
{
BodySubscriber<InputStream> isb = BodySubscribers.ofInputStream();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2026, 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
@ -28,7 +28,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* jdk.test.lib.Platform
* @run testng/othervm HttpVersionsTest
* @run junit/othervm HttpVersionsTest
*/
import java.io.IOException;
@ -42,30 +42,30 @@ import java.net.http.HttpResponse;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ssl.SSLContext;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.httpclient.test.lib.http2.Http2TestServer;
import jdk.httpclient.test.lib.http2.Http2TestExchange;
import jdk.httpclient.test.lib.http2.Http2Handler;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.String.format;
import static java.lang.System.out;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class HttpVersionsTest {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
Http2TestServer http2TestServer;
Http2TestServer https2TestServer;
String http2URI;
String https2URI;
static Http2TestServer http2TestServer;
static Http2TestServer https2TestServer;
static String http2URI;
static String https2URI;
static final int ITERATIONS = 3;
static final String[] BODY = new String[] {
@ -74,10 +74,9 @@ public class HttpVersionsTest {
"I think I'll drink until I stink",
"I'll drink until I cannot blink"
};
int nextBodyId;
static int nextBodyId;
@DataProvider(name = "scenarios")
public Object[][] scenarios() {
public static Object[][] scenarios() {
return new Object[][] {
{ http2URI, true },
{ https2URI, true },
@ -87,9 +86,10 @@ public class HttpVersionsTest {
}
/** Checks that an HTTP/2 request receives an HTTP/2 response. */
@Test(dataProvider = "scenarios")
@ParameterizedTest
@MethodSource("scenarios")
void testHttp2Get(String uri, boolean sameClient) throws Exception {
out.println(format("\n--- testHttp2Get uri:%s, sameClient:%s", uri, sameClient));
out.printf("\n--- testHttp2Get uri:%s, sameClient:%s%n", uri, sameClient);
HttpClient client = null;
for (int i=0; i<ITERATIONS; i++) {
if (!sameClient || client == null)
@ -104,17 +104,18 @@ public class HttpVersionsTest {
out.println("Got response: " + response);
out.println("Got body: " + response.body());
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), HTTP_2);
assertEquals(response.body(), "");
assertEquals(200, response.statusCode());
assertEquals(HTTP_2, response.version());
assertEquals("", response.body());
if (uri.startsWith("https"))
assertTrue(response.sslSession().isPresent());
}
}
@Test(dataProvider = "scenarios")
@ParameterizedTest
@MethodSource("scenarios")
void testHttp2Post(String uri, boolean sameClient) throws Exception {
out.println(format("\n--- testHttp2Post uri:%s, sameClient:%s", uri, sameClient));
out.printf("\n--- testHttp2Post uri:%s, sameClient:%s%n", uri, sameClient);
HttpClient client = null;
for (int i=0; i<ITERATIONS; i++) {
if (!sameClient || client == null)
@ -131,18 +132,19 @@ public class HttpVersionsTest {
out.println("Got response: " + response);
out.println("Got body: " + response.body());
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), HTTP_2);
assertEquals(response.body(), msg);
assertEquals(200, response.statusCode());
assertEquals(HTTP_2, response.version());
assertEquals(msg, response.body());
if (uri.startsWith("https"))
assertTrue(response.sslSession().isPresent());
}
}
/** Checks that an HTTP/1.1 request receives an HTTP/1.1 response, from the HTTP/2 server. */
@Test(dataProvider = "scenarios")
@ParameterizedTest
@MethodSource("scenarios")
void testHttp1dot1Get(String uri, boolean sameClient) throws Exception {
out.println(format("\n--- testHttp1dot1Get uri:%s, sameClient:%s", uri, sameClient));
out.printf("\n--- testHttp1dot1Get uri:%s, sameClient:%s%n", uri, sameClient);
HttpClient client = null;
for (int i=0; i<ITERATIONS; i++) {
if (!sameClient || client == null)
@ -158,20 +160,20 @@ public class HttpVersionsTest {
out.println("Got body: " + response.body());
response.headers().firstValue("X-Received-Body").ifPresent(s -> out.println("X-Received-Body:" + s));
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), HTTP_1_1);
assertEquals(response.body(), "");
assertEquals(response.headers().firstValue("X-Magic").get(),
"HTTP/1.1 request received by HTTP/2 server");
assertEquals(response.headers().firstValue("X-Received-Body").get(), "");
assertEquals(200, response.statusCode());
assertEquals(HTTP_1_1, response.version());
assertEquals("", response.body());
assertEquals("HTTP/1.1 request received by HTTP/2 server", response.headers().firstValue("X-Magic").get());
assertEquals("", response.headers().firstValue("X-Received-Body").get());
if (uri.startsWith("https"))
assertTrue(response.sslSession().isPresent());
}
}
@Test(dataProvider = "scenarios")
@ParameterizedTest
@MethodSource("scenarios")
void testHttp1dot1Post(String uri, boolean sameClient) throws Exception {
out.println(format("\n--- testHttp1dot1Post uri:%s, sameClient:%s", uri, sameClient));
out.printf("\n--- testHttp1dot1Post uri:%s, sameClient:%s%n", uri, sameClient);
HttpClient client = null;
for (int i=0; i<ITERATIONS; i++) {
if (!sameClient || client == null)
@ -188,12 +190,11 @@ public class HttpVersionsTest {
out.println("Got body: " + response.body());
response.headers().firstValue("X-Received-Body").ifPresent(s -> out.println("X-Received-Body:" + s));
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), HTTP_1_1);
assertEquals(response.body(), "");
assertEquals(response.headers().firstValue("X-Magic").get(),
"HTTP/1.1 request received by HTTP/2 server");
assertEquals(response.headers().firstValue("X-Received-Body").get(), msg);
assertEquals(200, response.statusCode());
assertEquals(HTTP_1_1, response.version());
assertEquals("", response.body());
assertEquals("HTTP/1.1 request received by HTTP/2 server", response.headers().firstValue("X-Magic").get());
assertEquals(msg, response.headers().firstValue("X-Received-Body").get());
if (uri.startsWith("https"))
assertTrue(response.sslSession().isPresent());
}
@ -203,8 +204,8 @@ public class HttpVersionsTest {
static final ExecutorService executor = Executors.newCachedThreadPool();
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
http2TestServer = new Http2TestServer("localhost", false, 0, executor, 50, null, null, true);
http2TestServer.addHandler(new Http2VerEchoHandler(), "/http2/vts");
http2URI = "http://" + http2TestServer.serverAuthority() + "/http2/vts";
@ -217,8 +218,8 @@ public class HttpVersionsTest {
https2TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
http2TestServer.stop();
https2TestServer.stop();
executor.shutdown();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2022, 2026, 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
@ -30,8 +30,6 @@ import jdk.httpclient.test.lib.quic.QuicServerConnection;
import jdk.internal.net.http.common.HttpHeadersBuilder;
import jdk.test.lib.net.SimpleSSLContext;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.io.InputStream;
@ -56,7 +54,10 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.net.http.HttpClient.Version.HTTP_2;
import static org.testng.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/*
* @test
@ -68,45 +69,45 @@ import static org.testng.Assert.assertEquals;
* jdk.httpclient.test.lib.http2.Http2TestServer
* jdk.httpclient.test.lib.http3.Http3TestServer
*
* @run testng/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout=1
* @run junit/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout=1
* IdleConnectionTimeoutTest
* @run testng/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout=20
* @run junit/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout=20
* IdleConnectionTimeoutTest
*
* @run testng/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h2=1
* @run junit/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h2=1
* IdleConnectionTimeoutTest
* @run testng/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h2=20
* @run junit/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h2=20
* IdleConnectionTimeoutTest
* @run testng/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h2=abc
* @run junit/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h2=abc
* IdleConnectionTimeoutTest
* @run testng/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h2=-1
* @run junit/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h2=-1
* IdleConnectionTimeoutTest
*
* @run testng/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h3=1
* @run junit/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h3=1
* IdleConnectionTimeoutTest
* @run testng/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h3=20
* @run junit/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h3=20
* IdleConnectionTimeoutTest
* @run testng/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h3=abc
* @run junit/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h3=abc
* IdleConnectionTimeoutTest
* @run testng/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h3=-1
* @run junit/othervm -Djdk.httpclient.HttpClient.log=all -Djdk.httpclient.keepalive.timeout.h3=-1
* IdleConnectionTimeoutTest
*/
public class IdleConnectionTimeoutTest {
URI timeoutUriH2, noTimeoutUriH2, timeoutUriH3, noTimeoutUriH3, getH3;
private static URI timeoutUriH2, noTimeoutUriH2, timeoutUriH3, noTimeoutUriH3, getH3;
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
static volatile QuicServerConnection latestServerConn;
final String KEEP_ALIVE_PROPERTY = "jdk.httpclient.keepalive.timeout";
final String IDLE_CONN_PROPERTY_H2 = "jdk.httpclient.keepalive.timeout.h2";
final String IDLE_CONN_PROPERTY_H3 = "jdk.httpclient.keepalive.timeout.h3";
final String TIMEOUT_PATH = "/serverTimeoutHandler";
final String NO_TIMEOUT_PATH = "/noServerTimeoutHandler";
static final String TIMEOUT_PATH = "/serverTimeoutHandler";
static final String NO_TIMEOUT_PATH = "/noServerTimeoutHandler";
static Http2TestServer http2TestServer;
static Http3TestServer http3TestServer;
static final PrintStream testLog = System.err;
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
http2TestServer = new Http2TestServer(false, 0);
http2TestServer.addHandler(new ServerTimeoutHandlerH2(), TIMEOUT_PATH);
http2TestServer.addHandler(new ServerNoTimeoutHandlerH2(), NO_TIMEOUT_PATH);
@ -212,7 +213,7 @@ public class IdleConnectionTimeoutTest {
HttpRequest hreq = HttpRequest.newBuilder(uri).version(version).GET()
.setOption(H3_DISCOVERY, config).build();
HttpResponse<String> hresp = runRequest(hc, hreq, 2750);
assertEquals(hresp.statusCode(), 200, "idleConnectionTimeoutEvent was not expected but occurred");
assertEquals(200, hresp.statusCode(), "idleConnectionTimeoutEvent was not expected but occurred");
}
private void testNoTimeout(HttpClient hc, URI uri, Version version) {
@ -221,13 +222,13 @@ public class IdleConnectionTimeoutTest {
HttpRequest hreq = HttpRequest.newBuilder(uri).version(version).GET()
.setOption(H3_DISCOVERY, config).build();
HttpResponse<String> hresp = runRequest(hc, hreq, 0);
assertEquals(hresp.statusCode(), 200, "idleConnectionTimeoutEvent was not expected but occurred");
assertEquals(200, hresp.statusCode(), "idleConnectionTimeoutEvent was not expected but occurred");
}
private HttpResponse<String> runRequest(HttpClient hc, HttpRequest req, int sleepTime) {
CompletableFuture<HttpResponse<String>> request = hc.sendAsync(req, HttpResponse.BodyHandlers.ofString(UTF_8));
HttpResponse<String> hresp = request.join();
assertEquals(hresp.statusCode(), 200);
assertEquals(200, hresp.statusCode());
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -28,7 +28,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.http2.Http2TestServer
* jdk.httpclient.test.lib.common.TestServerConfigurator
* @run testng/othervm ImmutableFlowItems
* @run junit/othervm ImmutableFlowItems
*/
import java.io.IOException;
@ -58,32 +58,33 @@ import jdk.httpclient.test.lib.http2.Http2TestServer;
import jdk.httpclient.test.lib.http2.Http2TestExchange;
import jdk.httpclient.test.lib.http2.Http2Handler;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.*;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ImmutableFlowItems {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpsServer httpsTestServer; // HTTPS/1.1
Http2TestServer http2TestServer; // HTTP/2 ( h2c )
Http2TestServer https2TestServer; // HTTP/2 ( h2 )
String httpURI_fixed;
String httpURI_chunk;
String httpsURI_fixed;
String httpsURI_chunk;
String http2URI_fixed;
String http2URI_chunk;
String https2URI_fixed;
String https2URI_chunk;
private static HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpsServer httpsTestServer; // HTTPS/1.1
private static Http2TestServer http2TestServer; // HTTP/2 ( h2c )
private static Http2TestServer https2TestServer; // HTTP/2 ( h2 )
private static String httpURI_fixed;
private static String httpURI_chunk;
private static String httpsURI_fixed;
private static String httpsURI_chunk;
private static String http2URI_fixed;
private static String http2URI_chunk;
private static String https2URI_fixed;
private static String https2URI_chunk;
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ httpURI_fixed },
{ httpURI_chunk },
@ -104,7 +105,8 @@ public class ImmutableFlowItems {
.build();
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsString(String uri) throws Exception {
HttpClient client = newHttpClient();
@ -114,14 +116,14 @@ public class ImmutableFlowItems {
BodyHandler<String> handler = new CRSBodyHandler();
client.sendAsync(req, handler)
.thenApply(HttpResponse::body)
.thenAccept(body -> assertEquals(body, BODY))
.thenAccept(body -> assertEquals(BODY, body))
.join();
}
static class CRSBodyHandler implements BodyHandler<String> {
@Override
public BodySubscriber<String> apply(HttpResponse.ResponseInfo rinfo) {
assertEquals(rinfo.statusCode(), 200);
assertEquals(200, rinfo.statusCode());
return new CRSBodySubscriber();
}
}
@ -138,7 +140,7 @@ public class ImmutableFlowItems {
public void onNext(List<ByteBuffer> item) {
assertUnmodifiableList(item);
long c = item.stream().filter(ByteBuffer::isReadOnly).count();
assertEquals(c, item.size(), "Unexpected writable buffer in: " +item);
assertEquals(item.size(), c, "Unexpected writable buffer in: " +item);
ofString.onNext(item);
}
@ -173,8 +175,8 @@ public class ImmutableFlowItems {
+ server.getAddress().getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
// HTTP/1.1
HttpHandler h1_fixedLengthHandler = new HTTP1_FixedLengthHandler();
HttpHandler h1_chunkHandler = new HTTP1_ChunkedHandler();
@ -214,8 +216,8 @@ public class ImmutableFlowItems {
https2TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop(0);
httpsTestServer.stop(0);
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -29,7 +29,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext ReferenceTracker
* jdk.httpclient.test.lib.common.HttpServerAdapters
* @run testng/othervm -Dtest.http.version=http3
* @run junit/othervm -Dtest.http.version=http3
* -Djdk.internal.httpclient.debug=true
* InvalidInputStreamSubscriptionRequest
*/
@ -41,7 +41,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext ReferenceTracker
* jdk.httpclient.test.lib.common.HttpServerAdapters
* @run testng/othervm -Dtest.http.version=http2 InvalidInputStreamSubscriptionRequest
* @run junit/othervm -Dtest.http.version=http2 InvalidInputStreamSubscriptionRequest
*/
/*
* @test id=http1
@ -51,16 +51,11 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext ReferenceTracker
* jdk.httpclient.test.lib.common.HttpServerAdapters
* @run testng/othervm -Dtest.http.version=http1 InvalidInputStreamSubscriptionRequest
* @run junit/othervm -Dtest.http.version=http1 InvalidInputStreamSubscriptionRequest
*/
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterClass;
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;
@ -96,26 +91,31 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI_fixed;
String httpURI_chunk;
String httpsURI_fixed;
String httpsURI_chunk;
String http2URI_fixed;
String http2URI_chunk;
String https2URI_fixed;
String https2URI_chunk;
String http3URI_fixed;
String http3URI_chunk;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI_fixed;
private static String httpURI_chunk;
private static String httpsURI_fixed;
private static String httpsURI_chunk;
private static String http2URI_fixed;
private static String http2URI_chunk;
private static String https2URI_fixed;
private static String https2URI_chunk;
private static String http3URI_fixed;
private static String http3URI_chunk;
static final int ITERATION_COUNT = 3;
// a shared executor helps reduce the amount of threads created by the test
@ -156,7 +156,7 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
}
}
@AfterClass
@AfterAll
static final void printFailedTests() {
out.println("\n=========================");
try {
@ -200,8 +200,7 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
static final Supplier<BodyHandler<InputStream>> OF_INPUTSTREAM =
BHS.of(BodyHandlers::ofInputStream, "BodyHandlers::ofInputStream");
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
Object[][] http3 = new Object[][]{
{http3URI_fixed, false, OF_INPUTSTREAM},
{http3URI_chunk, false, OF_INPUTSTREAM},
@ -244,7 +243,7 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
HttpClient newHttpClient(String uri) {
HttpClient.Builder builder = uri.contains("/http3/")
? newClientBuilderForH3()
@ -265,7 +264,8 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
return builder;
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testNoBody(String uri, boolean sameClient, BHS handlers)
throws Exception
{
@ -285,7 +285,7 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
HttpResponse<InputStream> response = client.send(req, badHandler);
try (InputStream is = response.body()) {
String body = new String(is.readAllBytes(), UTF_8);
assertEquals(body, "");
assertEquals("", body);
if (uri.endsWith("/chunk")
&& response.version() == HTTP_1_1) {
// with /fixed and 0 length
@ -324,7 +324,8 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testNoBodyAsync(String uri, boolean sameClient, BHS handlers)
throws Exception
{
@ -352,7 +353,7 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
});
try {
// Get the final result and compare it with the expected body
assertEquals(result.get(), "");
assertEquals("", result.get());
if (uri.endsWith("/chunk")
&& response.get().version() == HTTP_1_1) {
// with /fixed and 0 length
@ -390,7 +391,8 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsString(String uri, boolean sameClient, BHS handlers)
throws Exception
{
@ -409,7 +411,7 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
HttpResponse<InputStream> response = client.send(req, badHandler);
try (InputStream is = response.body()) {
String body = new String(is.readAllBytes(), UTF_8);
assertEquals(body, WITH_BODY);
assertEquals(WITH_BODY, body);
throw new RuntimeException("Expected IAE not thrown");
}
} catch (Exception x) {
@ -443,7 +445,8 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsStringAsync(String uri, boolean sameClient, BHS handlers)
throws Exception
{
@ -470,7 +473,7 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
// Get the final result and compare it with the expected body
try {
String body = result.get();
assertEquals(body, WITH_BODY);
assertEquals(WITH_BODY, body);
throw new RuntimeException("Expected IAE not thrown");
} catch (Exception x) {
Throwable cause = x;
@ -563,8 +566,8 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
+ server.getAddress().getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
// HTTP/1.1
HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler();
HttpTestHandler h1_chunkHandler = new HTTP_VariableLengthHandler();
@ -613,8 +616,8 @@ public class InvalidInputStreamSubscriptionRequest implements HttpServerAdapters
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
AssertionError fail = TRACKER.check(1500);
try {
httpTestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -27,7 +27,7 @@
* when SSL context is not valid.
* @library /test/lib
* @build jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm -Djdk.internal.httpclient.debug=true InvalidSSLContextTest
* @run junit/othervm -Djdk.internal.httpclient.debug=true InvalidSSLContextTest
*/
import java.io.IOException;
@ -40,7 +40,6 @@ import java.util.concurrent.CompletionException;
import java.net.SocketException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSocket;
import java.net.http.HttpClient;
@ -49,32 +48,32 @@ import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class InvalidSSLContextTest {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
volatile SSLServerSocket sslServerSocket;
volatile String uri;
static volatile SSLServerSocket sslServerSocket;
static volatile String uri;
@DataProvider(name = "versions")
public Object[][] versions() {
public static Object[][] versions() {
return new Object[][]{
{ HTTP_1_1 },
{ HTTP_2 }
};
}
@Test(dataProvider = "versions")
@ParameterizedTest
@MethodSource("versions")
public void testSync(Version version) throws Exception {
// client-side uses a different context to that of the server-side
HttpClient client = HttpClient.newBuilder()
@ -88,14 +87,15 @@ public class InvalidSSLContextTest {
try {
HttpResponse<?> response = client.send(request, BodyHandlers.discarding());
Assert.fail("UNEXPECTED response" + response);
Assertions.fail("UNEXPECTED response" + response);
} catch (IOException ex) {
System.out.println("Caught expected: " + ex);
assertExceptionOrCause(SSLException.class, ex);
}
}
@Test(dataProvider = "versions")
@ParameterizedTest
@MethodSource("versions")
public void testAsync(Version version) throws Exception {
// client-side uses a different context to that of the server-side
HttpClient client = HttpClient.newBuilder()
@ -115,13 +115,13 @@ public class InvalidSSLContextTest {
CompletableFuture<?> stage) {
stage.handle((result, error) -> {
if (result != null) {
Assert.fail("UNEXPECTED result: " + result);
Assertions.fail("UNEXPECTED result: " + result);
return null;
}
if (error instanceof CompletionException) {
Throwable cause = error.getCause();
if (cause == null) {
Assert.fail("Unexpected null cause: " + error);
Assertions.fail("Unexpected null cause: " + error);
}
assertExceptionOrCause(clazz, cause);
} else {
@ -133,7 +133,7 @@ public class InvalidSSLContextTest {
static void assertExceptionOrCause(Class<? extends Throwable> clazz, Throwable t) {
if (t == null) {
Assert.fail("Expected " + clazz + ", caught nothing");
Assertions.fail("Expected " + clazz + ", caught nothing");
}
final Throwable original = t;
do {
@ -142,11 +142,11 @@ public class InvalidSSLContextTest {
}
} while ((t = t.getCause()) != null);
original.printStackTrace(System.out);
Assert.fail("Expected " + clazz + "in " + original);
Assertions.fail("Expected " + clazz + "in " + original);
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
// server-side uses a different context to that of the client-side
sslServerSocket = (SSLServerSocket)sslContext
.getServerSocketFactory()
@ -169,7 +169,7 @@ public class InvalidSSLContextTest {
Thread.sleep(500);
s.startHandshake();
s.close();
Assert.fail("SERVER: UNEXPECTED ");
Assertions.fail("SERVER: UNEXPECTED ");
} catch (SSLException | SocketException se) {
System.out.println("SERVER: caught expected " + se);
} catch (IOException e) {
@ -187,8 +187,8 @@ public class InvalidSSLContextTest {
t.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
sslServerSocket.close();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -30,21 +30,15 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext ReferenceTracker
* jdk.httpclient.test.lib.common.HttpServerAdapters
* @run testng/othervm InvalidSubscriptionRequest
* @run junit/othervm InvalidSubscriptionRequest
*/
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.SimpleSSLContext;
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.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
@ -74,26 +68,31 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class InvalidSubscriptionRequest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI_fixed;
String httpURI_chunk;
String httpsURI_fixed;
String httpsURI_chunk;
String http2URI_fixed;
String http2URI_chunk;
String https2URI_fixed;
String https2URI_chunk;
String http3URI_fixed;
String http3URI_chunk;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI_fixed;
private static String httpURI_chunk;
private static String httpsURI_fixed;
private static String httpsURI_chunk;
private static String http2URI_fixed;
private static String http2URI_chunk;
private static String https2URI_fixed;
private static String https2URI_chunk;
private static String http3URI_fixed;
private static String http3URI_chunk;
static final int ITERATION_COUNT = 3;
// a shared executor helps reduce the amount of threads created by the test
@ -126,8 +125,7 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
static final Supplier<BodyHandler<Publisher<List<ByteBuffer>>>> OF_PUBLISHER_API =
BHS.of(BodyHandlers::ofPublisher, "BodyHandlers::ofPublisher");
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ http3URI_fixed, false, OF_PUBLISHER_API },
{ http3URI_chunk, false, OF_PUBLISHER_API },
@ -154,7 +152,7 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
};
}
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
HttpClient newHttpClient(String uri) {
HttpClient.Builder builder = uri.contains("/http3/")
? newClientBuilderForH3()
@ -175,8 +173,9 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
return builder;
}
@Test(dataProvider = "variants")
public void testNoBody(String uri, boolean sameClient, BHS handlers) throws Exception {
@ParameterizedTest
@MethodSource("variants")
void testNoBody(String uri, boolean sameClient, BHS handlers) throws Exception {
HttpClient client = null;
Throwable failed = null;
for (int i=0; i< ITERATION_COUNT; i++) {
@ -196,7 +195,7 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
// Get the final result and compare it with the expected body
try {
String body = ofString.getBody().toCompletableFuture().get();
assertEquals(body, "");
assertEquals("", body);
if (uri.endsWith("/chunk")
&& response.version() == HTTP_1_1) {
// with /fixed and 0 length
@ -231,8 +230,9 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
public void testNoBodyAsync(String uri, boolean sameClient, BHS handlers) throws Exception {
@ParameterizedTest
@MethodSource("variants")
void testNoBodyAsync(String uri, boolean sameClient, BHS handlers) {
HttpClient client = null;
Throwable failed = null;
for (int i=0; i< ITERATION_COUNT; i++) {
@ -257,7 +257,7 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
});
try {
// Get the final result and compare it with the expected body
assertEquals(result.get(), "");
assertEquals("", result.get());
if (uri.endsWith("/chunk")
&& response.get().version() == HTTP_1_1) {
// with /fixed and 0 length
@ -292,8 +292,9 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
public void testAsString(String uri, boolean sameClient, BHS handlers) throws Exception {
@ParameterizedTest
@MethodSource("variants")
void testAsString(String uri, boolean sameClient, BHS handlers) throws Exception {
HttpClient client = null;
Throwable failed = null;
for (int i=0; i< ITERATION_COUNT; i++) {
@ -314,7 +315,7 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
// Get the final result and compare it with the expected body
try {
String body = ofString.getBody().toCompletableFuture().get();
assertEquals(body, WITH_BODY);
assertEquals(WITH_BODY, body);
throw new RuntimeException("Expected IAE not thrown");
} catch (Exception x) {
Throwable cause = x;
@ -344,8 +345,9 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
public void testAsStringAsync(String uri, boolean sameClient, BHS handlers) throws Exception {
@ParameterizedTest
@MethodSource("variants")
void testAsStringAsync(String uri, boolean sameClient, BHS handlers) {
HttpClient client = null;
Throwable failed = null;
for (int i=0; i< ITERATION_COUNT; i++) {
@ -369,7 +371,7 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
// Get the final result and compare it with the expected body
try {
String body = result.get();
assertEquals(body, WITH_BODY);
assertEquals(WITH_BODY, body);
throw new RuntimeException("Expected IAE not thrown");
} catch (Exception x) {
Throwable cause = x;
@ -454,13 +456,8 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
}
}
static String serverAuthority(HttpServer server) {
return InetAddress.getLoopbackAddress().getHostName() + ":"
+ server.getAddress().getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
// HTTP/1.1
HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler();
HttpTestHandler h1_chunkHandler = new HTTP_VariableLengthHandler();
@ -509,8 +506,8 @@ public class InvalidSubscriptionRequest implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
AssertionError fail = TRACKER.check(500);
try {
httpTestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -54,10 +54,6 @@ import java.util.stream.Stream;
import javax.net.ssl.SSLContext;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
@ -66,11 +62,16 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_16;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.net.http.HttpRequest.BodyPublishers.ofString;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertThrows;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
@ -81,29 +82,28 @@ import static org.testng.Assert.assertTrue;
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build ReferenceTracker jdk.httpclient.test.lib.http2.Http2TestServer
* jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm -XX:+UnlockDiagnosticVMOptions -XX:DiagnoseSyncOnValueBasedClasses=1 LineBodyHandlerTest
* @run junit/othervm -XX:+UnlockDiagnosticVMOptions -XX:DiagnoseSyncOnValueBasedClasses=1 LineBodyHandlerTest
*/
public class LineBodyHandlerTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
final AtomicInteger clientCount = new AtomicInteger();
HttpClient sharedClient;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final AtomicInteger clientCount = new AtomicInteger();
private static HttpClient sharedClient;
@DataProvider(name = "uris")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ http3URI },
{ httpURI },
@ -171,7 +171,7 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
StandardCharsets.US_ASCII, ""));
}
private static final List<String> lines(String text, String eol) {
private static List<String> lines(String text, String eol) {
if (eol == null) {
return new BufferedReader(new StringReader(text)).lines().collect(Collectors.toList());
} else {
@ -210,7 +210,8 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
return builder;
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testStringWithFinisher(String url) {
String body = "May the luck of the Irish be with you!";
HttpClient client = newClient();
@ -226,12 +227,13 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
HttpResponse<String> response = cf.join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(text, body);
assertEquals(subscriber.list, lines(body, "\n"));
assertEquals(200, response.statusCode());
assertEquals(body, text);
assertEquals(lines(body, "\n"), subscriber.list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testAsStream(String url) {
String body = "May the luck of the Irish be with you!";
HttpClient client = newClient();
@ -247,13 +249,14 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
List<String> list = stream.collect(Collectors.toList());
String text = list.stream().collect(Collectors.joining("|"));
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(text, body);
assertEquals(list, List.of(body));
assertEquals(list, lines(body, null));
assertEquals(200, response.statusCode());
assertEquals(body, text);
assertEquals(List.of(body), list);
assertEquals(lines(body, null), list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testStringWithFinisher2(String url) {
String body = "May the luck\r\n\r\n of the Irish be with you!";
HttpClient client = newClient();
@ -270,12 +273,13 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
HttpResponse<Void> response = cf.join();
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(text, body.replace("\r\n", "\n"));
assertEquals(subscriber.list, lines(body, null));
assertEquals(200, response.statusCode());
assertEquals(body.replace("\r\n", "\n"), text);
assertEquals(lines(body, null), subscriber.list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testAsStreamWithCRLF(String url) {
String body = "May the luck\r\n\r\n of the Irish be with you!";
HttpClient client = newClient();
@ -291,15 +295,16 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
List<String> list = stream.collect(Collectors.toList());
String text = list.stream().collect(Collectors.joining("|"));
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(text, "May the luck|| of the Irish be with you!");
assertEquals(list, List.of("May the luck",
assertEquals(200, response.statusCode());
assertEquals("May the luck|| of the Irish be with you!", text);
assertEquals(List.of("May the luck",
"",
" of the Irish be with you!"));
assertEquals(list, lines(body, null));
" of the Irish be with you!"), list);
assertEquals(lines(body, null), list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testStringWithFinisherBlocking(String url) throws Exception {
String body = "May the luck of the Irish be with you!";
HttpClient client = newClient();
@ -311,12 +316,13 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
BodyHandlers.fromLineSubscriber(subscriber, Supplier::get, "\n"));
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(text, "May the luck of the Irish be with you!");
assertEquals(subscriber.list, lines(body, "\n"));
assertEquals(200, response.statusCode());
assertEquals("May the luck of the Irish be with you!", text);
assertEquals(lines(body, "\n"), subscriber.list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testStringWithoutFinisherBlocking(String url) throws Exception {
String body = "May the luck of the Irish be with you!";
HttpClient client = newClient();
@ -328,14 +334,15 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
BodyHandlers.fromLineSubscriber(subscriber));
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(text, "May the luck of the Irish be with you!");
assertEquals(subscriber.list, lines(body, null));
assertEquals(200, response.statusCode());
assertEquals("May the luck of the Irish be with you!", text);
assertEquals(lines(body, null), subscriber.list);
}
// Subscriber<Object>
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testAsStreamWithMixedCRLF(String url) {
String body = "May\r\n the wind\r\n always be\rat your back.\r\r";
HttpClient client = newClient();
@ -351,18 +358,19 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
List<String> list = stream.collect(Collectors.toList());
String text = list.stream().collect(Collectors.joining("|"));
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
assertTrue(text.length() != 0); // what else can be asserted!
assertEquals(text, "May| the wind| always be|at your back.|");
assertEquals(list, List.of("May",
assertEquals("May| the wind| always be|at your back.|", text);
assertEquals(List.of("May",
" the wind",
" always be",
"at your back.",
""));
assertEquals(list, lines(body, null));
""), list);
assertEquals(lines(body, null), list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testAsStreamWithMixedCRLF_UTF8(String url) {
String body = "May\r\n the wind\r\n always be\rat your back.\r\r";
HttpClient client = newClient();
@ -378,17 +386,18 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
List<String> list = stream.collect(Collectors.toList());
String text = list.stream().collect(Collectors.joining("|"));
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
assertTrue(text.length() != 0); // what else can be asserted!
assertEquals(text, "May| the wind| always be|at your back.|");
assertEquals(list, List.of("May",
assertEquals("May| the wind| always be|at your back.|", text);
assertEquals(List.of("May",
" the wind",
" always be",
"at your back.", ""));
assertEquals(list, lines(body, null));
"at your back.", ""), list);
assertEquals(lines(body, null), list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testAsStreamWithMixedCRLF_UTF16(String url) {
String body = "May\r\n the wind\r\n always be\rat your back.\r\r";
HttpClient client = newClient();
@ -404,18 +413,19 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
List<String> list = stream.collect(Collectors.toList());
String text = list.stream().collect(Collectors.joining("|"));
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
assertTrue(text.length() != 0); // what else can be asserted!
assertEquals(text, "May| the wind| always be|at your back.|");
assertEquals(list, List.of("May",
assertEquals("May| the wind| always be|at your back.|", text);
assertEquals(List.of("May",
" the wind",
" always be",
"at your back.",
""));
assertEquals(list, lines(body, null));
""), list);
assertEquals(lines(body, null), list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testObjectWithFinisher(String url) {
String body = "May\r\n the wind\r\n always be\rat your back.";
HttpClient client = newClient();
@ -431,16 +441,17 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
HttpResponse<String> response = cf.join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
assertTrue(text.length() != 0); // what else can be asserted!
assertEquals(text, "May\n the wind\n always be\rat your back.");
assertEquals(subscriber.list, List.of("May",
assertEquals("May\n the wind\n always be\rat your back.", text);
assertEquals(List.of("May",
" the wind",
" always be\rat your back."));
assertEquals(subscriber.list, lines(body, "\r\n"));
" always be\rat your back."), subscriber.list);
assertEquals(lines(body, "\r\n"), subscriber.list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testObjectWithFinisher_UTF16(String url) {
String body = "May\r\n the wind\r\n always be\rat your back.\r\r";
HttpClient client = newClient();
@ -455,18 +466,19 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
HttpResponse<String> response = cf.join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
assertTrue(text.length() != 0); // what else can be asserted!
assertEquals(text, "May\n the wind\n always be\nat your back.\n");
assertEquals(subscriber.list, List.of("May",
assertEquals("May\n the wind\n always be\nat your back.\n", text);
assertEquals(List.of("May",
" the wind",
" always be",
"at your back.",
""));
assertEquals(subscriber.list, lines(body, null));
""), subscriber.list);
assertEquals(lines(body, null), subscriber.list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testObjectWithoutFinisher(String url) {
String body = "May\r\n the wind\r\n always be\rat your back.";
HttpClient client = newClient();
@ -482,17 +494,18 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
HttpResponse<Void> response = cf.join();
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
assertTrue(text.length() != 0); // what else can be asserted!
assertEquals(text, "May\n the wind\n always be\nat your back.");
assertEquals(subscriber.list, List.of("May",
assertEquals("May\n the wind\n always be\nat your back.", text);
assertEquals(List.of("May",
" the wind",
" always be",
"at your back."));
assertEquals(subscriber.list, lines(body, null));
"at your back."), subscriber.list);
assertEquals(lines(body, null), subscriber.list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testObjectWithFinisherBlocking(String url) throws Exception {
String body = "May\r\n the wind\r\n always be\nat your back.";
HttpClient client = newClient();
@ -507,16 +520,17 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
"\r\n"));
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
assertTrue(text.length() != 0); // what else can be asserted!
assertEquals(text, "May\n the wind\n always be\nat your back.");
assertEquals(subscriber.list, List.of("May",
assertEquals("May\n the wind\n always be\nat your back.", text);
assertEquals(List.of("May",
" the wind",
" always be\nat your back."));
assertEquals(subscriber.list, lines(body, "\r\n"));
" always be\nat your back."), subscriber.list);
assertEquals(lines(body, "\r\n"), subscriber.list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testObjectWithoutFinisherBlocking(String url) throws Exception {
String body = "May\r\n the wind\r\n always be\nat your back.";
HttpClient client = newClient();
@ -529,14 +543,14 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
BodyHandlers.fromLineSubscriber(subscriber));
String text = subscriber.get();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
assertTrue(text.length() != 0); // what else can be asserted!
assertEquals(text, "May\n the wind\n always be\nat your back.");
assertEquals(subscriber.list, List.of("May",
assertEquals("May\n the wind\n always be\nat your back.", text);
assertEquals(List.of("May",
" the wind",
" always be",
"at your back."));
assertEquals(subscriber.list, lines(body, null));
"at your back."), subscriber.list);
assertEquals(lines(body, null), subscriber.list);
}
static private final String LINE = "Bient\u00f4t nous plongerons dans les" +
@ -551,7 +565,8 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
return res.toString();
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testBigTextFromLineSubscriber(String url) {
HttpClient client = newClient();
String bigtext = bigtext();
@ -567,12 +582,13 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
HttpResponse<String> response = cf.join();
String text = response.body();
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(text, bigtext.replace("\r\n", "\n"));
assertEquals(subscriber.list, lines(bigtext, "\r\n"));
assertEquals(200, response.statusCode());
assertEquals(bigtext.replace("\r\n", "\n"), text);
assertEquals(lines(bigtext, "\r\n"), subscriber.list);
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testBigTextAsStream(String url) {
HttpClient client = newClient();
String bigtext = bigtext();
@ -588,10 +604,10 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
List<String> list = stream.collect(Collectors.toList());
String text = list.stream().collect(Collectors.joining("|"));
System.out.println(text);
assertEquals(response.statusCode(), 200);
assertEquals(text, bigtext.replace("\r\n", "|"));
assertEquals(list, List.of(bigtext.split("\r\n")));
assertEquals(list, lines(bigtext, null));
assertEquals(200, response.statusCode());
assertEquals(bigtext.replace("\r\n", "|"), text);
assertEquals(List.of(bigtext.split("\r\n")), list);
assertEquals(lines(bigtext, null), list);
}
/** An abstract Subscriber that converts all received data into a String. */
@ -675,8 +691,8 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
return Executors.newCachedThreadPool(factory);
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpTestServer.create(HTTP_1_1, null,
executorFor("HTTP/1.1 Server Thread"));
httpTestServer.addHandler(new HttpTestEchoHandler(), "/http1/echo");
@ -706,8 +722,8 @@ public class LineBodyHandlerTest implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
sharedClient = null;
try {
System.gc();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -37,10 +37,11 @@ import java.util.concurrent.SubmissionPublisher;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.testng.annotations.Test;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.charset.StandardCharsets.UTF_16;
import static org.testng.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/*
* @test
@ -48,7 +49,7 @@ import static org.testng.Assert.assertEquals;
* In particular tests that surrogate characters are handled
* correctly.
* @modules java.net.http java.logging
* @run testng/othervm LineStreamsAndSurrogatesTest
* @run junit/othervm LineStreamsAndSurrogatesTest
*/
public class LineStreamsAndSurrogatesTest {
@ -56,7 +57,7 @@ public class LineStreamsAndSurrogatesTest {
static final Class<NullPointerException> NPE = NullPointerException.class;
private static final List<String> lines(String text) {
private static List<String> lines(String text) {
return new BufferedReader(new StringReader(text)).lines().collect(Collectors.toList());
}
@ -100,14 +101,14 @@ public class LineStreamsAndSurrogatesTest {
String resp2 = reader.lines().collect(Collectors.joining(""));
System.out.println("***** Got2: " + resp2);
assertEquals(resp, resp2);
assertEquals(list, List.of("Bient\u00f4t",
assertEquals(resp2, resp);
assertEquals(List.of("Bient\u00f4t",
" nous plongerons",
" dans",
" les",
"",
" fr\u00f4\ud801\udc00des",
" t\u00e9n\u00e8bres\ufffd"));
" t\u00e9n\u00e8bres\ufffd"), list);
} catch (ExecutionException x) {
Throwable cause = x.getCause();
if (cause instanceof MalformedInputException) {
@ -151,18 +152,18 @@ public class LineStreamsAndSurrogatesTest {
List<String> list = stream.collect(Collectors.toList());
String resp = list.stream().collect(Collectors.joining("|"));
System.out.println("***** Got: " + resp);
assertEquals(resp, text.replace("\r\n", "|")
assertEquals(text.replace("\r\n", "|")
.replace("\n","|")
.replace("\r","|"));
assertEquals(list, List.of("Bient\u00f4t",
.replace("\r","|"), resp);
assertEquals(List.of("Bient\u00f4t",
" nous plongerons",
" dans",
"",
" les",
"",
" fr\u00f4\ud801\udc00des",
" t\u00e9n\u00e8bres"));
assertEquals(list, lines(text));
" t\u00e9n\u00e8bres"), list);
assertEquals(lines(text), list);
if (errorRef.get() != null) {
throw new RuntimeException("Unexpected exception", errorRef.get());
}
@ -201,15 +202,15 @@ public class LineStreamsAndSurrogatesTest {
System.out.println("***** Got: " + resp);
String expected = Stream.of(text.split("\r\n|\r|\n"))
.collect(Collectors.joining(""));
assertEquals(resp, expected);
assertEquals(list, List.of("Bient\u00f4t",
assertEquals(expected, resp);
assertEquals(List.of("Bient\u00f4t",
" nous plongerons",
" dans",
"",
" les fr\u00f4\ud801\udc00des",
" t\u00e9n\u00e8bres",
""));
assertEquals(list, lines(text));
""), list);
assertEquals(lines(text), list);
if (errorRef.get() != null) {
throw new RuntimeException("Unexpected exception", errorRef.get());
}
@ -246,16 +247,16 @@ public class LineStreamsAndSurrogatesTest {
List<String> list = stream.collect(Collectors.toList());
String resp = list.stream().collect(Collectors.joining(""));
System.out.println("***** Got: " + resp);
assertEquals(resp, text.replace("\n","").replace("\r",""));
assertEquals(list, List.of("Bient\u00f4t",
assertEquals(text.replace("\n","").replace("\r",""), resp);
assertEquals(List.of("Bient\u00f4t",
" nous plongerons",
" dans",
"",
" les",
"",
" fr\u00f4\ud801\udc00des",
" t\u00e9n\u00e8bres"));
assertEquals(list, lines(text));
" t\u00e9n\u00e8bres"), list);
assertEquals(lines(text), list);
if (errorRef.get() != null) {
throw new RuntimeException("Unexpected exception", errorRef.get());
}
@ -294,15 +295,15 @@ public class LineStreamsAndSurrogatesTest {
System.out.println("***** Got: " + resp);
String expected = Stream.of(text.split("\r\n|\r|\n"))
.collect(Collectors.joining(""));
assertEquals(resp, expected);
assertEquals(list, List.of("Bient\u00f4t",
assertEquals(expected, resp);
assertEquals(List.of("Bient\u00f4t",
" nous plongerons",
" dans",
"",
" les fr\u00f4\ud801\udc00des",
" t\u00e9n\u00e8bres",
""));
assertEquals(list, lines(text));
""), list);
assertEquals(lines(text), list);
if (errorRef.get() != null) {
throw new RuntimeException("Unexpected exception", errorRef.get());
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -42,10 +42,11 @@ import java.util.concurrent.SubmissionPublisher;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.testng.annotations.Test;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.nio.charset.StandardCharsets.UTF_16;
import static org.testng.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
/*
* @test
@ -53,7 +54,7 @@ import static org.testng.Assert.assertEquals;
* In particular tests that surrogate characters are handled
* correctly.
* @modules java.net.http java.logging
* @run testng/othervm LineSubscribersAndSurrogatesTest
* @run junit/othervm LineSubscribersAndSurrogatesTest
*/
public class LineSubscribersAndSurrogatesTest {
@ -61,7 +62,7 @@ public class LineSubscribersAndSurrogatesTest {
static final Class<NullPointerException> NPE = NullPointerException.class;
private static final List<String> lines(String text, String eol) {
private static List<String> lines(String text, String eol) {
if (eol == null) {
return new BufferedReader(new StringReader(text)).lines().collect(Collectors.toList());
} else {
@ -104,14 +105,14 @@ public class LineSubscribersAndSurrogatesTest {
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedReader reader = new BufferedReader(new InputStreamReader(bais, UTF_8));
String resp2 = reader.lines().collect(Collectors.joining(""));
assertEquals(resp, resp2);
assertEquals(subscriber.list, List.of("Bient\u00f4t",
assertEquals(resp2, resp);
assertEquals(List.of("Bient\u00f4t",
" nous plongerons",
" dans",
" les",
"",
" fr\u00f4\ud801\udc00des",
" t\u00e9n\u00e8bres\ufffd"));
" t\u00e9n\u00e8bres\ufffd"), subscriber.list);
} catch (ExecutionException x) {
Throwable cause = x.getCause();
if (cause instanceof MalformedInputException) {
@ -147,10 +148,10 @@ public class LineSubscribersAndSurrogatesTest {
"",
" fr\u00f4\ud801\udc00des\r",
" t\u00e9n\u00e8bres\r");
assertEquals(subscriber.list, expected);
assertEquals(resp, Stream.of(text.split("\n")).collect(Collectors.joining("")));
assertEquals(resp, expected.stream().collect(Collectors.joining("")));
assertEquals(subscriber.list, lines(text, "\n"));
assertEquals(expected, subscriber.list);
assertEquals(Stream.of(text.split("\n")).collect(Collectors.joining("")), resp);
assertEquals(expected.stream().collect(Collectors.joining("")), resp);
assertEquals(lines(text, "\n"), subscriber.list);
}
@ -172,14 +173,14 @@ public class LineSubscribersAndSurrogatesTest {
publisher.close();
String resp = bodySubscriber.getBody().toCompletableFuture().get();
System.out.println("***** Got: " + resp);
assertEquals(resp, text.replace("\r", ""));
assertEquals(subscriber.list, List.of("Bient\u00f4t",
assertEquals(text.replace("\r", ""), resp);
assertEquals(List.of("Bient\u00f4t",
"\n nous plongerons",
"\n dans",
" les fr\u00f4\ud801\udc00des",
"\n t\u00e9n\u00e8bres",
""));
assertEquals(subscriber.list, lines(text, "\r"));
""), subscriber.list);
assertEquals(lines(text, "\r"), subscriber.list);
}
@Test
@ -200,12 +201,12 @@ public class LineSubscribersAndSurrogatesTest {
publisher.close();
String resp = bodySubscriber.getBody().toCompletableFuture().get();
System.out.println("***** Got: " + resp);
assertEquals(resp, text.replace("\r\n",""));
assertEquals(subscriber.list, List.of("Bient\u00f4t",
assertEquals(text.replace("\r\n",""), resp);
assertEquals(List.of("Bient\u00f4t",
" nous plongerons",
" dans\r les fr\u00f4\ud801\udc00des",
" t\u00e9n\u00e8bres"));
assertEquals(subscriber.list, lines(text, "\r\n"));
" t\u00e9n\u00e8bres"), subscriber.list);
assertEquals(lines(text, "\r\n"), subscriber.list);
}
@ -234,9 +235,9 @@ public class LineSubscribersAndSurrogatesTest {
"",
" fr\u00f4\ud801\udc00des",
" t\u00e9n\u00e8bres");
assertEquals(subscriber.list, expected);
assertEquals(resp, expected.stream().collect(Collectors.joining("")));
assertEquals(subscriber.list, lines(text, null));
assertEquals(expected, subscriber.list);
assertEquals(expected.stream().collect(Collectors.joining("")), resp);
assertEquals(lines(text, null), subscriber.list);
}
@Test
@ -265,9 +266,9 @@ public class LineSubscribersAndSurrogatesTest {
" fr\u00f4\ud801\udc00des",
" t\u00e9n\u00e8bres",
"");
assertEquals(resp, expected.stream().collect(Collectors.joining("")));
assertEquals(subscriber.list, expected);
assertEquals(subscriber.list, lines(text, null));
assertEquals(expected.stream().collect(Collectors.joining("")), resp);
assertEquals(expected, subscriber.list);
assertEquals(lines(text, null), subscriber.list);
}
void testStringWithoutFinisherBR() throws Exception {
@ -293,9 +294,9 @@ public class LineSubscribersAndSurrogatesTest {
"",
" fr\u00f4\ud801\udc00des",
" t\u00e9n\u00e8bres");
assertEquals(subscriber.text, expected.stream().collect(Collectors.joining("")));
assertEquals(subscriber.list, expected);
assertEquals(subscriber.list, lines(text, null));
assertEquals(expected.stream().collect(Collectors.joining("")), subscriber.text);
assertEquals(expected, subscriber.list);
assertEquals(lines(text, null), subscriber.list);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -27,7 +27,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.http2.Http2TestServer
* jdk.httpclient.test.lib.common.TestServerConfigurator
* @run testng/othervm
* @run junit/othervm
* -Djdk.internal.httpclient.debug=true
* MappingResponseSubscriber
*/
@ -64,30 +64,32 @@ import jdk.httpclient.test.lib.http2.Http2TestExchange;
import jdk.httpclient.test.lib.http2.Http2Handler;
import jdk.test.lib.Utils;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class MappingResponseSubscriber {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpsServer httpsTestServer; // HTTPS/1.1
Http2TestServer http2TestServer; // HTTP/2 ( h2c )
Http2TestServer https2TestServer; // HTTP/2 ( h2 )
String httpURI_fixed;
String httpURI_chunk;
String httpsURI_fixed;
String httpsURI_chunk;
String http2URI_fixed;
String http2URI_chunk;
String https2URI_fixed;
String https2URI_chunk;
private static HttpServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpsServer httpsTestServer; // HTTPS/1.1
private static Http2TestServer http2TestServer; // HTTP/2 ( h2c )
private static Http2TestServer https2TestServer; // HTTP/2 ( h2 )
private static String httpURI_fixed;
private static String httpURI_chunk;
private static String httpsURI_fixed;
private static String httpsURI_chunk;
private static String http2URI_fixed;
private static String http2URI_chunk;
private static String https2URI_fixed;
private static String https2URI_chunk;
static final int ITERATION_COUNT = 3;
// a shared executor helps reduce the amount of threads created by the test
@ -95,8 +97,7 @@ public class MappingResponseSubscriber {
static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ httpURI_fixed, false },
{ httpURI_chunk, false },
@ -125,7 +126,8 @@ public class MappingResponseSubscriber {
.build();
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsBytes(String uri, boolean sameClient) throws Exception {
HttpClient client = null;
for (int i = 0; i < ITERATION_COUNT; i++) {
@ -137,7 +139,7 @@ public class MappingResponseSubscriber {
BodyHandler<byte[]> handler = new CRSBodyHandler();
HttpResponse<byte[]> response = client.send(req, handler);
byte[] body = response.body();
assertEquals(body, bytes);
Assertions.assertArrayEquals(bytes, body);
// if sameClient we will reuse the client for the next
// operation, so there's nothing more to do.
@ -163,7 +165,7 @@ public class MappingResponseSubscriber {
static class CRSBodyHandler implements BodyHandler<byte[]> {
@Override
public BodySubscriber<byte[]> apply(HttpResponse.ResponseInfo rinfo) {
assertEquals(rinfo.statusCode(), 200);
assertEquals(200, rinfo.statusCode());
return BodySubscribers.mapping(
new CRSBodySubscriber(), (s) -> s.getBytes(UTF_8)
);
@ -213,8 +215,8 @@ public class MappingResponseSubscriber {
+ server.getAddress().getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
// HTTP/1.1
HttpHandler h1_fixedLengthHandler = new HTTP1_FixedLengthHandler();
HttpHandler h1_chunkHandler = new HTTP1_ChunkedHandler();
@ -254,8 +256,8 @@ public class MappingResponseSubscriber {
https2TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop(0);
httpsTestServer.stop(0);
http2TestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -27,7 +27,7 @@
* @summary Should HttpClient support SETTINGS_MAX_CONCURRENT_STREAMS from the server
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm MaxStreams
* @run junit/othervm MaxStreams
*/
import java.io.IOException;
@ -53,24 +53,24 @@ import jdk.httpclient.test.lib.http2.Http2TestServer;
import jdk.httpclient.test.lib.http2.Http2TestExchange;
import jdk.httpclient.test.lib.http2.Http2Handler;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class MaxStreams {
Http2TestServer http2TestServer; // HTTP/2 ( h2c )
Http2TestServer https2TestServer; // HTTP/2 ( h2 )
final Http2FixedHandler handler = new Http2FixedHandler();
private static Http2TestServer http2TestServer; // HTTP/2 ( h2c )
private static Http2TestServer https2TestServer; // HTTP/2 ( h2 )
private static final Http2FixedHandler handler = new Http2FixedHandler();
private static final SSLContext ctx = SimpleSSLContext.findSSLContext();
String http2FixedURI;
String https2FixedURI;
ExecutorService exec;
private static String http2FixedURI;
private static String https2FixedURI;
private static ExecutorService exec;
// we send an initial warm up request, then MAX_STREAMS+1 requests
// in parallel. The last of them should hit the limit.
@ -81,8 +81,7 @@ public class MaxStreams {
static final int MAX_STREAMS = 10;
static final String RESPONSE = "Hello world";
@DataProvider(name = "uris")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{http2FixedURI},
{https2FixedURI},
@ -92,7 +91,8 @@ public class MaxStreams {
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testAsString(String uri) throws Exception {
CountDownLatch latch = new CountDownLatch(1);
handler.setLatch(latch);
@ -161,8 +161,8 @@ public class MaxStreams {
System.err.println("Test OK");
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
exec = Executors.newCachedThreadPool();
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
@ -180,13 +180,13 @@ public class MaxStreams {
https2TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
System.err.println("Stopping test server now");
http2TestServer.stop();
}
class Http2FixedHandler implements Http2Handler {
static class Http2FixedHandler implements Http2Handler {
final AtomicInteger counter = new AtomicInteger(0);
volatile CountDownLatch latch;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2026, 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
@ -27,7 +27,7 @@
* @summary Test response body handlers/subscribers when there is no body
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.http2.Http2TestServer
* @run testng/othervm
* @run junit/othervm
* -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=all
* NoBodyPartOne
@ -42,16 +42,21 @@ import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodyHandlers;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Version.HTTP_3;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
// @TestInstance(TestInstance.Lifecycle.PER_CLASS)
// is inherited from the super class
public class NoBodyPartOne extends AbstractNoBody {
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsString(String uri, boolean sameClient) throws Exception {
printStamp(START, "testAsString(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -70,12 +75,13 @@ public class NoBodyPartOne extends AbstractNoBody {
: BodyHandlers.ofString(UTF_8);
HttpResponse<String> response = client.send(req, handler);
String body = response.body();
assertEquals(body, "");
assertEquals("", body);
}
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsFile(String uri, boolean sameClient) throws Exception {
printStamp(START, "testAsFile(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -94,14 +100,15 @@ public class NoBodyPartOne extends AbstractNoBody {
Path p = Paths.get("NoBody_testAsFile.txt");
HttpResponse<Path> response = client.send(req, BodyHandlers.ofFile(p));
Path bodyPath = response.body();
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
assertTrue(Files.exists(bodyPath));
assertEquals(Files.size(bodyPath), 0, Files.readString(bodyPath));
assertEquals(0, Files.size(bodyPath), Files.readString(bodyPath));
}
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsByteArray(String uri, boolean sameClient) throws Exception {
printStamp(START, "testAsByteArray(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -119,7 +126,7 @@ public class NoBodyPartOne extends AbstractNoBody {
.build();
HttpResponse<byte[]> response = client.send(req, BodyHandlers.ofByteArray());
byte[] body = response.body();
assertEquals(body.length, 0);
assertEquals(0, body.length);
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2026, 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
@ -27,7 +27,7 @@
* @summary Test request and response body handlers/subscribers when there is no body
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.http2.Http2TestServer
* @run testng/othervm
* @run junit/othervm
* -Djdk.httpclient.HttpClient.log=quic,errors
* -Djdk.httpclient.HttpClient.log=all
* NoBodyPartThree
@ -46,19 +46,24 @@ import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import jdk.internal.net.http.common.Utils;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Version.HTTP_3;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
// @TestInstance(TestInstance.Lifecycle.PER_CLASS)
// is inherited from the super class
public class NoBodyPartThree extends AbstractNoBody {
static final AtomicInteger REQID = new AtomicInteger();
volatile boolean consumerHasBeenCalled;
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsByteArrayPublisher(String uri, boolean sameClient) throws Exception {
printStamp(START, "testAsByteArrayPublisher(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -83,7 +88,7 @@ public class NoBodyPartThree extends AbstractNoBody {
consumerHasBeenCalled = false;
var response = client.send(req, BodyHandlers.ofByteArrayConsumer(consumer));
assertTrue(consumerHasBeenCalled);
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
u = uri + "/testAsByteArrayPublisher/second/" + REQID.getAndIncrement();
req = newRequestBuilder(u + "?echo")
@ -93,12 +98,13 @@ public class NoBodyPartThree extends AbstractNoBody {
consumerHasBeenCalled = false;
response = client.send(req, BodyHandlers.ofByteArrayConsumer(consumer));
assertTrue(consumerHasBeenCalled);
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
}
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testStringPublisher(String uri, boolean sameClient) throws Exception {
printStamp(START, "testStringPublisher(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -116,14 +122,15 @@ public class NoBodyPartThree extends AbstractNoBody {
.build();
System.out.println("sending " + req);
HttpResponse<InputStream> response = client.send(req, BodyHandlers.ofInputStream());
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
byte[] body = response.body().readAllBytes();
assertEquals(body.length, 0);
assertEquals(0, body.length);
}
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testInputStreamPublisherBuffering(String uri, boolean sameClient) throws Exception {
printStamp(START, "testInputStreamPublisherBuffering(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -142,14 +149,15 @@ public class NoBodyPartThree extends AbstractNoBody {
System.out.println("sending " + req);
HttpResponse<byte[]> response = client.send(req,
BodyHandlers.buffering(BodyHandlers.ofByteArray(), 1024));
assertEquals(response.statusCode(), 200);
assertEquals(200, response.statusCode());
byte[] body = response.body();
assertEquals(body.length, 0);
assertEquals(0, body.length);
}
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testEmptyArrayPublisher(String uri, boolean sameClient) throws Exception {
printStamp(START, "testEmptyArrayPublisher(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -167,8 +175,8 @@ public class NoBodyPartThree extends AbstractNoBody {
.build();
System.out.println("sending " + req);
var response = client.send(req, BodyHandlers.ofLines());
assertEquals(response.statusCode(), 200);
assertEquals(response.body().toList(), List.of());
assertEquals(200, response.statusCode());
assertEquals(List.of(), response.body().toList());
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2026, 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
@ -27,7 +27,7 @@
* @summary Test response body handlers/subscribers when there is no body
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.http2.Http2TestServer
* @run testng/othervm
* @run junit/othervm
* -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=all
* NoBodyPartTwo
@ -44,17 +44,22 @@ import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import jdk.internal.net.http.common.Utils;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Version.HTTP_3;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
// @TestInstance(TestInstance.Lifecycle.PER_CLASS)
// is inherited from the super class
public class NoBodyPartTwo extends AbstractNoBody {
volatile boolean consumerHasBeenCalled;
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsByteArrayConsumer(String uri, boolean sameClient) throws Exception {
printStamp(START, "testAsByteArrayConsumer(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -81,7 +86,8 @@ public class NoBodyPartTwo extends AbstractNoBody {
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testAsInputStream(String uri, boolean sameClient) throws Exception {
printStamp(START, "testAsInputStream(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -98,12 +104,13 @@ public class NoBodyPartTwo extends AbstractNoBody {
.build();
HttpResponse<InputStream> response = client.send(req, BodyHandlers.ofInputStream());
byte[] body = response.body().readAllBytes();
assertEquals(body.length, 0);
assertEquals(0, body.length);
}
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testBuffering(String uri, boolean sameClient) throws Exception {
printStamp(START, "testBuffering(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -121,12 +128,13 @@ public class NoBodyPartTwo extends AbstractNoBody {
HttpResponse<byte[]> response = client.send(req,
BodyHandlers.buffering(BodyHandlers.ofByteArray(), 1024));
byte[] body = response.body();
assertEquals(body.length, 0);
assertEquals(0, body.length);
}
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void testDiscard(String uri, boolean sameClient) throws Exception {
printStamp(START, "testDiscard(\"%s\", %s)", uri, sameClient);
HttpClient client = null;
@ -143,7 +151,7 @@ public class NoBodyPartTwo extends AbstractNoBody {
.build();
Object obj = new Object();
HttpResponse<Object> response = client.send(req, BodyHandlers.replacing(obj));
assertEquals(response.body(), obj);
assertEquals(obj, response.body());
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -29,7 +29,7 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* @compile -encoding utf-8 NonAsciiCharsInURI.java
* @run testng/othervm
* @run junit/othervm
* -Djdk.httpclient.HttpClient.log=requests,headers,errors,quic
* NonAsciiCharsInURI
*/
@ -51,10 +51,6 @@ import java.util.List;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.httpclient.test.lib.http3.Http3TestServer;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.err;
import static java.lang.System.out;
import static java.net.http.HttpClient.Version.HTTP_1_1;
@ -63,24 +59,29 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class NonAsciiCharsInURI implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
String http3URI_head;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
private static String http3URI_head;
private volatile HttpClient sharedClient;
private static volatile HttpClient sharedClient;
// = '\u20AC' => 0xE20x820xAC
static final String[][] pathsAndQueryStrings = new String[][] {
@ -93,8 +94,7 @@ public class NonAsciiCharsInURI implements HttpServerAdapters {
{ "/006/x?url=https://ja.wikipedia.org/wiki/エリザベス1世_(イングランド女王)" },
};
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
List<Object[]> list = new ArrayList<>();
for (boolean sameClient : new boolean[] { false, true }) {
@ -136,7 +136,7 @@ public class NonAsciiCharsInURI implements HttpServerAdapters {
return null;
}
HttpRequest.Builder newRequestBuilder(String uri) {
static HttpRequest.Builder newRequestBuilder(String uri) {
var builder = HttpRequest.newBuilder(URI.create(uri));
if (version(uri) == HTTP_3) {
builder.version(HTTP_3);
@ -145,7 +145,7 @@ public class NonAsciiCharsInURI implements HttpServerAdapters {
return builder;
}
HttpResponse<String> headRequest(HttpClient client)
static HttpResponse<String> headRequest(HttpClient client)
throws IOException, InterruptedException
{
out.println("\n" + now() + "--- Sending HEAD request ----\n");
@ -154,25 +154,26 @@ public class NonAsciiCharsInURI implements HttpServerAdapters {
var request = newRequestBuilder(http3URI_head)
.HEAD().version(HTTP_2).build();
var response = client.send(request, BodyHandlers.ofString());
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), HTTP_2);
assertEquals(200, response.statusCode());
assertEquals(HTTP_2, response.version());
out.println("\n" + now() + "--- HEAD request succeeded ----\n");
err.println("\n" + now() + "--- HEAD request succeeded ----\n");
return response;
}
private HttpClient makeNewClient() {
return newClientBuilderForH3()
private static HttpClient makeNewClient() {
return HttpServerAdapters.createClientBuilderForH3()
.proxy(NO_PROXY)
.sslContext(sslContext)
.build();
}
HttpClient newHttpClient(boolean share) {
private static final Object zis = new Object();
static HttpClient newHttpClient(boolean share) {
if (!share) return makeNewClient();
HttpClient shared = sharedClient;
if (shared != null) return shared;
synchronized (this) {
synchronized (zis) {
shared = sharedClient;
if (shared == null) {
shared = sharedClient = makeNewClient();
@ -191,7 +192,8 @@ public class NonAsciiCharsInURI implements HttpServerAdapters {
static final int ITERATION_COUNT = 3; // checks upgrade and re-use
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
void test(String uriString, boolean sameClient) throws Exception {
out.println("\n--- Starting ");
// The single-argument factory requires any illegal characters in its
@ -215,7 +217,7 @@ public class NonAsciiCharsInURI implements HttpServerAdapters {
out.println("Got response: " + resp);
out.println("Got body: " + resp.body());
assertEquals(resp.statusCode(), 200,
assertEquals(200, resp.statusCode(),
"Expected 200, got:" + resp.statusCode());
// the response body should contain the toASCIIString
@ -228,12 +230,13 @@ public class NonAsciiCharsInURI implements HttpServerAdapters {
} else {
out.println("Found expected " + resp.body() + " in " + expectedURIString);
}
assertEquals(resp.version(), version(uriString));
assertEquals(version(uriString), resp.version());
}
}
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
void testAsync(String uriString, boolean sameClient) throws Exception {
out.println("\n--- Starting ");
URI uri = URI.create(uriString);
@ -254,8 +257,8 @@ public class NonAsciiCharsInURI implements HttpServerAdapters {
.thenApply(response -> {
out.println("Got response: " + response);
out.println("Got body: " + response.body());
assertEquals(response.statusCode(), 200);
assertEquals(response.version(), version(uriString));
assertEquals(200, response.statusCode());
assertEquals(version(uriString), response.version());
return response.body();
})
.thenAccept(body -> {
@ -276,8 +279,8 @@ public class NonAsciiCharsInURI implements HttpServerAdapters {
}
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
out.println(now() + "begin setup");
HttpTestHandler handler = new HttpUriStringHandler();
@ -324,8 +327,8 @@ public class NonAsciiCharsInURI implements HttpServerAdapters {
err.println(now() + "setup done");
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
sharedClient.close();
httpTestServer.stop();
httpsTestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -26,7 +26,7 @@
* @summary Method change during redirection
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm RedirectMethodChange
* @run junit/othervm RedirectMethodChange
*/
import javax.net.ssl.SSLContext;
@ -41,33 +41,34 @@ import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class RedirectMethodChange implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpClient client;
private static HttpClient client;
HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
static final String RESPONSE = "Hello world";
static final String POST_BODY = "This is the POST body 123909090909090";
@ -86,8 +87,7 @@ public class RedirectMethodChange implements HttpServerAdapters {
}
}
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][] {
{ http3URI, "GET", 301, "GET" },
{ http3URI, "GET", 302, "GET" },
@ -180,7 +180,8 @@ public class RedirectMethodChange implements HttpServerAdapters {
return builder;
}
@Test(dataProvider = "variants")
@ParameterizedTest
@MethodSource("variants")
public void test(String uriString,
String method,
int redirectCode,
@ -195,15 +196,15 @@ public class RedirectMethodChange implements HttpServerAdapters {
HttpResponse<String> resp = client.send(req, BodyHandlers.ofString());
System.out.println("Response: " + resp + ", body: " + resp.body());
assertEquals(resp.statusCode(), 200);
assertEquals(resp.body(), RESPONSE);
assertEquals(200, resp.statusCode());
assertEquals(RESPONSE, resp.body());
}
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
client = newClientBuilderForH3()
@BeforeAll
public static void setup() throws Exception {
client = HttpServerAdapters.createClientBuilderForH3()
.followRedirects(HttpClient.Redirect.NORMAL)
.sslContext(sslContext)
.build();
@ -245,8 +246,8 @@ public class RedirectMethodChange implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
client.close();
httpTestServer.stop();
httpsTestServer.stop();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2026, 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
@ -29,16 +29,11 @@
* an HttpTimeoutException during the redirected request.
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm -Djdk.httpclient.HttpClient.log=errors,trace -Djdk.internal.httpclient.debug=false RedirectTimeoutTest
* @run junit/othervm -Djdk.httpclient.HttpClient.log=errors,trace -Djdk.internal.httpclient.debug=false RedirectTimeoutTest
*/
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.TestException;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.io.IOException;
import java.io.OutputStream;
@ -64,6 +59,12 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static jdk.test.lib.Utils.adjustTimeout;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.fail;
public class RedirectTimeoutTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
@ -75,8 +76,8 @@ public class RedirectTimeoutTest implements HttpServerAdapters {
public static final int ITERATIONS = 4;
private static final PrintStream out = System.out;
@BeforeTest
public void setup() throws IOException {
@BeforeAll
public static void setup() throws IOException {
h1TestServer = HttpTestServer.create(HTTP_1_1);
h2TestServer = HttpTestServer.create(HTTP_2);
h3TestServer = HttpTestServer.create(HTTP_3_URI_ONLY, sslContext);
@ -101,15 +102,14 @@ public class RedirectTimeoutTest implements HttpServerAdapters {
h3TestServer.start();
}
@AfterTest
public void teardown() {
@AfterAll
public static void teardown() {
h1TestServer.stop();
h2TestServer.stop();
h3TestServer.stop();
}
@DataProvider(name = "testData")
public Object[][] testData() {
public static Object[][] testData() {
return new Object[][] {
{ HTTP_3, h3Uri, h3RedirectUri },
{ HTTP_1_1, h1Uri, h1RedirectUri },
@ -117,7 +117,8 @@ public class RedirectTimeoutTest implements HttpServerAdapters {
};
}
@Test(dataProvider = "testData")
@ParameterizedTest
@MethodSource("testData")
public void test(Version version, URI uri, URI redirectURI) throws InterruptedException {
out.println("Testing for " + version);
testRedirectURI = redirectURI;
@ -159,7 +160,7 @@ public class RedirectTimeoutTest implements HttpServerAdapters {
} catch (IOException e) {
if (e.getClass() == HttpTimeoutException.class) {
e.printStackTrace(System.out);
throw new TestException("Timeout from original HttpRequest expired on redirect when it should have been cancelled.");
fail("Timeout from original HttpRequest expired on redirect when it should have been cancelled.");
} else {
throw new RuntimeException(e);
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -26,7 +26,7 @@
* @summary Test for cookie handling when redirecting
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm
* @run junit/othervm
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* RedirectWithCookie
*/
@ -45,10 +45,6 @@ import java.util.List;
import javax.net.ssl.SSLContext;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
@ -56,28 +52,32 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class RedirectWithCookie implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
static final String MESSAGE = "BasicRedirectTest message body";
static final int ITERATIONS = 3;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ http3URI, },
{ httpURI, },
@ -96,7 +96,8 @@ public class RedirectWithCookie implements HttpServerAdapters {
return builder;
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void test(String uriString) throws Exception {
out.printf("%n---- starting (%s) ----%n", uriString);
var builder = uriString.contains("/http3/")
@ -120,8 +121,8 @@ public class RedirectWithCookie implements HttpServerAdapters {
out.println(" Got response: " + response);
out.println(" Got body Path: " + response.body());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), MESSAGE);
assertEquals(200, response.statusCode());
assertEquals(MESSAGE, response.body());
// asserts redirected URI in response.request().uri()
assertTrue(response.uri().getPath().endsWith("message"));
assertPreviousRedirectResponses(request, response);
@ -142,7 +143,7 @@ public class RedirectWithCookie implements HttpServerAdapters {
response = response.previousResponse().get();
assertTrue(300 <= response.statusCode() && response.statusCode() <= 309,
"Expected 300 <= code <= 309, got:" + response.statusCode());
assertEquals(response.body(), null, "Unexpected body: " + response.body());
assertEquals(null, response.body(), "Unexpected body: " + response.body());
String locationHeader = response.headers().firstValue("Location")
.orElseThrow(() -> new RuntimeException("no previous Location"));
assertTrue(uri.toString().endsWith(locationHeader),
@ -151,15 +152,15 @@ public class RedirectWithCookie implements HttpServerAdapters {
} while (response.previousResponse().isPresent());
// initial
assertEquals(initialRequest, response.request(),
assertEquals(response.request(), initialRequest,
String.format("Expected initial request [%s] to equal last prev req [%s]",
initialRequest, response.request()));
}
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpTestServer.create(HTTP_1_1);
httpTestServer.addHandler(new CookieRedirectHandler(), "/http1/cookie/");
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/cookie/redirect";
@ -185,8 +186,8 @@ public class RedirectWithCookie implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop();
httpsTestServer.stop();
http2TestServer.stop();

View File

@ -47,11 +47,11 @@ import static java.lang.System.out;
import static java.nio.charset.StandardCharsets.*;
import static java.nio.file.StandardOpenOption.*;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
@ -62,18 +62,18 @@ import static org.testng.Assert.*;
* @build LightWeightHttpServer
* @build jdk.test.lib.Platform
* @build jdk.test.lib.util.FileUtils
* @run testng/othervm RequestBodyTest
* @run junit/othervm RequestBodyTest
*/
public class RequestBodyTest {
static final String fileroot = System.getProperty("test.src", ".") + "/docs";
static final String midSizedFilename = "/files/notsobigfile.txt";
static final String smallFilename = "/files/smallfile.txt";
final ConcurrentHashMap<String,Throwable> failures = new ConcurrentHashMap<>();
private static final ConcurrentHashMap<String,Throwable> failures = new ConcurrentHashMap<>();
HttpClient client;
String httpURI;
String httpsURI;
private static HttpClient client;
private static String httpURI;
private static String httpsURI;
enum RequestBody {
BYTE_ARRAY,
@ -95,8 +95,8 @@ public class RequestBodyTest {
STRING_WITH_CHARSET,
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
LightWeightHttpServer.initServer();
httpURI = LightWeightHttpServer.httproot + "echo/foo";
httpsURI = LightWeightHttpServer.httpsroot + "echo/foo";
@ -109,8 +109,8 @@ public class RequestBodyTest {
.build();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
try {
LightWeightHttpServer.stop();
} finally {
@ -127,8 +127,7 @@ public class RequestBodyTest {
}
}
@DataProvider
public Object[][] exchanges() throws Exception {
public static Object[][] exchanges() throws Exception {
List<Object[]> values = new ArrayList<>();
for (boolean async : new boolean[] { false, true })
@ -143,7 +142,8 @@ public class RequestBodyTest {
return values.stream().toArray(Object[][]::new);
}
@Test(dataProvider = "exchanges")
@ParameterizedTest
@MethodSource("exchanges")
void exchange(String target,
RequestBody requestBodyType,
ResponseBody responseBodyType,
@ -239,8 +239,8 @@ public class RequestBodyTest {
BodyHandler<byte[]> bh = BodyHandlers.ofByteArray();
if (bufferResponseBody) bh = BodyHandlers.buffering(bh, 50);
HttpResponse<byte[]> bar = getResponse(client, request, bh, async);
assertEquals(bar.statusCode(), 200);
assertEquals(bar.body(), fileAsBytes);
assertEquals(200, bar.statusCode());
assertArrayEquals(fileAsBytes, bar.body());
break;
case BYTE_ARRAY_CONSUMER:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
@ -249,46 +249,46 @@ public class RequestBodyTest {
if (bufferResponseBody) bh1 = BodyHandlers.buffering(bh1, 49);
HttpResponse<Void> v = getResponse(client, request, bh1, async);
byte[] ba = baos.toByteArray();
assertEquals(v.statusCode(), 200);
assertEquals(ba, fileAsBytes);
assertEquals(200, v.statusCode());
assertArrayEquals(fileAsBytes, ba);
break;
case DISCARD:
Object o = new Object();
BodyHandler<Object> bh2 = BodyHandlers.replacing(o);
if (bufferResponseBody) bh2 = BodyHandlers.buffering(bh2, 51);
HttpResponse<Object> or = getResponse(client, request, bh2, async);
assertEquals(or.statusCode(), 200);
assertEquals(200, or.statusCode());
assertSame(or.body(), o);
break;
case FILE:
BodyHandler<Path> bh3 = BodyHandlers.ofFile(tempFile);
if (bufferResponseBody) bh3 = BodyHandlers.buffering(bh3, 48);
HttpResponse<Path> fr = getResponse(client, request, bh3, async);
assertEquals(fr.statusCode(), 200);
assertEquals(Files.size(tempFile), fileAsString.length());
assertEquals(Files.readAllBytes(tempFile), fileAsBytes);
assertEquals(200, fr.statusCode());
assertEquals(fileAsString.length(), Files.size(tempFile));
assertArrayEquals(fileAsBytes, Files.readAllBytes(tempFile));
break;
case FILE_WITH_OPTION:
BodyHandler<Path> bh4 = BodyHandlers.ofFile(tempFile, CREATE_NEW, WRITE);
if (bufferResponseBody) bh4 = BodyHandlers.buffering(bh4, 52);
fr = getResponse(client, request, bh4, async);
assertEquals(fr.statusCode(), 200);
assertEquals(Files.size(tempFile), fileAsString.length());
assertEquals(Files.readAllBytes(tempFile), fileAsBytes);
assertEquals(200, fr.statusCode());
assertEquals(fileAsString.length(), Files.size(tempFile));
assertArrayEquals(fileAsBytes, Files.readAllBytes(tempFile));
break;
case STRING:
BodyHandler<String> bh5 = BodyHandlers.ofString();
if(bufferResponseBody) bh5 = BodyHandlers.buffering(bh5, 47);
HttpResponse<String> sr = getResponse(client, request, bh5, async);
assertEquals(sr.statusCode(), 200);
assertEquals(sr.body(), fileAsString);
assertEquals(200, sr.statusCode());
assertEquals(fileAsString, sr.body());
break;
case STRING_WITH_CHARSET:
BodyHandler<String> bh6 = BodyHandlers.ofString(StandardCharsets.UTF_8);
if (bufferResponseBody) bh6 = BodyHandlers.buffering(bh6, 53);
HttpResponse<String> r = getResponse(client, request, bh6, async);
assertEquals(r.statusCode(), 200);
assertEquals(r.body(), fileAsString);
assertEquals(200, r.statusCode());
assertEquals(fileAsString, r.body());
break;
default:
throw new AssertionError("Unknown response body:" + responseBodyType);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -25,7 +25,7 @@
* @test
* @bug 8276559
* @summary HttpRequest[.Builder] API and behaviour checks
* @run testng RequestBuilderTest
* @run junit RequestBuilderTest
*/
import java.net.URI;
@ -49,9 +49,9 @@ import static java.time.Duration.ofNanos;
import static java.time.Duration.ofMinutes;
import static java.time.Duration.ofSeconds;
import static java.time.Duration.ZERO;
import static org.testng.Assert.*;
import org.testng.annotations.Test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
public class RequestBuilderTest {
@ -70,12 +70,12 @@ public class RequestBuilderTest {
newBuilder(uri).copy());
for (HttpRequest.Builder builder : builders) {
assertFalse(builder.build().expectContinue());
assertEquals(builder.build().method(), "GET");
assertEquals("GET", builder.build().method());
assertFalse(builder.build().bodyPublisher().isPresent());
assertFalse(builder.build().version().isPresent());
assertFalse(builder.build().timeout().isPresent());
assertTrue(builder.build().headers() != null);
assertEquals(builder.build().headers().map().size(), 0);
assertEquals(0, builder.build().headers().map().size());
}
}
@ -128,61 +128,61 @@ public class RequestBuilderTest {
assertThrows(IAE, () -> newBuilder().uri(u));
}
assertEquals(newBuilder(uri).build().uri(), uri);
assertEquals(newBuilder().uri(uri).build().uri(), uri);
assertEquals(uri, newBuilder(uri).build().uri());
assertEquals(uri, newBuilder().uri(uri).build().uri());
URI https = URI.create("https://foo.com");
assertEquals(newBuilder(https).build().uri(), https);
assertEquals(newBuilder().uri(https).build().uri(), https);
assertEquals(https, newBuilder(https).build().uri());
assertEquals(https, newBuilder().uri(https).build().uri());
}
@Test
public void testMethod() {
HttpRequest request = newBuilder(uri).build();
assertEquals(request.method(), "GET");
assertEquals("GET", request.method());
assertTrue(!request.bodyPublisher().isPresent());
request = newBuilder(uri).GET().build();
assertEquals(request.method(), "GET");
assertEquals("GET", request.method());
assertTrue(!request.bodyPublisher().isPresent());
request = newBuilder(uri).POST(BodyPublishers.ofString("")).GET().build();
assertEquals(request.method(), "GET");
assertEquals("GET", request.method());
assertTrue(!request.bodyPublisher().isPresent());
request = newBuilder(uri).PUT(BodyPublishers.ofString("")).GET().build();
assertEquals(request.method(), "GET");
assertEquals("GET", request.method());
assertTrue(!request.bodyPublisher().isPresent());
request = newBuilder(uri).DELETE().GET().build();
assertEquals(request.method(), "GET");
assertEquals("GET", request.method());
assertTrue(!request.bodyPublisher().isPresent());
request = newBuilder(uri).POST(BodyPublishers.ofString("")).build();
assertEquals(request.method(), "POST");
assertEquals("POST", request.method());
assertTrue(request.bodyPublisher().isPresent());
request = newBuilder(uri).PUT(BodyPublishers.ofString("")).build();
assertEquals(request.method(), "PUT");
assertEquals("PUT", request.method());
assertTrue(request.bodyPublisher().isPresent());
request = newBuilder(uri).DELETE().build();
assertEquals(request.method(), "DELETE");
assertEquals("DELETE", request.method());
assertTrue(!request.bodyPublisher().isPresent());
request = newBuilder(uri).HEAD().build();
assertEquals(request.method(), "HEAD");
assertEquals("HEAD", request.method());
assertFalse(request.bodyPublisher().isPresent());
request = newBuilder(uri).GET().POST(BodyPublishers.ofString("")).build();
assertEquals(request.method(), "POST");
assertEquals("POST", request.method());
assertTrue(request.bodyPublisher().isPresent());
request = newBuilder(uri).GET().PUT(BodyPublishers.ofString("")).build();
assertEquals(request.method(), "PUT");
assertEquals("PUT", request.method());
assertTrue(request.bodyPublisher().isPresent());
request = newBuilder(uri).GET().DELETE().build();
assertEquals(request.method(), "DELETE");
assertEquals("DELETE", request.method());
assertTrue(!request.bodyPublisher().isPresent());
// CONNECT is disallowed in the implementation, since it is used for
@ -190,11 +190,11 @@ public class RequestBuilderTest {
assertThrows(IAE, () -> newBuilder(uri).method("CONNECT", BodyPublishers.noBody()).build());
request = newBuilder(uri).method("GET", BodyPublishers.noBody()).build();
assertEquals(request.method(), "GET");
assertEquals("GET", request.method());
assertTrue(request.bodyPublisher().isPresent());
request = newBuilder(uri).method("POST", BodyPublishers.ofString("")).build();
assertEquals(request.method(), "POST");
assertEquals("POST", request.method());
assertTrue(request.bodyPublisher().isPresent());
}
@ -207,7 +207,7 @@ public class RequestBuilderTest {
assertThrows(IAE, () -> builder.headers("1").build());
assertThrows(IAE, () -> builder.headers("1", "2", "3").build());
assertThrows(IAE, () -> builder.headers("1", "2", "3", "4", "5").build());
assertEquals(builder.build().headers().map().size(),0);
assertEquals(0, builder.build().headers().map().size());
List<HttpRequest> requests = List.of(
// same header built from different combinations of the API
@ -219,13 +219,13 @@ public class RequestBuilderTest {
);
for (HttpRequest r : requests) {
assertEquals(r.headers().map().size(), 1);
assertEquals(1, r.headers().map().size());
assertTrue(r.headers().firstValue("A").isPresent());
assertTrue(r.headers().firstValue("a").isPresent());
assertEquals(r.headers().firstValue("A").get(), "B");
assertEquals(r.headers().allValues("A"), List.of("B"));
assertEquals(r.headers().allValues("C").size(), 0);
assertEquals(r.headers().map().get("A"), List.of("B"));
assertEquals("B", r.headers().firstValue("A").get());
assertEquals(List.of("B"), r.headers().allValues("A"));
assertEquals(0, r.headers().allValues("C").size());
assertEquals(List.of("B"), r.headers().map().get("A"));
assertThrows(NFE, () -> r.headers().firstValueAsLong("A"));
assertFalse(r.headers().firstValue("C").isPresent());
// a non-exhaustive list of mutators
@ -265,14 +265,14 @@ public class RequestBuilderTest {
);
for (HttpRequest r : requests) {
assertEquals(r.headers().map().size(), 2);
assertEquals(2, r.headers().map().size());
assertTrue(r.headers().firstValue("A").isPresent());
assertEquals(r.headers().firstValue("A").get(), "B");
assertEquals(r.headers().allValues("A"), List.of("B"));
assertEquals("B", r.headers().firstValue("A").get());
assertEquals(List.of("B"), r.headers().allValues("A"));
assertTrue(r.headers().firstValue("C").isPresent());
assertEquals(r.headers().firstValue("C").get(), "D");
assertEquals(r.headers().allValues("C"), List.of("D"));
assertEquals(r.headers().map().get("C"), List.of("D"));
assertEquals("D", r.headers().firstValue("C").get());
assertEquals(List.of("D"), r.headers().allValues("C"));
assertEquals(List.of("D"), r.headers().map().get("C"));
assertThrows(NFE, () -> r.headers().firstValueAsLong("C"));
assertFalse(r.headers().firstValue("E").isPresent());
// a smaller non-exhaustive list of mutators
@ -304,11 +304,11 @@ public class RequestBuilderTest {
);
for (HttpRequest r : requests) {
assertEquals(r.headers().map().size(), 1);
assertEquals(1, r.headers().map().size());
assertTrue(r.headers().firstValue("A").isPresent());
assertTrue(r.headers().allValues("A").containsAll(List.of("B", "C")));
assertEquals(r.headers().allValues("C").size(), 0);
assertEquals(r.headers().map().get("A"), List.of("B", "C"));
assertEquals(0, r.headers().allValues("C").size());
assertEquals(List.of("B", "C"), r.headers().map().get("A"));
assertThrows(NFE, () -> r.headers().firstValueAsLong("A"));
assertFalse(r.headers().firstValue("C").isPresent());
// a non-exhaustive list of mutators
@ -340,11 +340,11 @@ public class RequestBuilderTest {
"aCCept-EnCODing", "accepT-encodinG")) {
assertTrue(r.headers().firstValue(name).isPresent());
assertTrue(r.headers().allValues(name).contains("gzip, deflate"));
assertEquals(r.headers().firstValue(name).get(), "gzip, deflate");
assertEquals(r.headers().allValues(name).size(), 1);
assertEquals(r.headers().map().size(), 1);
assertEquals(r.headers().map().get(name).size(), 1);
assertEquals(r.headers().map().get(name).get(0), "gzip, deflate");
assertEquals("gzip, deflate", r.headers().firstValue(name).get());
assertEquals(1, r.headers().allValues(name).size());
assertEquals(1, r.headers().map().size());
assertEquals(1, r.headers().map().get(name).size());
assertEquals("gzip, deflate", r.headers().map().get(name).get(0));
}
}
}
@ -391,7 +391,7 @@ public class RequestBuilderTest {
.GET(), "x-" + name, value).build();
String v = req.headers().firstValue("x-" + name).orElseThrow(
() -> new RuntimeException("header x-" + name + " not set"));
assertEquals(v, value);
assertEquals(value, v);
try {
f.withHeader(HttpRequest.newBuilder(uri)
.GET(), name, value).build();
@ -419,27 +419,27 @@ public class RequestBuilderTest {
builder.GET().timeout(ofSeconds(5)).version(HTTP_2).setHeader("A", "C");
HttpRequest copyRequest = copy.build();
assertEquals(copyRequest.uri(), uri);
assertEquals(copyRequest.expectContinue(), true);
assertEquals(copyRequest.headers().map().get("A"), List.of("B"));
assertEquals(copyRequest.method(), "POST");
assertEquals(copyRequest.bodyPublisher().isPresent(), true);
assertEquals(copyRequest.timeout().get(), ofSeconds(30));
assertEquals(uri, copyRequest.uri());
assertEquals(true, copyRequest.expectContinue());
assertEquals(List.of("B"), copyRequest.headers().map().get("A"));
assertEquals("POST", copyRequest.method());
assertEquals(true, copyRequest.bodyPublisher().isPresent());
assertEquals(ofSeconds(30), copyRequest.timeout().get());
assertTrue(copyRequest.version().isPresent());
assertEquals(copyRequest.version().get(), HTTP_1_1);
assertEquals(HTTP_1_1, copyRequest.version().get());
assertTrue(copyRequest.getOption(H3_DISCOVERY).isPresent());
assertEquals(copyRequest.getOption(H3_DISCOVERY).get(), HTTP_3_URI_ONLY);
assertEquals(HTTP_3_URI_ONLY, copyRequest.getOption(H3_DISCOVERY).get());
// lazy set URI ( maybe builder as a template )
copyRequest = newBuilder().copy().uri(uri).build();
assertEquals(copyRequest.uri(), uri);
assertEquals(uri, copyRequest.uri());
builder = newBuilder().header("C", "D");
copy = builder.copy();
copy.uri(uri);
copyRequest = copy.build();
assertEquals(copyRequest.uri(), uri);
assertEquals(copyRequest.headers().firstValue("C").get(), "D");
assertEquals(uri, copyRequest.uri());
assertEquals("D", copyRequest.headers().firstValue("C").get());
}
@Test
@ -449,42 +449,41 @@ public class RequestBuilderTest {
assertThrows(IAE, () -> builder.timeout(ofSeconds(0)));
assertThrows(IAE, () -> builder.timeout(ofSeconds(-1)));
assertThrows(IAE, () -> builder.timeout(ofNanos(-100)));
assertEquals(builder.timeout(ofNanos(15)).build().timeout().get(), ofNanos(15));
assertEquals(builder.timeout(ofSeconds(50)).build().timeout().get(), ofSeconds(50));
assertEquals(builder.timeout(ofMinutes(30)).build().timeout().get(), ofMinutes(30));
assertEquals(ofNanos(15), builder.timeout(ofNanos(15)).build().timeout().get());
assertEquals(ofSeconds(50), builder.timeout(ofSeconds(50)).build().timeout().get());
assertEquals(ofMinutes(30), builder.timeout(ofMinutes(30)).build().timeout().get());
}
@Test
public void testExpect() {
HttpRequest.Builder builder = newBuilder(uri);
assertEquals(builder.build().expectContinue(), false);
assertEquals(builder.expectContinue(true).build().expectContinue(), true);
assertEquals(builder.expectContinue(false).build().expectContinue(), false);
assertEquals(builder.expectContinue(true).build().expectContinue(), true);
assertEquals(false, builder.build().expectContinue());
assertEquals(true, builder.expectContinue(true).build().expectContinue());
assertEquals(false, builder.expectContinue(false).build().expectContinue());
assertEquals(true, builder.expectContinue(true).build().expectContinue());
}
@Test
public void testEquals() {
assertNotEquals(newBuilder(URI.create("http://foo.com")),
newBuilder(URI.create("http://bar.com")));
assertNotEquals( newBuilder(URI.create("http://bar.com")), newBuilder(URI.create("http://foo.com")));
HttpRequest.Builder builder = newBuilder(uri);
assertEquals(builder.build(), builder.build());
assertEquals(builder.build(), newBuilder(uri).build());
assertEquals(newBuilder(uri).build(), builder.build());
builder.POST(BodyPublishers.noBody());
assertEquals(builder.build(), builder.build());
assertEquals(builder.build(), newBuilder(uri).POST(BodyPublishers.noBody()).build());
assertEquals(builder.build(), newBuilder(uri).POST(BodyPublishers.ofString("")).build());
assertNotEquals(builder.build(), newBuilder(uri).build());
assertNotEquals(builder.build(), newBuilder(uri).GET().build());
assertNotEquals(builder.build(), newBuilder(uri).PUT(BodyPublishers.noBody()).build());
assertEquals(newBuilder(uri).POST(BodyPublishers.noBody()).build(), builder.build());
assertEquals(newBuilder(uri).POST(BodyPublishers.ofString("")).build(), builder.build());
assertNotEquals(newBuilder(uri).build(), builder.build());
assertNotEquals(newBuilder(uri).GET().build(), builder.build());
assertNotEquals(newBuilder(uri).PUT(BodyPublishers.noBody()).build(), builder.build());
builder = newBuilder(uri).header("x", "y");
assertEquals(builder.build(), builder.build());
assertEquals(builder.build(), newBuilder(uri).header("x", "y").build());
assertNotEquals(builder.build(), newBuilder(uri).header("x", "Z").build());
assertNotEquals(builder.build(), newBuilder(uri).header("z", "y").build());
assertEquals(newBuilder(uri).header("x", "y").build(), builder.build());
assertNotEquals(newBuilder(uri).header("x", "Z").build(), builder.build());
assertNotEquals(newBuilder(uri).header("z", "y").build(), builder.build());
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2022, 2026, 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
@ -42,10 +42,6 @@ import javax.net.ssl.SSLContext;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.test.lib.net.SimpleSSLContext;
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;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
@ -54,39 +50,44 @@ import static java.net.http.HttpClient.Version.valueOf;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
/**
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
/*
* @test
* @bug 8292044
* @summary Tests behaviour of HttpClient when server responds with 102 or 103 status codes
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.common.HttpServerAdapters
* jdk.httpclient.test.lib.http2.Http2TestServer
* @run testng/othervm -Djdk.internal.httpclient.debug=true
* @run junit/othervm -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=headers,requests,responses,errors Response1xxTest
*/
public class Response1xxTest implements HttpServerAdapters {
private static final String EXPECTED_RSP_BODY = "Hello World";
private ServerSocket serverSocket;
private Http11Server server;
private String http1RequestURIBase;
private static ServerSocket serverSocket;
private static Http11Server server;
private static String http1RequestURIBase;
private HttpTestServer http2Server; // h2c
private String http2RequestURIBase;
private static HttpTestServer http2Server; // h2c
private static String http2RequestURIBase;
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
private HttpTestServer https2Server; // h2
private String https2RequestURIBase;
private static HttpTestServer https2Server; // h2
private static String https2RequestURIBase;
private HttpTestServer http3Server; // h3
private String http3RequestURIBase;
private static HttpTestServer http3Server; // h3
private static String http3RequestURIBase;
private final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
@BeforeClass
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
serverSocket = new ServerSocket(0, 0, InetAddress.getLoopbackAddress());
server = new Http11Server(serverSocket);
new Thread(server).start();
@ -130,8 +131,8 @@ public class Response1xxTest implements HttpServerAdapters {
}
@AfterClass
public void teardown() throws Throwable {
@AfterAll
public static void teardown() throws Throwable {
try {
assertNoOutstandingClientOps();
} finally {
@ -269,7 +270,7 @@ public class Response1xxTest implements HttpServerAdapters {
static String readRequestLine(final Socket sock) throws IOException {
final InputStream is = sock.getInputStream();
final StringBuilder sb = new StringBuilder("");
final StringBuilder sb = new StringBuilder();
byte[] buf = new byte[1024];
while (!sb.toString().endsWith("\r\n\r\n")) {
final int numRead = is.read(buf);
@ -424,10 +425,10 @@ public class Response1xxTest implements HttpServerAdapters {
System.out.println("Issuing request to " + requestURI);
final HttpResponse<String> response = client.send(request,
BodyHandlers.ofString(StandardCharsets.UTF_8));
Assert.assertEquals(response.version(), version,
Assertions.assertEquals(version, response.version(),
"Unexpected HTTP version in response");
Assert.assertEquals(response.statusCode(), 200, "Unexpected response code");
Assert.assertEquals(response.body(), EXPECTED_RSP_BODY, "Unexpected response body");
Assertions.assertEquals(200, response.statusCode(), "Unexpected response code");
Assertions.assertEquals(EXPECTED_RSP_BODY, response.body(), "Unexpected response body");
}
}
@ -484,7 +485,7 @@ public class Response1xxTest implements HttpServerAdapters {
.build();
System.out.println("Issuing request to " + requestURI);
// we expect the request to timeout
Assert.assertThrows(HttpTimeoutException.class, () -> {
Assertions.assertThrows(HttpTimeoutException.class, () -> {
client.send(request, BodyHandlers.ofString(StandardCharsets.UTF_8));
});
}
@ -561,7 +562,7 @@ public class Response1xxTest implements HttpServerAdapters {
final HttpRequest request = requestBuilder.build();
System.out.println("Issuing request to " + requestURI);
// we expect the request to fail because the server sent an unexpected 101
Assert.assertThrows(ProtocolException.class,
Assertions.assertThrows(ProtocolException.class,
() -> client.send(request, BodyHandlers.ofString(StandardCharsets.UTF_8)));
}
@ -571,11 +572,11 @@ public class Response1xxTest implements HttpServerAdapters {
final HttpRequest request = HttpRequest.newBuilder(requestURI).build();
System.out.println("Issuing (warmup) request to " + requestURI);
final HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
Assert.assertEquals(response.statusCode(), 200, "Unexpected response code");
Assertions.assertEquals(200, response.statusCode(), "Unexpected response code");
}
// verifies that the HttpClient being tracked has no outstanding operations
private void assertNoOutstandingClientOps() throws AssertionError {
private static void assertNoOutstandingClientOps() throws AssertionError {
System.gc();
final AssertionError refCheckFailure = TRACKER.check(1000);
if (refCheckFailure != null) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -28,7 +28,7 @@
* @modules java.net.http/jdk.internal.net.http.common
* @library /test/lib
* @build jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm/timeout=480 ResponseBodyBeforeError
* @run junit/othervm/timeout=480 ResponseBodyBeforeError
*/
import java.io.Closeable;
@ -54,10 +54,6 @@ import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Flow;
import jdk.test.lib.net.SimpleSSLContext;
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 javax.net.ssl.SSLServerSocketFactory;
@ -67,28 +63,32 @@ import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ResponseBodyBeforeError {
ReplyingServer variableLengthServer;
ReplyingServer variableLengthHttpsServer;
ReplyingServer fixedLengthServer;
ReplyingServer fixedLengthHttpsServer;
private static ReplyingServer variableLengthServer;
private static ReplyingServer variableLengthHttpsServer;
private static ReplyingServer fixedLengthServer;
private static ReplyingServer fixedLengthHttpsServer;
String httpURIVarLen;
String httpsURIVarLen;
String httpURIFixLen;
String httpsURIFixLen;
private static String httpURIVarLen;
private static String httpsURIVarLen;
private static String httpURIFixLen;
private static String httpsURIFixLen;
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
static final String EXPECTED_RESPONSE_BODY =
"<html><body><h1>Heading</h1><p>Some Text</p></body></html>";
@DataProvider(name = "sanity")
public Object[][] sanity() {
public static Object[][] sanity() {
return new Object[][]{
{ httpURIVarLen + "?length=all" },
{ httpsURIVarLen + "?length=all" },
@ -97,7 +97,8 @@ public class ResponseBodyBeforeError {
};
}
@Test(dataProvider = "sanity")
@ParameterizedTest
@MethodSource("sanity")
void sanity(String url) throws Exception {
HttpClient client = HttpClient.newBuilder()
.proxy(NO_PROXY)
@ -106,15 +107,14 @@ public class ResponseBodyBeforeError {
HttpRequest request = HttpRequest.newBuilder(URI.create(url)).build();
HttpResponse<String> response = client.send(request, ofString());
String body = response.body();
assertEquals(body, EXPECTED_RESPONSE_BODY);
assertEquals(EXPECTED_RESPONSE_BODY, body);
client.sendAsync(request, ofString())
.thenApply(resp -> resp.body())
.thenAccept(b -> assertEquals(b, EXPECTED_RESPONSE_BODY))
.thenAccept(b -> assertEquals(EXPECTED_RESPONSE_BODY, b))
.join();
}
@DataProvider(name = "uris")
public Object[][] variants() {
public static Object[][] variants() {
Object[][] cases = new Object[][] {
// The length query string is the total number of response body
// bytes in the reply, before the server closes the connection. The
@ -182,7 +182,8 @@ public class ResponseBodyBeforeError {
static final int ITERATION_COUNT = 3;
static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testSynchronousAllRequestBody(String url,
String expectedPatrialBody,
boolean sameClient)
@ -210,7 +211,7 @@ public class ResponseBodyBeforeError {
} catch (IOException expected) {
String pm = bs.receivedAsString();
out.println("partial body received: " + pm);
assertEquals(pm, expectedPatrialBody);
assertEquals(expectedPatrialBody, pm);
}
}
} finally {
@ -221,7 +222,8 @@ public class ResponseBodyBeforeError {
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testAsynchronousAllRequestBody(String url,
String expectedPatrialBody,
boolean sameClient)
@ -250,7 +252,7 @@ public class ResponseBodyBeforeError {
if (ee.getCause() instanceof IOException) {
String pm = bs.receivedAsString();
out.println("partial body received: " + pm);
assertEquals(pm, expectedPatrialBody);
assertEquals(expectedPatrialBody, pm);
} else {
throw ee;
}
@ -536,8 +538,8 @@ public class ResponseBodyBeforeError {
+ server.getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
SSLContext.setDefault(sslContext);
variableLengthServer = new PlainVariableLengthServer();
@ -557,8 +559,8 @@ public class ResponseBodyBeforeError {
+ "/https1/fixed/foz";
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
variableLengthServer.close();
variableLengthHttpsServer.close();
fixedLengthServer.close();

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -28,22 +28,16 @@
* immediately with a Publisher<List<ByteBuffer>>
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext jdk.httpclient.test.lib.common.HttpServerAdapters
* @run testng/othervm/timeout=480 ResponsePublisher
* @run junit/othervm/timeout=480 ResponsePublisher
*/
import com.sun.net.httpserver.HttpServer;
import jdk.internal.net.http.common.OperationTrackers;
import jdk.test.lib.net.SimpleSSLContext;
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.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
@ -73,28 +67,33 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ResponsePublisher implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI_fixed;
String httpURI_chunk;
String httpsURI_fixed;
String httpsURI_chunk;
String http2URI_fixed;
String http2URI_chunk;
String https2URI_fixed;
String https2URI_chunk;
String http3URI_fixed;
String http3URI_chunk;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI_fixed;
private static String httpURI_chunk;
private static String httpsURI_fixed;
private static String httpsURI_chunk;
private static String http2URI_fixed;
private static String http2URI_chunk;
private static String https2URI_fixed;
private static String https2URI_chunk;
private static String http3URI_fixed;
private static String http3URI_chunk;
static final int ITERATION_COUNT = 3;
// a shared executor helps reduce the amount of threads created by the test
@ -139,8 +138,7 @@ public class ResponsePublisher implements HttpServerAdapters {
static final Supplier<BodyHandler<Publisher<List<ByteBuffer>>>> OF_PUBLISHER_TEST =
BHS.of(PublishingBodyHandler::new, "PublishingBodyHandler::new");
@DataProvider(name = "variants")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][]{
{ http3URI_fixed, false, OF_PUBLISHER_API },
{ http3URI_chunk, false, OF_PUBLISHER_API },
@ -190,7 +188,7 @@ public class ResponsePublisher implements HttpServerAdapters {
};
}
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
HttpClient newHttpClient(String uri) {
var builder = uri.contains("/http3/")
? newClientBuilderForH3()
@ -210,8 +208,9 @@ public class ResponsePublisher implements HttpServerAdapters {
return builder;
}
@Test(dataProvider = "variants")
public void testExceptions(String uri, boolean sameClient, BHS handlers) throws Exception {
@ParameterizedTest
@MethodSource("variants")
void testExceptions(String uri, boolean sameClient, BHS handlers) throws Exception {
HttpClient client = null;
for (int i=0; i< ITERATION_COUNT; i++) {
if (!sameClient || client == null)
@ -247,7 +246,7 @@ public class ResponsePublisher implements HttpServerAdapters {
}
// Get the final result and compare it with the expected body
String body = ofString.getBody().toCompletableFuture().get();
assertEquals(body, "");
assertEquals("", body);
// ensure client closes before next iteration
if (!sameClient) {
var tracker = TRACKER.getTracker(client);
@ -257,8 +256,9 @@ public class ResponsePublisher implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
public void testNoBody(String uri, boolean sameClient, BHS handlers) throws Exception {
@ParameterizedTest
@MethodSource("variants")
void testNoBody(String uri, boolean sameClient, BHS handlers) throws Exception {
HttpClient client = null;
for (int i=0; i< ITERATION_COUNT; i++) {
if (!sameClient || client == null)
@ -276,7 +276,7 @@ public class ResponsePublisher implements HttpServerAdapters {
response.body().subscribe(ofString);
// Get the final result and compare it with the expected body
String body = ofString.getBody().toCompletableFuture().get();
assertEquals(body, "");
assertEquals("", body);
// ensure client closes before next iteration
if (!sameClient) {
var tracker = TRACKER.getTracker(client);
@ -286,8 +286,9 @@ public class ResponsePublisher implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
public void testNoBodyAsync(String uri, boolean sameClient, BHS handlers) throws Exception {
@ParameterizedTest
@MethodSource("variants")
void testNoBodyAsync(String uri, boolean sameClient, BHS handlers) throws Exception {
HttpClient client = null;
for (int i=0; i< ITERATION_COUNT; i++) {
if (!sameClient || client == null)
@ -308,7 +309,7 @@ public class ResponsePublisher implements HttpServerAdapters {
return ofString.getBody();
});
// Get the final result and compare it with the expected body
assertEquals(result.get(), "");
assertEquals("", result.get());
// ensure client closes before next iteration
if (!sameClient) {
var tracker = TRACKER.getTracker(client);
@ -318,8 +319,9 @@ public class ResponsePublisher implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
public void testAsString(String uri, boolean sameClient, BHS handlers) throws Exception {
@ParameterizedTest
@MethodSource("variants")
void testAsString(String uri, boolean sameClient, BHS handlers) throws Exception {
HttpClient client = null;
for (int i=0; i< ITERATION_COUNT; i++) {
if (!sameClient || client == null)
@ -337,7 +339,7 @@ public class ResponsePublisher implements HttpServerAdapters {
response.body().subscribe(ofString);
// Get the final result and compare it with the expected body
String body = ofString.getBody().toCompletableFuture().get();
assertEquals(body, WITH_BODY);
assertEquals(WITH_BODY, body);
// ensure client closes before next iteration
if (!sameClient) {
var tracker = TRACKER.getTracker(client);
@ -347,8 +349,9 @@ public class ResponsePublisher implements HttpServerAdapters {
}
}
@Test(dataProvider = "variants")
public void testAsStringAsync(String uri, boolean sameClient, BHS handlers) throws Exception {
@ParameterizedTest
@MethodSource("variants")
void testAsStringAsync(String uri, boolean sameClient, BHS handlers) throws Exception {
HttpClient client = null;
for (int i=0; i< ITERATION_COUNT; i++) {
if (!sameClient || client == null)
@ -369,7 +372,7 @@ public class ResponsePublisher implements HttpServerAdapters {
});
// Get the final result and compare it with the expected body
String body = result.get();
assertEquals(body, WITH_BODY);
assertEquals(WITH_BODY, body);
// ensure client closes before next iteration
if (!sameClient) {
var tracker = TRACKER.getTracker(client);
@ -383,7 +386,7 @@ public class ResponsePublisher implements HttpServerAdapters {
static class PublishingBodyHandler implements BodyHandler<Publisher<List<ByteBuffer>>> {
@Override
public BodySubscriber<Publisher<List<ByteBuffer>>> apply(HttpResponse.ResponseInfo rinfo) {
assertEquals(rinfo.statusCode(), 200);
assertEquals(200, rinfo.statusCode());
return new PublishingBodySubscriber();
}
}
@ -392,7 +395,7 @@ public class ResponsePublisher implements HttpServerAdapters {
static class PublishingBodySubscriber implements BodySubscriber<Publisher<List<ByteBuffer>>> {
private final CompletableFuture<Flow.Subscription> subscriptionCF = new CompletableFuture<>();
private final CompletableFuture<Flow.Subscriber<? super List<ByteBuffer>>> subscribedCF = new CompletableFuture<>();
private AtomicReference<Flow.Subscriber<? super List<ByteBuffer>>> subscriberRef = new AtomicReference<>();
private final AtomicReference<Flow.Subscriber<? super List<ByteBuffer>>> subscriberRef = new AtomicReference<>();
private final CompletionStage<Publisher<List<ByteBuffer>>> body =
subscriptionCF.thenCompose((s) -> CompletableFuture.completedStage(this::subscribe));
//CompletableFuture.completedStage(this::subscribe);
@ -449,13 +452,8 @@ public class ResponsePublisher implements HttpServerAdapters {
}
}
static String serverAuthority(HttpServer server) {
return InetAddress.getLoopbackAddress().getHostName() + ":"
+ server.getAddress().getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
// HTTP/1.1
HttpTestHandler h1_fixedLengthHandler = new HTTP_FixedLengthHandler();
HttpTestHandler h1_chunkHandler = new HTTP_VariableLengthHandler();
@ -504,8 +502,8 @@ public class ResponsePublisher implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
Thread.sleep(100);
AssertionError fail = TRACKER.check(500);
try {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -24,8 +24,8 @@
/*
* @test
* @summary Ensure that the POST method is retied when the property is set.
* @run testng/othervm -Djdk.httpclient.enableAllMethodRetry RetryPost
* @run testng/othervm -Djdk.httpclient.enableAllMethodRetry=true RetryPost
* @run junit/othervm -Djdk.httpclient.enableAllMethodRetry RetryPost
* @run junit/othervm -Djdk.httpclient.enableAllMethodRetry=true RetryPost
*/
import java.io.IOException;
@ -41,26 +41,26 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class RetryPost {
FixedLengthServer fixedLengthServer;
String httpURIFixLen;
private static FixedLengthServer fixedLengthServer;
private static String httpURIFixLen;
static final String RESPONSE_BODY =
"You use a glass mirror to see your face: you use works of art to see your soul.";
@DataProvider(name = "uris")
public Object[][] variants() {
public static Object[][] variants() {
return new Object[][] {
{ httpURIFixLen, true },
{ httpURIFixLen, false },
@ -71,7 +71,8 @@ public class RetryPost {
static final String REQUEST_BODY = "Body";
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testSynchronousPOST(String url, boolean sameClient) throws Exception {
out.print("---\n");
HttpClient client = null;
@ -84,12 +85,13 @@ public class RetryPost {
HttpResponse<String> response = client.send(request, ofString());
String body = response.body();
out.println(response + ": " + body);
assertEquals(response.statusCode(), 200);
assertEquals(body, RESPONSE_BODY);
assertEquals(200, response.statusCode());
assertEquals(RESPONSE_BODY, body);
}
}
@Test(dataProvider = "uris")
@ParameterizedTest
@MethodSource("variants")
void testAsynchronousPOST(String url, boolean sameClient) {
out.print("---\n");
HttpClient client = null;
@ -101,9 +103,9 @@ public class RetryPost {
.build();
client.sendAsync(request, ofString())
.thenApply(r -> { out.println(r + ": " + r.body()); return r; })
.thenApply(r -> { assertEquals(r.statusCode(), 200); return r; })
.thenApply(r -> { assertEquals(200, r.statusCode()); return r; })
.thenApply(HttpResponse::body)
.thenAccept(b -> assertEquals(b, RESPONSE_BODY))
.thenAccept(b -> assertEquals(RESPONSE_BODY, b))
.join();
}
}
@ -223,15 +225,15 @@ public class RetryPost {
+ server.getPort();
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
fixedLengthServer = new FixedLengthServer();
httpURIFixLen = "http://" + serverAuthority(fixedLengthServer)
+ "/http1/fixed/baz";
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
fixedLengthServer.close();
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -29,16 +29,12 @@
* @build jdk.httpclient.test.lib.common.HttpServerAdapters
* jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* ReferenceTracker
* @run testng/othervm
* @run junit/othervm
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* RetryWithCookie
*/
import jdk.test.lib.net.SimpleSSLContext;
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;
@ -67,28 +63,32 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class RetryWithCookie implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 5 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
static final String MESSAGE = "BasicRedirectTest message body";
static final int ITERATIONS = 3;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ http3URI, },
{ httpURI, },
@ -99,7 +99,7 @@ public class RetryWithCookie implements HttpServerAdapters {
}
static final AtomicLong requestCounter = new AtomicLong();
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private HttpRequest.Builder newRequestBuilder(URI uri) {
var builder = HttpRequest.newBuilder(uri);
@ -110,7 +110,8 @@ public class RetryWithCookie implements HttpServerAdapters {
return builder;
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void test(String uriString) throws Exception {
out.printf("%n---- starting (%s) ----%n", uriString);
CookieManager cookieManager = new CookieManager();
@ -145,9 +146,9 @@ public class RetryWithCookie implements HttpServerAdapters {
out.println(" Got response: " + response);
out.println(" Got body Path: " + response.body());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), MESSAGE);
assertEquals(response.headers().allValues("X-Request-Cookie"), cookies);
assertEquals(200, response.statusCode());
assertEquals(MESSAGE, response.body());
assertEquals(cookies, response.headers().allValues("X-Request-Cookie"));
request = newRequestBuilder(uri)
.header("X-uuid", "uuid-" + requestCounter.incrementAndGet())
.build();
@ -156,8 +157,8 @@ public class RetryWithCookie implements HttpServerAdapters {
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpTestServer.create(HTTP_1_1);
httpTestServer.addHandler(new CookieRetryHandler(), "/http1/cookie/");
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/cookie/retry";
@ -183,8 +184,8 @@ public class RetryWithCookie implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
Thread.sleep(100);
AssertionError fail = TRACKER.check(500);
try {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2026, 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
@ -24,9 +24,11 @@
import java.io.UncheckedIOException;
import java.net.http.HttpClient;
import java.security.NoSuchAlgorithmException;
import org.testng.annotations.Test;
import static org.testng.Assert.expectThrows;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.Assertions;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.Test;
/*
* @test
@ -34,7 +36,7 @@ import static org.testng.Assert.fail;
* @summary This test verifies exception when resources for
* SSLcontext used by HttpClient are not available
* @build SSLExceptionTest
* @run testng/othervm -Djdk.tls.client.protocols="InvalidTLSv1.4"
* @run junit/othervm -Djdk.tls.client.protocols="InvalidTLSv1.4"
* SSLExceptionTest
*/
@ -47,12 +49,12 @@ public class SSLExceptionTest {
@Test
public void testHttpClientsslException() {
for (int i = 0; i < ITERATIONS; i++) {
excp = expectThrows(UncheckedIOException.class, HttpClient.newBuilder()::build);
excp = Assertions.assertThrows(UncheckedIOException.class, HttpClient.newBuilder()::build);
noSuchAlgo = excp.getCause().getCause();
if ( !(noSuchAlgo instanceof NoSuchAlgorithmException) ) {
fail("Test failed due to wrong exception cause : " + noSuchAlgo);
}
excp = expectThrows(UncheckedIOException.class, HttpClient::newHttpClient);
excp = Assertions.assertThrows(UncheckedIOException.class, HttpClient::newHttpClient);
noSuchAlgo = excp.getCause().getCause();
if ( !(noSuchAlgo instanceof NoSuchAlgorithmException) ) {
fail("Test failed due to wrong exception cause : " + noSuchAlgo);

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2026, 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
@ -27,16 +27,13 @@
* @library /test/lib
* @summary Check that sendResponseHeaders throws an IOException when headers
* have already been sent
* @run testng/othervm SendResponseHeadersTest
* @run junit/othervm SendResponseHeadersTest
*/
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import jdk.test.lib.net.URIBuilder;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.io.InputStream;
@ -54,16 +51,21 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import static java.net.http.HttpClient.Builder.NO_PROXY;
import static org.testng.Assert.expectThrows;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class SendResponseHeadersTest {
URI uri;
HttpServer server;
ExecutorService executor;
private static URI uri;
private static HttpServer server;
private static ExecutorService executor;
@BeforeTest
public void setUp() throws IOException, URISyntaxException {
@BeforeAll
public static void setUp() throws IOException, URISyntaxException {
var loopback = InetAddress.getLoopbackAddress();
var addr = new InetSocketAddress(loopback, 0);
server = HttpServer.create(addr, 0);
@ -94,8 +96,8 @@ public class SendResponseHeadersTest {
fail(response.body());
}
@AfterTest
public void tearDown() {
@AfterAll
public static void tearDown() {
server.stop(0);
executor.shutdown();
}
@ -108,7 +110,7 @@ public class SendResponseHeadersTest {
is.readAllBytes();
exchange.sendResponseHeaders(200, 0);
try {
IOException io = expectThrows(IOException.class,
IOException io = Assertions.assertThrows(IOException.class,
() -> exchange.sendResponseHeaders(200, 0));
System.out.println("Got expected exception: " + io);
} catch (Throwable t) {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -28,16 +28,11 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext
* jdk.httpclient.test.lib.common.HttpServerAdapters
* @run testng/othervm -Djdk.tls.acknowledgeCloseNotify=true ServerCloseTest
* @run junit/othervm -Djdk.tls.acknowledgeCloseNotify=true ServerCloseTest
*/
//* -Djdk.internal.httpclient.debug=true
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLContext;
@ -70,18 +65,22 @@ import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.httpclient.test.lib.http2.Http2TestServer;
import static java.lang.System.out;
import static java.nio.charset.StandardCharsets.UTF_8;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ServerCloseTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
DummyServer httpDummyServer; // HTTP/1.1 [ 2 servers ]
DummyServer httpsDummyServer; // HTTPS/1.1
String httpDummy;
String httpsDummy;
private static DummyServer httpDummyServer; // HTTP/1.1 [ 2 servers ]
private static DummyServer httpsDummyServer; // HTTPS/1.1
private static String httpDummy;
private static String httpsDummy;
static final int ITERATION_COUNT = 3;
// a shared executor helps reduce the amount of threads created by the test
@ -99,7 +98,7 @@ public class ServerCloseTest implements HttpServerAdapters {
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
}
private volatile HttpClient sharedClient;
private static volatile HttpClient sharedClient;
static class TestExecutor implements Executor {
final AtomicLong tasks = new AtomicLong();
@ -125,8 +124,8 @@ public class ServerCloseTest implements HttpServerAdapters {
}
}
@AfterClass
static final void printFailedTests() {
@AfterAll
static void printFailedTests() {
out.println("\n=========================");
try {
out.printf("%n%sCreated %d servers and %d clients%n",
@ -145,15 +144,14 @@ public class ServerCloseTest implements HttpServerAdapters {
}
}
private String[] uris() {
private static String[] uris() {
return new String[] {
httpDummy,
httpsDummy,
};
}
@DataProvider(name = "servers")
public Object[][] noThrows() {
public static Object[][] noThrows() {
String[] uris = uris();
Object[][] result = new Object[uris.length * 2][];
//Object[][] result = new Object[uris.length][];
@ -192,7 +190,8 @@ public class ServerCloseTest implements HttpServerAdapters {
final String ENCODED = "/01%252F03/";
@Test(dataProvider = "servers")
@ParameterizedTest
@MethodSource("noThrows")
public void testServerClose(String uri, boolean sameClient) {
HttpClient client = null;
out.printf("%n%s testServerClose(%s, %b)%n", now(), uri, sameClient);
@ -224,8 +223,8 @@ public class ServerCloseTest implements HttpServerAdapters {
}
}
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
InetSocketAddress sa = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
// DummyServer
@ -240,8 +239,8 @@ public class ServerCloseTest implements HttpServerAdapters {
httpsDummyServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
sharedClient = null;
httpDummyServer.stopServer();
httpsDummyServer.stopServer();
@ -324,7 +323,7 @@ public class ServerCloseTest implements HttpServerAdapters {
// Read all headers until we find the empty line that
// signals the end of all headers.
String line = requestLine;
while (!line.equals("")) {
while (!line.isEmpty()) {
System.out.println(now() + getName() + ": Reading header: "
+ (line = readLine(ccis)));
headers.append(line).append("\r\n");
@ -338,7 +337,7 @@ public class ServerCloseTest implements HttpServerAdapters {
byte[] b = uri.toString().getBytes(UTF_8);
if (index >= 0) {
index = index + "content-length: ".length();
String cl = headers.toString().substring(index);
String cl = headers.substring(index);
StringTokenizer tk = new StringTokenizer(cl);
int len = Integer.parseInt(tk.nextToken());
assert len < b.length * 2;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2023, 2026, 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
@ -32,7 +32,7 @@
* @build jdk.httpclient.test.lib.http2.Http2TestServer jdk.test.lib.net.SimpleSSLContext
* jdk.test.lib.RandomFactory jdk.test.lib.Utils
* ReferenceTracker
* @run testng/othervm
* @run junit/othervm
* -Djdk.internal.httpclient.debug=true
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* ShutdownNow
@ -66,10 +66,6 @@ import javax.net.ssl.SSLContext;
import jdk.test.lib.RandomFactory;
import jdk.test.lib.Utils;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Builder.NO_PROXY;
@ -80,9 +76,14 @@ import static java.net.http.HttpOption.Http3DiscoveryMode.ALT_SVC;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class ShutdownNow implements HttpServerAdapters {
@ -92,25 +93,24 @@ public class ShutdownNow implements HttpServerAdapters {
static final Random RANDOM = RandomFactory.getRandom();
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer h2h3TestServer; // HTTP/3 ( h2 + h3 )
HttpTestServer h3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String h2h3URI;
String h2h3Head;
String h3URI;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 4 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer h2h3TestServer; // HTTP/3 ( h2 + h3 )
private static HttpTestServer h3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String h2h3URI;
private static String h2h3Head;
private static String h3URI;
static final String MESSAGE = "ShutdownNow message body";
static final int ITERATIONS = 3;
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ h2h3URI, HTTP_3, h2h3TestServer.h3DiscoveryConfig()},
{ h3URI, HTTP_3, h3TestServer.h3DiscoveryConfig()},
@ -122,7 +122,7 @@ public class ShutdownNow implements HttpServerAdapters {
}
static final AtomicLong requestCounter = new AtomicLong();
final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
private static final ReferenceTracker TRACKER = ReferenceTracker.INSTANCE;
static Throwable getCause(Throwable t) {
while (t instanceof CompletionException || t instanceof ExecutionException) {
@ -137,7 +137,7 @@ public class ShutdownNow implements HttpServerAdapters {
.HEAD()
.build();
var resp = client.send(request, BodyHandlers.discarding());
assertEquals(resp.statusCode(), 200);
assertEquals(200, resp.statusCode());
}
static boolean hasExpectedMessage(IOException io) {
@ -176,7 +176,8 @@ public class ShutdownNow implements HttpServerAdapters {
throw new AssertionError(what + ": Unexpected exception: " + cause, cause);
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testConcurrent(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- starting concurrent (%s, %s, %s) ----%n%n", uriString, version, config);
HttpClient client = newClientBuilderForH3()
@ -217,8 +218,8 @@ public class ShutdownNow implements HttpServerAdapters {
var cf = responseCF.thenApply((response) -> {
out.println(si + ": Got response: " + response);
out.println(si + ": Got body Path: " + response.body());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), MESSAGE);
assertEquals(200, response.statusCode());
assertEquals(MESSAGE, response.body());
return response;
}).exceptionally((t) -> {
Throwable cause = getCause(t);
@ -243,7 +244,8 @@ public class ShutdownNow implements HttpServerAdapters {
}
}
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void testSequential(String uriString, Version version, Http3DiscoveryMode config) throws Exception {
out.printf("%n---- starting sequential (%s, %s, %s) ----%n%n",
uriString, version, config);
@ -284,8 +286,8 @@ public class ShutdownNow implements HttpServerAdapters {
responseCF.thenApply((response) -> {
out.println(si + ": Got response: " + response);
out.println(si + ": Got body Path: " + response.body());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), MESSAGE);
assertEquals(200, response.statusCode());
assertEquals(MESSAGE, response.body());
return response;
}).handle((r,t) -> {
if (t != null) {
@ -318,8 +320,8 @@ public class ShutdownNow implements HttpServerAdapters {
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
out.println("\n**** Setup ****\n");
httpTestServer = HttpTestServer.create(HTTP_1_1);
httpTestServer.addHandler(new ServerRequestHandler(), "/http1/exec/");
@ -352,8 +354,8 @@ public class ShutdownNow implements HttpServerAdapters {
h3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
Thread.sleep(100);
AssertionError fail = TRACKER.check(5000);
try {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, NTT DATA.
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@ -30,7 +30,7 @@
* @library /test/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters
* jdk.httpclient.test.lib.http2.Http2TestServer
* @run testng/othervm StreamCloseTest
* @run junit/othervm StreamCloseTest
*/
import java.io.InputStream;
@ -44,10 +44,10 @@ import java.net.http.HttpResponse.BodyHandlers;
import java.net.URI;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.Assert;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class StreamCloseTest {
@ -82,8 +82,8 @@ public class StreamCloseTest {
private static HttpServerAdapters.HttpTestServer httpTestServer;
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpServerAdapters.HttpTestServer.create(Version.HTTP_1_1);
httpTestServer.addHandler(new HttpServerAdapters.HttpTestEchoHandler(), "/");
URI uri = URI.create("http://" + httpTestServer.serverAuthority() + "/");
@ -96,8 +96,8 @@ public class StreamCloseTest {
requestBuilder = HttpRequest.newBuilder(uri);
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop();
}
@ -108,7 +108,7 @@ public class StreamCloseTest {
.POST(BodyPublishers.ofInputStream(() -> in))
.build();
client.send(request, BodyHandlers.discarding());
Assert.assertTrue(in.closeCalled, "InputStream was not closed!");
Assertions.assertTrue(in.closeCalled, "InputStream was not closed!");
}
@Test
@ -120,9 +120,9 @@ public class StreamCloseTest {
try {
client.send(request, BodyHandlers.discarding());
} catch (IOException e) { // expected
Assert.assertTrue(in.closeCalled, "InputStream was not closed!");
Assertions.assertTrue(in.closeCalled, "InputStream was not closed!");
return;
}
Assert.fail("IOException should be occurred!");
Assertions.fail("IOException should be occurred!");
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2017, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2017, 2026, 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
@ -36,26 +36,26 @@ import java.net.http.HttpResponse.BodySubscriber;
import java.net.http.HttpResponse.BodySubscribers;
import java.util.function.Function;
import org.testng.annotations.Test;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.DELETE_ON_CLOSE;
import static java.nio.file.StandardOpenOption.WRITE;
import static java.nio.file.StandardOpenOption.READ;
import static org.testng.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
/*
* @test
* @summary Basic tests for API specified exceptions from Handler,
* and Subscriber convenience static factory methods.
* @run testng SubscriberAPIExceptions
* @run junit SubscriberAPIExceptions
*/
public class SubscriberAPIExceptions {
static final Class<NullPointerException> NPE = NullPointerException.class;
static final Class<IllegalArgumentException> IAE = IllegalArgumentException.class;
static final Class<IndexOutOfBoundsException> IOB = IndexOutOfBoundsException.class;
@Test
public void handlerAPIExceptions() throws Exception {

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2016, 2026, 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
@ -21,7 +21,6 @@
* questions.
*/
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.ArrayList;
@ -33,15 +32,16 @@ import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
/*
* @test
* @compile TestKit.java
* @run testng TestKitTest
* @run junit TestKitTest
*/
public final class TestKitTest {
@ -50,15 +50,14 @@ public final class TestKitTest {
Integer integer = TestKit.assertNotThrows(
() -> TestKit.assertNotThrows(() -> 1)
);
assertEquals(integer, Integer.valueOf(1));
assertEquals(Integer.valueOf(1), integer);
RuntimeException re = TestKit.assertThrows(
RuntimeException.class,
() -> TestKit.assertNotThrows(() -> { throw new IOException(); })
);
assertEquals(re.getMessage(),
"Expected to run normally, but threw "
+ "java.io.IOException");
assertEquals("Expected to run normally, but threw "
+ "java.io.IOException", re.getMessage());
TestKit.assertNotThrows(
() -> TestKit.assertNotThrows(() -> { })
@ -68,9 +67,8 @@ public final class TestKitTest {
RuntimeException.class,
() -> TestKit.assertNotThrows((TestKit.ThrowingProcedure) () -> { throw new IOException(); })
);
assertEquals(re.getMessage(),
"Expected to run normally, but threw "
+ "java.io.IOException");
assertEquals("Expected to run normally, but threw "
+ "java.io.IOException", re.getMessage());
}
@Test
@ -87,13 +85,13 @@ public final class TestKitTest {
() -> TestKit.assertThrows(IOException.class, null)
);
assertNotNull(npe);
assertEquals(npe.getMessage(), "code");
assertEquals("code", npe.getMessage());
npe = TestKit.assertThrows(
NullPointerException.class,
() -> TestKit.assertThrows(null, () -> { })
);
assertEquals(npe.getMessage(), "clazz");
assertEquals("clazz", npe.getMessage());
npe = TestKit.assertThrows(
NullPointerException.class,
@ -101,16 +99,15 @@ public final class TestKitTest {
);
assertNotNull(npe);
assertNull(npe.getMessage());
assertEquals(npe.getClass(), NullPointerException.class);
assertEquals(NullPointerException.class, npe.getClass());
RuntimeException re = TestKit.assertThrows(
RuntimeException.class,
() -> TestKit.assertThrows(NullPointerException.class, () -> { })
);
assertEquals(re.getClass(), RuntimeException.class);
assertEquals(re.getMessage(),
"Expected to catch an exception of type "
+ "java.lang.NullPointerException, but caught nothing");
assertEquals(RuntimeException.class, re.getClass());
assertEquals("Expected to catch an exception of type "
+ "java.lang.NullPointerException, but caught nothing", re.getMessage());
re = TestKit.assertThrows(
RuntimeException.class,
@ -118,7 +115,7 @@ public final class TestKitTest {
);
assertNotNull(re);
assertNull(re.getMessage());
assertEquals(re.getClass(), NullPointerException.class);
assertEquals(NullPointerException.class, re.getClass());
re = TestKit.assertThrows(
RuntimeException.class,
@ -127,10 +124,9 @@ public final class TestKitTest {
() -> { throw new IndexOutOfBoundsException(); }
));
assertNotNull(re);
assertEquals(re.getClass(), RuntimeException.class);
assertEquals(re.getMessage(),
"Expected to catch an exception of type java.util.IllegalFormatException"
+ ", but caught java.lang.IndexOutOfBoundsException");
assertEquals(RuntimeException.class, re.getClass());
assertEquals("Expected to catch an exception of type java.util.IllegalFormatException"
+ ", but caught java.lang.IndexOutOfBoundsException", re.getMessage());
}
@Test

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2026, 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
@ -36,19 +36,22 @@ import javax.net.ssl.SSLParameters;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.httpclient.test.lib.http2.Http2TestServer;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Version;
import static java.net.http.HttpClient.Version.HTTP_1_1;
import static java.net.http.HttpClient.Version.HTTP_2;
import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpResponse.BodyHandlers.ofString;
import static org.testng.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import jdk.test.lib.security.SecurityUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/*
* @test
* @bug 8239594 8371887
@ -56,7 +59,7 @@ import jdk.test.lib.security.SecurityUtils;
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.test.lib.net.SimpleSSLContext TlsContextTest
* jdk.httpclient.test.lib.common.HttpServerAdapters
* @run testng/othervm -Dtest.requiresHost=true
* @run junit/othervm -Dtest.requiresHost=true
* -Djdk.httpclient.HttpClient.log=headers
* -Djdk.internal.httpclient.disableHostnameVerification
* -Djdk.internal.httpclient.debug=false
@ -67,11 +70,11 @@ public class TlsContextTest implements HttpServerAdapters {
static HttpTestServer https2Server;
static String https2URI;
SSLContext server;
static SSLContext server;
final static Integer ITERATIONS = 3;
@BeforeTest
public void setUp() throws Exception {
@BeforeAll
public static void setUp() throws Exception {
// Re-enable TLSv1 and TLSv1.1 since test depends on them
SecurityUtils.removeFromDisabledTlsAlgs("TLSv1", "TLSv1.1");
@ -86,8 +89,7 @@ public class TlsContextTest implements HttpServerAdapters {
https2URI = "https://" + https2Server.serverAuthority() + "/server/";
}
@DataProvider(name = "scenarios")
public Object[][] scenarios() throws Exception {
public static Object[][] scenarios() throws Exception {
return new Object[][]{
{ SimpleSSLContext.findSSLContext("TLS"), HTTP_2, "TLSv1.3" },
{ SimpleSSLContext.findSSLContext("TLSv1.2"), HTTP_2, "TLSv1.2" },
@ -102,7 +104,8 @@ public class TlsContextTest implements HttpServerAdapters {
/**
* Tests various scenarios between client and server tls handshake with valid http
*/
@Test(dataProvider = "scenarios")
@ParameterizedTest
@MethodSource("scenarios")
public void testVersionProtocolsNoParams(SSLContext context,
Version version,
String expectedProtocol) throws Exception {
@ -113,7 +116,8 @@ public class TlsContextTest implements HttpServerAdapters {
* Tests various scenarios between client and server tls handshake with valid http,
* but with empty SSLParameters
*/
@Test(dataProvider = "scenarios")
@ParameterizedTest
@MethodSource("scenarios")
public void testVersionProtocolsEmptyParams(SSLContext context,
Version version,
String expectedProtocol) throws Exception {
@ -150,24 +154,24 @@ public class TlsContextTest implements HttpServerAdapters {
private void testAllProtocols(HttpResponse<String> response,
String expectedProtocol,
Version clientVersion) throws Exception {
Version clientVersion) {
String protocol = response.sslSession().get().getProtocol();
int statusCode = response.statusCode();
Version version = response.version();
out.println("Got Body " + response.body());
out.println("The protocol negotiated is :" + protocol);
assertEquals(statusCode, 200);
assertEquals(protocol, expectedProtocol);
assertEquals(200, statusCode);
assertEquals(expectedProtocol, protocol);
if (clientVersion == HTTP_3) {
assertEquals(version, expectedProtocol.equals("TLSv1.1") ? HTTP_1_1 :
expectedProtocol.equals("TLSv1.2") ? HTTP_2 : HTTP_3);
assertEquals(expectedProtocol.equals("TLSv1.1") ? HTTP_1_1 :
expectedProtocol.equals("TLSv1.2") ? HTTP_2 : HTTP_3, version);
} else {
assertEquals(version, expectedProtocol.equals("TLSv1.1") ? HTTP_1_1 : HTTP_2);
assertEquals(expectedProtocol.equals("TLSv1.1") ? HTTP_1_1 : HTTP_2, version);
}
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
https2Server.stop();
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2018, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2018, 2026, 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
@ -32,16 +32,12 @@
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters
* jdk.test.lib.net.SimpleSSLContext ReferenceTracker
* @run testng/othervm
* @run junit/othervm
* -Djdk.httpclient.HttpClient.log=headers
* UnauthorizedTest
*/
import jdk.test.lib.net.SimpleSSLContext;
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;
@ -65,24 +61,29 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class UnauthorizedTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
HttpClient authClient;
HttpClient noAuthClient;
private static HttpTestServer httpTestServer; // HTTP/1.1
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
private static HttpClient authClient;
private static HttpClient noAuthClient;
static final int ITERATIONS = 3;
@ -100,8 +101,7 @@ public class UnauthorizedTest implements HttpServerAdapters {
return new WeakReference<>(client);
}
@DataProvider(name = "all")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ http3URI + "/server", UNAUTHORIZED, true, ref(authClient)},
{ http3URI + "/server", UNAUTHORIZED, false, ref(authClient)},
@ -144,8 +144,6 @@ public class UnauthorizedTest implements HttpServerAdapters {
};
}
static final AtomicLong requestCounter = new AtomicLong();
static final Authenticator authenticator = new Authenticator() {
};
@ -158,7 +156,8 @@ public class UnauthorizedTest implements HttpServerAdapters {
return builder;
}
@Test(dataProvider = "all")
@ParameterizedTest
@MethodSource("positive")
void test(String uriString, int code, boolean async, WeakReference<HttpClient> clientRef) throws Throwable {
HttpClient client = clientRef.get();
out.printf("%n---- starting (%s, %d, %s, %s) ----%n",
@ -195,9 +194,8 @@ public class UnauthorizedTest implements HttpServerAdapters {
}
out.println(" Got response: " + response);
assertEquals(response.statusCode(), code);
assertEquals(response.body(),
(code == UNAUTHORIZED ? "WWW-" : "Proxy-") + MESSAGE);
assertEquals(code, response.statusCode());
assertEquals( (code == UNAUTHORIZED ? "WWW-" : "Proxy-") + MESSAGE, response.body());
if (shouldThrow) {
throw new RuntimeException("Expected IOException not thrown.");
}
@ -205,8 +203,8 @@ public class UnauthorizedTest implements HttpServerAdapters {
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpTestServer.create(HTTP_1_1);
httpTestServer.addHandler(new UnauthorizedHandler(), "/http1/");
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1";
@ -225,13 +223,13 @@ public class UnauthorizedTest implements HttpServerAdapters {
http3TestServer.addHandler(new UnauthorizedHandler(), "/http3/");
http3URI = "https://" + http3TestServer.serverAuthority() + "/http3";
authClient = newClientBuilderForH3()
authClient = HttpServerAdapters.createClientBuilderForH3()
.proxy(HttpClient.Builder.NO_PROXY)
.sslContext(sslContext)
.authenticator(authenticator)
.build();
noAuthClient = newClientBuilderForH3()
noAuthClient = HttpServerAdapters.createClientBuilderForH3()
.proxy(HttpClient.Builder.NO_PROXY)
.sslContext(sslContext)
.build();
@ -243,8 +241,8 @@ public class UnauthorizedTest implements HttpServerAdapters {
http3TestServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
// authClient.close();
// noAuthClient.close();
var TRACKER = ReferenceTracker.INSTANCE;

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2021, 2026, 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
@ -28,7 +28,7 @@
* server-cookies for HTTP/2 vs HTTP/1.1
* @library /test/lib /test/jdk/java/net/httpclient/lib
* @build jdk.httpclient.test.lib.common.HttpServerAdapters jdk.test.lib.net.SimpleSSLContext
* @run testng/othervm
* @run junit/othervm
* -Djdk.tls.acknowledgeCloseNotify=true
* -Djdk.httpclient.HttpClient.log=trace,headers,requests
* UserCookieTest
@ -68,10 +68,6 @@ import javax.net.ssl.SSLContext;
import jdk.httpclient.test.lib.common.HttpServerAdapters;
import jdk.test.lib.net.SimpleSSLContext;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static java.lang.System.out;
import static java.net.http.HttpClient.Version.HTTP_1_1;
@ -80,25 +76,30 @@ import static java.net.http.HttpClient.Version.HTTP_3;
import static java.net.http.HttpOption.Http3DiscoveryMode.HTTP_3_URI_ONLY;
import static java.net.http.HttpOption.H3_DISCOVERY;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.testng.Assert.assertEquals;
import org.junit.jupiter.api.AfterAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
public class UserCookieTest implements HttpServerAdapters {
private static final SSLContext sslContext = SimpleSSLContext.findSSLContext();
HttpTestServer httpTestServer; // HTTP/1.1 [ 7 servers ]
HttpTestServer httpsTestServer; // HTTPS/1.1
HttpTestServer http2TestServer; // HTTP/2 ( h2c )
HttpTestServer https2TestServer; // HTTP/2 ( h2 )
HttpTestServer http3TestServer; // HTTP/3 ( h3 )
DummyServer httpDummyServer;
DummyServer httpsDummyServer;
String httpURI;
String httpsURI;
String http2URI;
String https2URI;
String http3URI;
String httpDummy;
String httpsDummy;
private static HttpTestServer httpTestServer; // HTTP/1.1 [ 7 servers ]
private static HttpTestServer httpsTestServer; // HTTPS/1.1
private static HttpTestServer http2TestServer; // HTTP/2 ( h2c )
private static HttpTestServer https2TestServer; // HTTP/2 ( h2 )
private static HttpTestServer http3TestServer; // HTTP/3 ( h3 )
private static DummyServer httpDummyServer;
private static DummyServer httpsDummyServer;
private static String httpURI;
private static String httpsURI;
private static String http2URI;
private static String https2URI;
private static String http3URI;
private static String httpDummy;
private static String httpsDummy;
static final String MESSAGE = "Basic CookieHeaderTest message body";
static final int ITERATIONS = 3;
@ -111,8 +112,7 @@ public class UserCookieTest implements HttpServerAdapters {
return String.format("[%d s, %d ms, %d ns] ", secs, mill, nan);
}
@DataProvider(name = "positive")
public Object[][] positive() {
public static Object[][] positive() {
return new Object[][] {
{ http3URI, HTTP_3 },
{ httpURI, HTTP_1_1 },
@ -130,7 +130,8 @@ public class UserCookieTest implements HttpServerAdapters {
static final AtomicLong requestCounter = new AtomicLong();
@Test(dataProvider = "positive")
@ParameterizedTest
@MethodSource("positive")
void test(String uriString, HttpClient.Version version) throws Exception {
out.printf("%n---- starting (%s) ----%n", uriString);
ConcurrentHashMap<String, List<String>> cookieHeaders
@ -178,12 +179,13 @@ public class UserCookieTest implements HttpServerAdapters {
out.println(" Got response: " + response);
out.println(" Got body Path: " + response.body());
assertEquals(response.statusCode(), 200);
assertEquals(response.body(), MESSAGE);
assertEquals(response.headers().allValues("X-Request-Cookie"),
expectedCookies.stream()
.filter(s -> !s.startsWith("LOC"))
.toList());
assertEquals(200, response.statusCode());
assertEquals(MESSAGE, response.body());
List<String> expectedCookieList = expectedCookies.stream()
.filter(s -> !s.startsWith("LOC")).toList();
List<String> actualCookieList = response.headers()
.allValues("X-Request-Cookie");
assertEquals(expectedCookieList, actualCookieList);
requestBuilder = HttpRequest.newBuilder(uri)
.header("X-uuid", "uuid-" + requestCounter.incrementAndGet())
.header("Cookie", userCookie);
@ -200,8 +202,8 @@ public class UserCookieTest implements HttpServerAdapters {
// -- Infrastructure
@BeforeTest
public void setup() throws Exception {
@BeforeAll
public static void setup() throws Exception {
httpTestServer = HttpTestServer.create(HTTP_1_1);
httpTestServer.addHandler(new CookieValidationHandler(), "/http1/cookie/");
httpURI = "http://" + httpTestServer.serverAuthority() + "/http1/cookie/retry";
@ -236,8 +238,8 @@ public class UserCookieTest implements HttpServerAdapters {
httpsDummyServer.start();
}
@AfterTest
public void teardown() throws Exception {
@AfterAll
public static void teardown() throws Exception {
httpTestServer.stop();
httpsTestServer.stop();
http2TestServer.stop();
@ -575,6 +577,5 @@ public class UserCookieTest implements HttpServerAdapters {
return new DummyServer(ss, true);
}
}
}