diff --git a/archetypes/helidon/src/main/archetype/common/extra.xml b/archetypes/helidon/src/main/archetype/common/extra.xml index 8101ae756f3..d0a2202b860 100644 --- a/archetypes/helidon/src/main/archetype/common/extra.xml +++ b/archetypes/helidon/src/main/archetype/common/extra.xml @@ -110,9 +110,6 @@ java -cp "target/classes:target/libs/*" {{package}}.WebClientMain PORT io.helidon.microprofile.faulttolerance - - io.helidon.http.Http - java.util.concurrent.TimeoutException @@ -325,9 +322,9 @@ restrictive-cors: io.helidon.cors.CrossOriginConfig - io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN - io.helidon.http.Http.HeaderNames.HOST - io.helidon.http.Http.HeaderNames.ORIGIN + io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN + io.helidon.http.HeaderNames.HOST + io.helidon.http.HeaderNames.ORIGIN org.hamcrest.CoreMatchers.containsString diff --git a/archetypes/helidon/src/main/archetype/common/media.xml b/archetypes/helidon/src/main/archetype/common/media.xml index a7d69cda2e2..3a2590618e7 100644 --- a/archetypes/helidon/src/main/archetype/common/media.xml +++ b/archetypes/helidon/src/main/archetype/common/media.xml @@ -53,7 +53,7 @@ try (Http1ClientResponse response = client.get("/greet") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("message"), is("Hello World!")); } @@ -113,7 +113,7 @@ @Test void testGreet() { try (Http1ClientResponse response = client.get("/greet").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(Message.class).getMessage(), is("Hello World!")); } } @@ -121,7 +121,7 @@ @Test void testGreetJoe() { try (Http1ClientResponse response = client.get("/greet/Joe").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(Message.class).getMessage(), is("Hello Joe!")); } } @@ -171,14 +171,16 @@ jersey.media.multipart - io.helidon.http.Http - io.helidon.http.Http.Header + io.helidon.http.Header + io.helidon.http.Status + io.helidon.http.HeaderNames + io.helidon.http.HeaderValues io.helidon.webserver.staticcontent.StaticContentService { - res.status(Http.Status.MOVED_PERMANENTLY_301); - res.header(Http.Headers.createCached(Http.HeaderNames.LOCATION, "/ui")); + res.status(Status.MOVED_PERMANENTLY_301); + res.header(HeaderValues.createCached(HeaderNames.LOCATION, "/ui")); res.send(); }) .register("/ui", StaticContentService.builder("WEB") @@ -191,7 +193,7 @@ @Test void testFileService() { try (Http1ClientResponse response = client.get("/api").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } } ]]> diff --git a/archetypes/helidon/src/main/archetype/common/observability.xml b/archetypes/helidon/src/main/archetype/common/observability.xml index 6a596a02edb..0deb6d8d808 100644 --- a/archetypes/helidon/src/main/archetype/common/observability.xml +++ b/archetypes/helidon/src/main/archetype/common/observability.xml @@ -547,7 +547,7 @@ curl -s -X GET http://localhost:8080/health @Test void testHealth() { try (Http1ClientResponse response = client.get("/observe/health").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), containsString("status\":\"UP")); } } diff --git a/archetypes/helidon/src/main/archetype/mp/custom/files/src/test/java/__pkg__/TestCORS.java.mustache b/archetypes/helidon/src/main/archetype/mp/custom/files/src/test/java/__pkg__/TestCORS.java.mustache index 9da6a3dc3e4..174ac313536 100644 --- a/archetypes/helidon/src/main/archetype/mp/custom/files/src/test/java/__pkg__/TestCORS.java.mustache +++ b/archetypes/helidon/src/main/archetype/mp/custom/files/src/test/java/__pkg__/TestCORS.java.mustache @@ -1,6 +1,6 @@ package {{package}}; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.config.Config; import io.helidon.cors.CrossOriginConfig; import io.helidon.microprofile.tests.junit5.HelidonTest; @@ -29,15 +29,15 @@ class TestCORS { void testAnonymousGreetWithCors() { Response r = target.path("/simple-greet") .request() - .header(Http.HeaderNames.ORIGIN.defaultCase(), "http://foo.com") - .header(Http.HeaderNames.HOST.defaultCase(), "here.com") + .header(HeaderNames.ORIGIN.defaultCase(), "http://foo.com") + .header(HeaderNames.HOST.defaultCase(), "here.com") .get(); assertThat("HTTP response", r.getStatus(), is(200)); String payload = fromPayload(r); assertThat("HTTP response payload", payload.contains("Hello World!"), is(true)); assertThat("CORS header " + CrossOriginConfig.ACCESS_CONTROL_ALLOW_ORIGIN, - r.getHeaders().getFirst(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()), + r.getHeaders().getFirst(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()), is("http://foo.com")); } @@ -45,30 +45,30 @@ class TestCORS { void testCustomGreetingWithCors() { Response r = target.path("/simple-greet") .request() - .header(Http.HeaderNames.ORIGIN.defaultCase(), "http://foo.com") - .header(Http.HeaderNames.HOST.defaultCase(), "here.com") + .header(HeaderNames.ORIGIN.defaultCase(), "http://foo.com") + .header(HeaderNames.HOST.defaultCase(), "here.com") .header("Access-Control-Request-Method", "PUT") .options(); assertThat("pre-flight status", r.getStatus(), is(200)); MultivaluedMap responseHeaders = r.getHeaders(); assertThat("Header " + CrossOriginConfig.ACCESS_CONTROL_ALLOW_METHODS, - r.getHeaders().getFirst(Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS.defaultCase()), + r.getHeaders().getFirst(HeaderNames.ACCESS_CONTROL_ALLOW_METHODS.defaultCase()), is("PUT")); assertThat( "Header " + CrossOriginConfig.ACCESS_CONTROL_ALLOW_ORIGIN, - r.getHeaders().getFirst(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()), + r.getHeaders().getFirst(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()), is("http://foo.com")); Invocation.Builder builder = target.path("/simple-greet") .request() .headers(responseHeaders) - .header(Http.HeaderNames.ORIGIN.defaultCase(), "http://foo.com") - .header(Http.HeaderNames.HOST.defaultCase(), "here.com"); + .header(HeaderNames.ORIGIN.defaultCase(), "http://foo.com") + .header(HeaderNames.HOST.defaultCase(), "here.com"); r = putResponse("Cheers", builder); assertThat("HTTP response3", r.getStatus(), is(200)); assertThat( "Header " + CrossOriginConfig.ACCESS_CONTROL_ALLOW_ORIGIN, - r.getHeaders().getFirst(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()), + r.getHeaders().getFirst(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()), is("http://foo.com")); assertThat(fromPayload(r), containsString("Cheers World!")); } @@ -77,8 +77,8 @@ class TestCORS { void testGreetingChangeWithCorsAndOtherOrigin() { Invocation.Builder builder = target.path("/simple-greet") .request() - .header(Http.HeaderNames.ORIGIN.defaultCase(), "http://other.com") - .header(Http.HeaderNames.HOST.defaultCase(), "here.com"); + .header(HeaderNames.ORIGIN.defaultCase(), "http://other.com") + .header(HeaderNames.HOST.defaultCase(), "here.com"); Response r = putResponse("Ahoy", builder); boolean isOverriding = Config.create().get("cors").exists(); diff --git a/archetypes/helidon/src/main/archetype/se/common/common-se.xml b/archetypes/helidon/src/main/archetype/se/common/common-se.xml index e152d14b706..f6a7d240b66 100644 --- a/archetypes/helidon/src/main/archetype/se/common/common-se.xml +++ b/archetypes/helidon/src/main/archetype/se/common/common-se.xml @@ -57,7 +57,7 @@ io.helidon.webserver.http.HttpRouting - io.helidon.http.Http + io.helidon.http.Status io.helidon.config.Config io.helidon.webserver.testing.junit5.SetUpRoute io.helidon.webclient.http1.Http1Client diff --git a/archetypes/helidon/src/main/archetype/se/custom/custom-se.xml b/archetypes/helidon/src/main/archetype/se/custom/custom-se.xml index ee2638b57be..e419d2a8dda 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/custom-se.xml +++ b/archetypes/helidon/src/main/archetype/se/custom/custom-se.xml @@ -46,7 +46,7 @@ @Test void testSimpleGreet() { try (Http1ClientResponse response = client.get("/simple-greet").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is("Hello World!")); } } diff --git a/archetypes/helidon/src/main/archetype/se/custom/extra.xml b/archetypes/helidon/src/main/archetype/se/custom/extra.xml index 0af20037c2f..06f544725e9 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/extra.xml +++ b/archetypes/helidon/src/main/archetype/se/custom/extra.xml @@ -29,7 +29,7 @@ - io.helidon.http.Http + io.helidon.http.Status io.helidon.faulttolerance.BulkheadException io.helidon.faulttolerance.CircuitBreakerOpenException io.helidon.faulttolerance.TimeoutException @@ -37,13 +37,13 @@ res.status(Http.Status.SERVICE_UNAVAILABLE_503).send("bulkhead")) + (req, res, ex) -> res.status(Status.SERVICE_UNAVAILABLE_503).send("bulkhead")) .error(CircuitBreakerOpenException.class, - (req, res, ex) -> res.status(Http.Status.SERVICE_UNAVAILABLE_503).send("circuit breaker")) + (req, res, ex) -> res.status(Status.SERVICE_UNAVAILABLE_503).send("circuit breaker")) .error(TimeoutException.class, - (req, res, ex) -> res.status(Http.Status.REQUEST_TIMEOUT_408).send("timeout")) + (req, res, ex) -> res.status(Status.REQUEST_TIMEOUT_408).send("timeout")) .error(Throwable.class, - (req, res, ex) -> res.status(Http.Status.INTERNAL_SERVER_ERROR_500) + (req, res, ex) -> res.status(Status.INTERNAL_SERVER_ERROR_500) .send(ex.getClass().getName() + ": " + ex.getMessage()))]]> @@ -75,7 +75,7 @@ try (Http1ClientResponse third = client.get().path("/bulkhead/10000").request()) { // registered an error handler in Main - assertThat(third.status(), is(Http.Status.OK_200)); + assertThat(third.status(), is(Status.OK_200)); assertThat(third.as(String.class), is("Call rejected: 1")); } } @@ -114,7 +114,7 @@ .request(); // registered an error handler in Main - assertThat(clientResponse.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); + assertThat(clientResponse.status(), is(Status.SERVICE_UNAVAILABLE_503)); assertThat(clientResponse.as(String.class), is("circuit breaker")); } @@ -163,7 +163,7 @@ .request()) { // no error handler specified - assertThat(clientResponse.status(), is(Http.Status.INTERNAL_SERVER_ERROR_500)); + assertThat(clientResponse.status(), is(Status.INTERNAL_SERVER_ERROR_500)); assertThat(clientResponse.as(String.class), is("java.lang.RuntimeException: reactive failure")); } } @@ -181,7 +181,7 @@ .path("/timeout/1000") .request()) { // error handler specified in Main - assertThat(clientResponse.status(), is(Http.Status.REQUEST_TIMEOUT_408)); + assertThat(clientResponse.status(), is(Status.REQUEST_TIMEOUT_408)); assertThat(clientResponse.as(String.class), is("timeout")); } } diff --git a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/FileService.java.multipart.mustache b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/FileService.java.multipart.mustache index 49050da77c4..6a14b963915 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/FileService.java.multipart.mustache +++ b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/FileService.java.multipart.mustache @@ -10,8 +10,9 @@ import java.util.Map; import java.util.stream.Stream; import io.helidon.http.ContentDisposition; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; +import io.helidon.http.Header; +import io.helidon.http.HeaderValues; +import io.helidon.http.HeaderNames; import io.helidon.http.ServerResponseHeaders; import io.helidon.common.media.type.MediaTypes; import io.helidon.http.media.multipart.MultiPart; @@ -25,15 +26,15 @@ import jakarta.json.Json; import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonBuilderFactory; -import static io.helidon.http.Http.Status.BAD_REQUEST_400; -import static io.helidon.http.Http.Status.MOVED_PERMANENTLY_301; -import static io.helidon.http.Http.Status.NOT_FOUND_404; +import static io.helidon.http.Status.BAD_REQUEST_400; +import static io.helidon.http.Status.MOVED_PERMANENTLY_301; +import static io.helidon.http.Status.NOT_FOUND_404; /** * File service. */ final class FileService implements HttpService { - private static final Http.Header UI_LOCATION = Http.Headers.createCached(Http.HeaderNames.LOCATION, "/ui"); + private static final Header UI_LOCATION = HeaderValues.createCached(HeaderNames.LOCATION, "/ui"); private final JsonBuilderFactory jsonFactory; private final Path storage; diff --git a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.json.mustache b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.json.mustache index 5e8c3aefaf2..b1573912611 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.json.mustache +++ b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.json.mustache @@ -5,7 +5,7 @@ import java.util.concurrent.atomic.AtomicReference; {{#GreetService-imports}} {{.}} {{/GreetService-imports}} -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -80,13 +80,13 @@ public class GreetService implements HttpService { if (message.getGreeting() == null) { Message errorMessage = new Message(); errorMessage.setMessage("No greeting provided"); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(errorMessage); return; } greeting.set(message.getGreeting()); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.jsonp.mustache b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.jsonp.mustache index 2421f8624bc..3d206063f12 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.jsonp.mustache +++ b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.jsonp.mustache @@ -6,7 +6,7 @@ import java.util.concurrent.atomic.AtomicReference; {{#GreetService-imports}} {{.}} {{/GreetService-imports}} -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -105,13 +105,13 @@ class GreetService implements HttpService { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.mustache b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.mustache index 5cde2942d07..177319d738e 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.mustache +++ b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/GreetService.java.mustache @@ -6,7 +6,7 @@ import java.util.concurrent.atomic.AtomicReference; {{#GreetService-imports}} {{.}} {{/GreetService-imports}} -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -91,7 +91,7 @@ class GreetService implements HttpService { private void updateGreeting(String update, ServerResponse response) { greeting.set(update); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/MetricsService.java.mustache b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/MetricsService.java.mustache index f13384c0d0a..5891552e2c4 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/MetricsService.java.mustache +++ b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/MetricsService.java.mustache @@ -6,7 +6,6 @@ import java.util.concurrent.atomic.AtomicReference; {{#MetricsService-imports}} import {{.}}; {{/MetricsService-imports}} -import io.helidon.http.Http; import io.helidon.config.Config; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; diff --git a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/OutboundOverrideJwt.java.mustache b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/OutboundOverrideJwt.java.mustache index bf0a18cba36..1dc258ca079 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/OutboundOverrideJwt.java.mustache +++ b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/OutboundOverrideJwt.java.mustache @@ -2,7 +2,7 @@ package {{package}}; import java.util.concurrent.TimeUnit; -import io.helidon.http.Http; +import io.helidon.http.Header; import io.helidon.config.Config; import io.helidon.config.ConfigSources; import io.helidon.webserver.WebServer; @@ -84,7 +84,7 @@ public final class OutboundOverrideJwt { .get("/hello", (req, res) -> { // This is the token. It should be bearer - req.headers().first(Http.Header.AUTHORIZATION) + req.headers().first(Header.AUTHORIZATION) .ifPresent(System.out::println); String username = req.context() diff --git a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/Service1.java.mustache b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/Service1.java.mustache index 71b1b6dfd69..18790097167 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/Service1.java.mustache +++ b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/Service1.java.mustache @@ -2,8 +2,8 @@ package {{package}}; import io.helidon.common.LazyValue; import io.helidon.common.context.Contexts; -import io.helidon.http.Http; import io.helidon.http.HttpMediaTypes; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServer; @@ -42,7 +42,7 @@ class Service1 implements HttpService { .get(SecurityContext.class) .ifPresentOrElse(context -> { try (Http1ClientResponse clientRes = client.get().get(path).request()) { - if (clientRes.status() == Http.Status.OK_200) { + if (clientRes.status() == Status.OK_200) { res.send(clientRes.entity().as(String.class)); } else { res.send("Request failed, status: " + clientRes.status()); diff --git a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/WebClientMain.java.mustache b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/WebClientMain.java.mustache index b1fd109c96c..85be767ca7b 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/WebClientMain.java.mustache +++ b/archetypes/helidon/src/main/archetype/se/custom/files/src/main/java/__pkg__/WebClientMain.java.mustache @@ -7,7 +7,6 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; -import io.helidon.http.Http; import io.helidon.config.Config; import io.helidon.config.ConfigValue; import io.helidon.webclient.http1.Http1Client; @@ -56,7 +55,7 @@ public class WebClientMain { static String performGetMethod(Http1Client client) { System.out.println("Get request execution."); - String result = client.get().path("/simple-greet").request().as(String.class); + String result = client.get().path("/simple-greet").requestEntity(String.class); System.out.println("GET request successfully executed."); System.out.println(result); return result; diff --git a/archetypes/helidon/src/main/archetype/se/custom/files/src/test/java/__pkg__/GoogleMainTest.java.mustache b/archetypes/helidon/src/main/archetype/se/custom/files/src/test/java/__pkg__/GoogleMainTest.java.mustache index 607beadc1d7..38071538e0f 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/files/src/test/java/__pkg__/GoogleMainTest.java.mustache +++ b/archetypes/helidon/src/main/archetype/se/custom/files/src/test/java/__pkg__/GoogleMainTest.java.mustache @@ -1,7 +1,8 @@ package {{package}}; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webserver.testing.junit5.ServerTest; import io.helidon.webserver.testing.junit5.SetUpServer; import io.helidon.webclient.http1.Http1Client; @@ -35,8 +36,8 @@ public class GoogleMainTest { public void testEndpoint() { try (Http1ClientResponse response = client.get("/rest/profile").request()) { - assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); - assertThat(response.headers().first(Http.HeaderNames.WWW_AUTHENTICATE), + assertThat(response.status(), is(Status.UNAUTHORIZED_401)); + assertThat(response.headers().first(HeaderNames.WWW_AUTHENTICATE), optionalValue(is("Bearer realm=\"helidon\",scope=\"openid profile email\""))); } } diff --git a/archetypes/helidon/src/main/archetype/se/custom/observability.xml b/archetypes/helidon/src/main/archetype/se/custom/observability.xml index 987c72d9fe7..b3929f18a27 100644 --- a/archetypes/helidon/src/main/archetype/se/custom/observability.xml +++ b/archetypes/helidon/src/main/archetype/se/custom/observability.xml @@ -76,7 +76,7 @@ io.helidon.tracing.TracerBuilder - static io.helidon.http.Http.Method.GET + static io.helidon.http.Method.GET diff --git a/archetypes/helidon/src/main/archetype/se/quickstart/files/src/main/java/__pkg__/GreetClientHttp.java.mustache b/archetypes/helidon/src/main/archetype/se/quickstart/files/src/main/java/__pkg__/GreetClientHttp.java.mustache index 878f77ab1c1..e0a5a0e79ab 100644 --- a/archetypes/helidon/src/main/archetype/se/quickstart/files/src/main/java/__pkg__/GreetClientHttp.java.mustache +++ b/archetypes/helidon/src/main/archetype/se/quickstart/files/src/main/java/__pkg__/GreetClientHttp.java.mustache @@ -1,6 +1,6 @@ package {{package}}; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webclient.api.WebClient; /** @@ -20,7 +20,7 @@ public class GreetClientHttp { .baseUri("http://localhost:8080/greet") .build(); - String response = client.method(Http.Method.GET) + String response = client.method(Method.GET) .requestEntity(String.class); System.out.println(response); diff --git a/common/testing/http-junit5/src/main/java/io/helidon/common/testing/http/junit5/HttpHeaderMatcher.java b/common/testing/http-junit5/src/main/java/io/helidon/common/testing/http/junit5/HttpHeaderMatcher.java index 9bd6d7b1f97..49eb2b41651 100644 --- a/common/testing/http-junit5/src/main/java/io/helidon/common/testing/http/junit5/HttpHeaderMatcher.java +++ b/common/testing/http-junit5/src/main/java/io/helidon/common/testing/http/junit5/HttpHeaderMatcher.java @@ -18,9 +18,10 @@ import java.util.List; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; import org.hamcrest.Description; import org.hamcrest.Matcher; @@ -77,7 +78,7 @@ public static Matcher hasHeader(HeaderName name) { * @param header http header with values * @return matcher validating the {@link io.helidon.http.Headers} does contain the provided header */ - public static Matcher hasHeader(Http.Header header) { + public static Matcher hasHeader(Header header) { return new HasValueMatcher(header); } @@ -94,8 +95,8 @@ public static Matcher hasHeader(Http.Header header) { * @param value value(s) of the header * @return matcher validating the {@link io.helidon.http.Headers} does contain the provided header */ - public static Matcher hasHeader(Http.HeaderName name, String... value) { - return new HasValueMatcher(Http.Headers.create(name, value)); + public static Matcher hasHeader(HeaderName name, String... value) { + return new HasValueMatcher(HeaderValues.create(name, value)); } /** @@ -160,7 +161,7 @@ private static class HasValueMatcher extends TypeSafeMatcher { private final HeaderName name; private final Matcher> valuesMatcher; - HasValueMatcher(Http.Header header) { + HasValueMatcher(Header header) { this.name = header.headerName(); this.valuesMatcher = Matchers.containsInAnyOrder(header.allValues().toArray(new String[0])); } @@ -214,7 +215,7 @@ public void describeTo(Description description) { @Override protected boolean matchesSafely(Headers httpHeaders) { if (httpHeaders.contains(name)) { - Http.Header headerValue = httpHeaders.get(name); + Header headerValue = httpHeaders.get(name); if (headerValue.allValues().size() == 1) { return valuesMatcher.matches(headerValue.value()); } diff --git a/common/testing/http-junit5/src/main/java/io/helidon/common/testing/http/junit5/SocketHttpClient.java b/common/testing/http-junit5/src/main/java/io/helidon/common/testing/http/junit5/SocketHttpClient.java index c004bf956c0..743bdf146c6 100644 --- a/common/testing/http-junit5/src/main/java/io/helidon/common/testing/http/junit5/SocketHttpClient.java +++ b/common/testing/http-junit5/src/main/java/io/helidon/common/testing/http/junit5/SocketHttpClient.java @@ -34,7 +34,9 @@ import java.util.regex.Pattern; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.http.WritableHeaders; import static org.hamcrest.CoreMatchers.containsString; @@ -136,7 +138,7 @@ public static ClientResponseHeaders headersFromResponse(String response) { if (i < 0) { throw new AssertionError("Header without semicolon - " + line); } - headers.add(Http.HeaderNames.create(line.substring(0, i).trim()), line.substring(i + 1).trim()); + headers.add(HeaderNames.create(line.substring(0, i).trim()), line.substring(i + 1).trim()); } return ClientResponseHeaders.create(headers); } @@ -147,7 +149,7 @@ public static ClientResponseHeaders headersFromResponse(String response) { * @param response full HTTP response * @return status */ - public static Http.Status statusFromResponse(String response) { + public static Status statusFromResponse(String response) { // response should start with HTTP/1.1 000 reasonPhrase\n int eol = response.indexOf('\n'); assertThat("There must be at least a line end after first line: " + response, eol > -1); @@ -160,7 +162,7 @@ public static Http.Status statusFromResponse(String response) { int statusCode = Integer.parseInt(matcher.group(1)); String phrase = matcher.group(2); - return Http.Status.create(statusCode, phrase); + return Status.create(statusCode, phrase); } /** @@ -198,7 +200,7 @@ public void close() throws Exception { */ public void assertConnectionIsOpen() { // get - request(Http.Method.GET, "/this/path/should/not/exist", null); + request(Method.GET, "/this/path/should/not/exist", null); // assert assertThat(receive(), containsString("HTTP/1.1")); } @@ -208,7 +210,7 @@ public void assertConnectionIsOpen() { */ public void assertConnectionIsClosed() { // get - request(Http.Method.POST, null); + request(Method.POST, null); // assert try { // when the connection is closed before we start reading, just "" is returned by receive() @@ -232,7 +234,7 @@ public void assertConnectionIsClosed() { * otherwise it's not a valid payload) * @return the exact string returned by webserver (including {@code HTTP/1.1 200 OK} line for instance) */ - public String sendAndReceive(Http.Method method, String payload) { + public String sendAndReceive(Method method, String payload) { return sendAndReceive(method, "/", payload); } @@ -245,7 +247,7 @@ public String sendAndReceive(Http.Method method, String payload) { * otherwise it's not a valid payload) * @return the exact string returned by webserver (including {@code HTTP/1.1 200 OK} line for instance) */ - public String sendAndReceive(Http.Method method, String path, String payload) { + public String sendAndReceive(Method method, String path, String payload) { return sendAndReceive(method, path, payload, Collections.emptyList()); } @@ -259,7 +261,7 @@ public String sendAndReceive(Http.Method method, String path, String payload) { * @param headers HTTP request headers * @return the exact string returned by webserver (including {@code HTTP/1.1 200 OK} line for instance) */ - public String sendAndReceive(Http.Method method, + public String sendAndReceive(Method method, String path, String payload, Iterable headers) { @@ -367,7 +369,7 @@ public SocketHttpClient awaitResponse(String expectedStartsWith, String expected * * @param method the http method */ - public void request(Http.Method method) { + public void request(Method method) { request(method, null); } @@ -378,7 +380,7 @@ public void request(Http.Method method) { * @param payload the payload to send (must be without the newlines; * otherwise it's not a valid payload) */ - public void request(Http.Method method, String payload) { + public void request(Method method, String payload) { request(method, "/", payload); } @@ -390,7 +392,7 @@ public void request(Http.Method method, String payload) { * @param payload the payload to send (must be without the newlines; * otherwise it's not a valid payload) */ - public void request(Http.Method method, String path, String payload) { + public void request(Method method, String path, String payload) { request(method, path, payload, List.of("Content-Type: application/x-www-form-urlencoded")); } @@ -403,7 +405,7 @@ public void request(Http.Method method, String path, String payload) { * otherwise it's not a valid payload) * @param headers the headers (e.g., {@code Content-Type: application/json}) */ - public void request(Http.Method method, String path, String payload, Iterable headers) { + public void request(Method method, String path, String payload, Iterable headers) { request(method.text(), path, "HTTP/1.1", "127.0.0.1", headers, payload); } diff --git a/cors/src/main/java/io/helidon/cors/CorsRequestAdapter.java b/cors/src/main/java/io/helidon/cors/CorsRequestAdapter.java index fa51bfc01f2..4abcb368f34 100644 --- a/cors/src/main/java/io/helidon/cors/CorsRequestAdapter.java +++ b/cors/src/main/java/io/helidon/cors/CorsRequestAdapter.java @@ -19,7 +19,7 @@ import java.util.List; import java.util.Optional; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; /** * Not for use by developers. @@ -48,7 +48,7 @@ public interface CorsRequestAdapter { * @param key header name to retrieve * @return the first header value for the key */ - Optional firstHeader(Http.HeaderName key); + Optional firstHeader(HeaderName key); /** * Reports whether the specified header exists. @@ -56,7 +56,7 @@ public interface CorsRequestAdapter { * @param key header name to check for * @return whether the header exists among the request's headers */ - boolean headerContainsKey(Http.HeaderName key); + boolean headerContainsKey(HeaderName key); /** * Retrieves all header values for a given key as Strings. @@ -64,7 +64,7 @@ public interface CorsRequestAdapter { * @param key header name to retrieve * @return header values for the header; empty list if none */ - List allHeaders(Http.HeaderName key); + List allHeaders(HeaderName key); /** * Reports the method name for the request. diff --git a/cors/src/main/java/io/helidon/cors/CorsResponseAdapter.java b/cors/src/main/java/io/helidon/cors/CorsResponseAdapter.java index 16f3de0b8fc..8de4d1d2672 100644 --- a/cors/src/main/java/io/helidon/cors/CorsResponseAdapter.java +++ b/cors/src/main/java/io/helidon/cors/CorsResponseAdapter.java @@ -16,7 +16,7 @@ package io.helidon.cors; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; /** * Not for use by developers. @@ -40,7 +40,7 @@ public interface CorsResponseAdapter { * @param value header value to add * @return the adapter */ - CorsResponseAdapter header(Http.HeaderName key, String value); + CorsResponseAdapter header(HeaderName key, String value); /** * Arranges to add the specified header and value to the eventual response. @@ -49,7 +49,7 @@ public interface CorsResponseAdapter { * @param value header value to add * @return the adapter */ - CorsResponseAdapter header(Http.HeaderName key, Object value); + CorsResponseAdapter header(HeaderName key, Object value); /** * Returns a response with the forbidden status and the specified error message, without any headers assigned diff --git a/cors/src/main/java/io/helidon/cors/CorsSupportHelper.java b/cors/src/main/java/io/helidon/cors/CorsSupportHelper.java index 6031583dcd2..95a57027564 100644 --- a/cors/src/main/java/io/helidon/cors/CorsSupportHelper.java +++ b/cors/src/main/java/io/helidon/cors/CorsSupportHelper.java @@ -30,8 +30,10 @@ import io.helidon.common.config.Config; import io.helidon.cors.LogHelper.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import static io.helidon.cors.LogHelper.DECISION_LEVEL; import static java.lang.Character.isDigit; @@ -324,9 +326,9 @@ public void prepareResponse(CorsRequestAdapter requestAdapter, CorsResponseAd if (requestType == RequestType.CORS) { // Aggregator knows only about expect paths. If response is 404, use an ad hoc cross-origin config for the given // origin and method, thus allowing the 404 to pass through the CORS handling in the client. - CrossOriginConfig crossOrigin = responseAdapter.status() == Http.Status.NOT_FOUND_404.code() + CrossOriginConfig crossOrigin = responseAdapter.status() == Status.NOT_FOUND_404.code() ? CrossOriginConfig.builder() - .allowOrigins(requestAdapter.firstHeader(Http.HeaderNames.ORIGIN).orElse("*")) + .allowOrigins(requestAdapter.firstHeader(HeaderNames.ORIGIN).orElse("*")) .allowMethods(requestAdapter.method()) .build() : aggregator.lookupCrossOrigin( @@ -380,9 +382,9 @@ private boolean isRequestTypeNormal(CorsRequestAdapter requestAdapter, boolea private RequestType inferCORSRequestType(CorsRequestAdapter requestAdapter, boolean silent) { String methodName = requestAdapter.method(); - boolean isMethodOPTION = methodName.equalsIgnoreCase(Http.Method.OPTIONS.text()); + boolean isMethodOPTION = methodName.equalsIgnoreCase(Method.OPTIONS.text()); boolean requestContainsAccessControlRequestMethodHeader = - requestAdapter.headerContainsKey(Http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD); + requestAdapter.headerContainsKey(HeaderNames.ACCESS_CONTROL_REQUEST_METHOD); RequestType result = isMethodOPTION && requestContainsAccessControlRequestMethodHeader ? RequestType.PREFLIGHT @@ -417,7 +419,7 @@ Optional processCorsRequest( // If enabled but not whitelisted, deny request List allowedOrigins = Arrays.asList(crossOriginConfig.allowOrigins()); - Optional originOpt = requestAdapter.firstHeader(Http.HeaderNames.ORIGIN); + Optional originOpt = requestAdapter.firstHeader(HeaderNames.ORIGIN); if (!allowedOrigins.contains("*") && !contains(originOpt, allowedOrigins, CorsSupportHelper::compareOrigins)) { return Optional.of(forbid(requestAdapter, responseAdapter, @@ -443,27 +445,27 @@ void addCorsHeadersToResponse(CrossOriginConfig crossOrigin, // // Throw an exception if there is no ORIGIN because we should not even be here unless this is a CORS request, which would // have required the ORIGIN heading to be present when we determined the request type. - String origin = requestAdapter.firstHeader(Http.HeaderNames.ORIGIN) - .orElseThrow(noRequiredHeaderExcFactory(Http.HeaderNames.ORIGIN)); + String origin = requestAdapter.firstHeader(HeaderNames.ORIGIN) + .orElseThrow(noRequiredHeaderExcFactory(HeaderNames.ORIGIN)); if (crossOrigin.allowCredentials()) { new Headers() - .add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true") - .add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin) - .add(Http.HeaderNames.VARY, Http.HeaderNames.ORIGIN) + .add(HeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true") + .add(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin) + .add(HeaderNames.VARY, HeaderNames.ORIGIN) .setAndLog(responseAdapter::header, "allow-credentials was set in CORS config"); } else { List allowedOrigins = Arrays.asList(crossOrigin.allowOrigins()); new Headers() - .add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigins.contains("*") ? "*" : origin) - .add(Http.HeaderNames.VARY, Http.HeaderNames.ORIGIN) + .add(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigins.contains("*") ? "*" : origin) + .add(HeaderNames.VARY, HeaderNames.ORIGIN) .setAndLog(responseAdapter::header, "allow-credentials was not set in CORS config"); } // Add Access-Control-Expose-Headers if non-empty Headers headers = new Headers(); formatHeader(crossOrigin.exposeHeaders()).ifPresent( - h -> headers.add(Http.HeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, h)); + h -> headers.add(HeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, h)); headers.setAndLog(responseAdapter::header, "expose-headers was set in CORS config"); } @@ -482,11 +484,11 @@ R processCorsPreFlightRequest(CorsRequestAdapter requestAdapter, CorsResponse Optional originOpt = requestAdapter.firstHeader(HeaderNames.ORIGIN); if (originOpt.isEmpty()) { - return forbid(requestAdapter, responseAdapter, noRequiredHeader(Http.HeaderNames.ORIGIN)); + return forbid(requestAdapter, responseAdapter, noRequiredHeader(HeaderNames.ORIGIN)); } // Access-Control-Request-Method had to be present in order for this to be assessed as a preflight request. - String requestedMethod = requestAdapter.firstHeader(Http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD).get(); + String requestedMethod = requestAdapter.firstHeader(HeaderNames.ACCESS_CONTROL_REQUEST_METHOD).get(); // Lookup the CrossOriginConfig using the requested method, not the current method (which we know is OPTIONS). Optional crossOriginOpt = aggregator.lookupCrossOrigin( @@ -520,7 +522,7 @@ R processCorsPreFlightRequest(CorsRequestAdapter requestAdapter, CorsResponse allowedMethods)); } // Check if headers are allowed - Set requestHeaders = parseHeader(requestAdapter.allHeaders(Http.HeaderNames.ACCESS_CONTROL_REQUEST_HEADERS)); + Set requestHeaders = parseHeader(requestAdapter.allHeaders(HeaderNames.ACCESS_CONTROL_REQUEST_HEADERS)); List allowedHeaders = Arrays.asList(crossOrigin.allowHeaders()); if (!allowedHeaders.contains("*") && !contains(requestHeaders, allowedHeaders)) { return forbid(requestAdapter, @@ -535,14 +537,14 @@ R processCorsPreFlightRequest(CorsRequestAdapter requestAdapter, CorsResponse Headers headers = new Headers() .add(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, originOpt.get()); if (crossOrigin.allowCredentials()) { - headers.add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true", "allowCredentials config was set"); + headers.add(HeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true", "allowCredentials config was set"); } - headers.add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS, requestedMethod); + headers.add(HeaderNames.ACCESS_CONTROL_ALLOW_METHODS, requestedMethod); formatHeader(requestHeaders.toArray()).ifPresent( - h -> headers.add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, h)); + h -> headers.add(HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, h)); long maxAgeSeconds = crossOrigin.maxAgeSeconds(); if (maxAgeSeconds > 0) { - headers.add(Http.HeaderNames.ACCESS_CONTROL_MAX_AGE, maxAgeSeconds, "maxAgeSeconds > 0"); + headers.add(HeaderNames.ACCESS_CONTROL_MAX_AGE, maxAgeSeconds, "maxAgeSeconds > 0"); } headers.setAndLog(responseAdapter::header, "headers set on preflight request"); return responseAdapter.ok(); @@ -745,11 +747,11 @@ static boolean contains(Collection left, Collection right) { return true; } - private static Supplier noRequiredHeaderExcFactory(Http.HeaderName header) { + private static Supplier noRequiredHeaderExcFactory(HeaderName header) { return () -> new IllegalArgumentException(noRequiredHeader(header)); } - private static String noRequiredHeader(Http.HeaderName header) { + private static String noRequiredHeader(HeaderName header) { return "CORS request does not have required header " + header.defaultCase(); } diff --git a/cors/src/main/java/io/helidon/cors/LogHelper.java b/cors/src/main/java/io/helidon/cors/LogHelper.java index cd34a7627a7..e65e37c7ac5 100644 --- a/cors/src/main/java/io/helidon/cors/LogHelper.java +++ b/cors/src/main/java/io/helidon/cors/LogHelper.java @@ -30,8 +30,9 @@ import java.util.stream.Collectors; import io.helidon.cors.CorsSupportHelper.RequestType; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; class LogHelper { @@ -45,15 +46,15 @@ private LogHelper() { * Collects headers for assignment to a request or response and logging during assignment. */ static class Headers { - private final List> headers = new ArrayList<>(); + private final List> headers = new ArrayList<>(); private final List notes = CorsSupportHelper.LOGGER.isLoggable(DECISION_LEVEL) ? new ArrayList<>() : null; - Headers add(Http.HeaderName key, Object value) { + Headers add(HeaderName key, Object value) { headers.add(new AbstractMap.SimpleEntry<>(key, value)); return this; } - Headers add(Http.HeaderName key, Object value, String note) { + Headers add(HeaderName key, Object value, String note) { add(key, value); if (notes != null) { notes.add(note); @@ -61,7 +62,7 @@ Headers add(Http.HeaderName key, Object value, String note) { return this; } - void setAndLog(BiConsumer consumer, String note) { + void setAndLog(BiConsumer consumer, String note) { headers.forEach(entry -> consumer.accept(entry.getKey(), entry.getValue())); CorsSupportHelper.LOGGER.log(DECISION_LEVEL, () -> note + ": " + headers + (notes == null ? "" : notes)); } @@ -129,8 +130,8 @@ static void logInferRequestType(RequestType result, List reasonsWhyCORS = new ArrayList<>(); // any reason is determinative List factorsWhyPreflight = new ArrayList<>(); // factors contribute but, individually, do not determine - if (!methodName.equalsIgnoreCase(Http.Method.OPTIONS.text())) { - reasonsWhyCORS.add(String.format("method is %s, not %s", methodName, Http.Method.OPTIONS.text())); + if (!methodName.equalsIgnoreCase(Method.OPTIONS.text())) { + reasonsWhyCORS.add(String.format("method is %s, not %s", methodName, Method.OPTIONS.text())); } else { factorsWhyPreflight.add(String.format("method is %s", methodName)); } diff --git a/examples/cors/src/main/java/io/helidon/examples/cors/GreetService.java b/examples/cors/src/main/java/io/helidon/examples/cors/GreetService.java index ac7c3c672cb..1f7315f3aeb 100644 --- a/examples/cors/src/main/java/io/helidon/examples/cors/GreetService.java +++ b/examples/cors/src/main/java/io/helidon/examples/cors/GreetService.java @@ -19,7 +19,7 @@ import java.util.Collections; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -102,13 +102,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON_BF.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting = GreetingMessage.fromRest(jo).getMessage(); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/examples/cors/src/test/java/io/helidon/examples/cors/MainTest.java b/examples/cors/src/test/java/io/helidon/examples/cors/MainTest.java index ec46604b2a4..232c7687cd0 100644 --- a/examples/cors/src/test/java/io/helidon/examples/cors/MainTest.java +++ b/examples/cors/src/test/java/io/helidon/examples/cors/MainTest.java @@ -19,17 +19,17 @@ import java.util.List; import java.util.Optional; -import io.helidon.http.Headers; -import io.helidon.http.WritableHeaders; import io.helidon.common.media.type.MediaTypes; import io.helidon.config.Config; import io.helidon.cors.CrossOriginConfig; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Headers; +import io.helidon.http.WritableHeaders; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientRequest; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import jakarta.json.JsonObject; import org.junit.jupiter.api.MethodOrderer; @@ -37,11 +37,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD; -import static io.helidon.http.Http.HeaderNames.HOST; -import static io.helidon.http.Http.HeaderNames.ORIGIN; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD; +import static io.helidon.http.HeaderNames.HOST; +import static io.helidon.http.HeaderNames.ORIGIN; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; diff --git a/examples/employee-app/src/test/java/io/helidon/examples/employee/MainTest.java b/examples/employee-app/src/test/java/io/helidon/examples/employee/MainTest.java index dcdd81d267a..ea331d04867 100644 --- a/examples/employee-app/src/test/java/io/helidon/examples/employee/MainTest.java +++ b/examples/employee-app/src/test/java/io/helidon/examples/employee/MainTest.java @@ -16,13 +16,13 @@ package io.helidon.examples.employee; -import io.helidon.http.Http; import io.helidon.config.Config; +import io.helidon.http.Status; +import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.testing.junit5.DirectClient; import io.helidon.webserver.testing.junit5.RoutingTest; import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webclient.http1.Http1ClientResponse; -import io.helidon.webserver.http.HttpRouting; import jakarta.json.JsonArray; import org.junit.jupiter.api.Test; @@ -48,7 +48,7 @@ public static void setup(HttpRouting.Builder routing) { public void testEmployees() { try (Http1ClientResponse response = client.get("/employees") .request()) { - assertThat("HTTP response2", response.status(), is(Http.Status.OK_200)); + assertThat("HTTP response2", response.status(), is(Status.OK_200)); assertThat(response.as(JsonArray.class).size(), is(40)); } } diff --git a/examples/integrations/micrometer/se/src/main/java/io/helidon/examples/integrations/micrometer/se/GreetService.java b/examples/integrations/micrometer/se/src/main/java/io/helidon/examples/integrations/micrometer/se/GreetService.java index 4317bf1f7b4..58d5b6592b8 100644 --- a/examples/integrations/micrometer/se/src/main/java/io/helidon/examples/integrations/micrometer/se/GreetService.java +++ b/examples/integrations/micrometer/se/src/main/java/io/helidon/examples/integrations/micrometer/se/GreetService.java @@ -19,7 +19,7 @@ import java.util.Collections; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRequest; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; @@ -120,13 +120,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON_BF.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting = GreetingMessage.fromRest(jo).getMessage(); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/examples/integrations/micrometer/se/src/test/java/io/helidon/examples/integrations/micrometer/se/MainTest.java b/examples/integrations/micrometer/se/src/test/java/io/helidon/examples/integrations/micrometer/se/MainTest.java index baaef19aaa7..04574b41673 100644 --- a/examples/integrations/micrometer/se/src/test/java/io/helidon/examples/integrations/micrometer/se/MainTest.java +++ b/examples/integrations/micrometer/se/src/test/java/io/helidon/examples/integrations/micrometer/se/MainTest.java @@ -17,13 +17,13 @@ import java.util.Collections; -import io.helidon.http.Http; import io.helidon.config.Config; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig.Builder; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import jakarta.json.Json; import jakarta.json.JsonBuilderFactory; @@ -86,7 +86,7 @@ void testUpdateGreeting() { .path("/greet/greeting") .submit(TEST_JSON_OBJECT)) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); } JsonObject jsonObject = personalizedGet("Joe"); diff --git a/examples/integrations/microstream/greetings-se/src/main/java/io/helidon/examples/integrations/microstream/greetings/se/GreetingService.java b/examples/integrations/microstream/greetings-se/src/main/java/io/helidon/examples/integrations/microstream/greetings/se/GreetingService.java index eb446b122f1..69dd6e1db95 100644 --- a/examples/integrations/microstream/greetings-se/src/main/java/io/helidon/examples/integrations/microstream/greetings/se/GreetingService.java +++ b/examples/integrations/microstream/greetings-se/src/main/java/io/helidon/examples/integrations/microstream/greetings/se/GreetingService.java @@ -21,7 +21,7 @@ import java.util.logging.Logger; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.integrations.microstream.core.EmbeddedStorageManagerBuilder; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; @@ -125,13 +125,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/examples/integrations/neo4j/src/test/java/io/helidon/examples/integrations/neo4j/MainTest.java b/examples/integrations/neo4j/src/test/java/io/helidon/examples/integrations/neo4j/MainTest.java index 2365576926b..c6497aebdad 100644 --- a/examples/integrations/neo4j/src/test/java/io/helidon/examples/integrations/neo4j/MainTest.java +++ b/examples/integrations/neo4j/src/test/java/io/helidon/examples/integrations/neo4j/MainTest.java @@ -16,12 +16,12 @@ package io.helidon.examples.integrations.neo4j; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import jakarta.json.JsonArray; import org.junit.jupiter.api.AfterAll; @@ -88,7 +88,7 @@ void testMovies() { @Test public void testHealth() { try (Http1ClientResponse response = webClient.get("/observe/health").request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); } } diff --git a/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java index e8595937361..bfd342e7054 100644 --- a/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java +++ b/examples/integrations/oci/atp/src/main/java/io/helidon/examples/integrations/oci/atp/AtpService.java @@ -36,7 +36,7 @@ import io.helidon.dbclient.DbClient; import io.helidon.dbclient.DbRow; import io.helidon.dbclient.jdbc.JdbcClientProvider; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -85,7 +85,7 @@ private void generateWallet(ServerRequest req, ServerResponse res) { if (walletResponse.getContentLength() == 0) { LOGGER.log(Level.SEVERE, "GenerateAutonomousDatabaseWalletResponse is empty"); - res.status(Http.Status.NOT_FOUND_404).send(); + res.status(Status.NOT_FOUND_404).send(); return; } @@ -94,7 +94,7 @@ private void generateWallet(ServerRequest req, ServerResponse res) { walletContent = walletResponse.getInputStream().readAllBytes(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Error processing GenerateAutonomousDatabaseWalletResponse", e); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); + res.status(Status.INTERNAL_SERVER_ERROR_500).send(); return; } diff --git a/examples/integrations/oci/objectstorage-cdi/src/main/java/io/helidon/examples/integrations/oci/objectstorage/cdi/ObjectStorageResource.java b/examples/integrations/oci/objectstorage-cdi/src/main/java/io/helidon/examples/integrations/oci/objectstorage/cdi/ObjectStorageResource.java index b62fa0ed71e..6b753a47900 100644 --- a/examples/integrations/oci/objectstorage-cdi/src/main/java/io/helidon/examples/integrations/oci/objectstorage/cdi/ObjectStorageResource.java +++ b/examples/integrations/oci/objectstorage-cdi/src/main/java/io/helidon/examples/integrations/oci/objectstorage/cdi/ObjectStorageResource.java @@ -24,7 +24,7 @@ import java.util.logging.Level; import java.util.logging.Logger; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import com.oracle.bmc.objectstorage.ObjectStorage; import com.oracle.bmc.objectstorage.requests.DeleteObjectRequest; @@ -90,10 +90,10 @@ public Response download(@PathParam("file-name") String fileName) { try (InputStream fileStream = getObjectResponse.getInputStream()) { byte[] objectContent = fileStream.readAllBytes(); Response.ResponseBuilder ok = Response.ok(objectContent) - .header(Http.HeaderNames.CONTENT_DISPOSITION.defaultCase(), "attachment; filename=\"" + fileName + "\"") + .header(HeaderNames.CONTENT_DISPOSITION.defaultCase(), "attachment; filename=\"" + fileName + "\"") .header("opc-request-id", getObjectResponse.getOpcRequestId()) .header("request-id", getObjectResponse.getOpcClientRequestId()) - .header(Http.HeaderNames.CONTENT_LENGTH.defaultCase(), getObjectResponse.getContentLength()); + .header(HeaderNames.CONTENT_LENGTH.defaultCase(), getObjectResponse.getContentLength()); return ok.build(); } catch (IOException e) { diff --git a/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java index fdd4b763ff5..9d45a77b5cb 100644 --- a/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java +++ b/examples/integrations/oci/objectstorage/src/main/java/io/helidon/examples/integrations/oci/objecstorage/ObjectStorageService.java @@ -26,7 +26,8 @@ import io.helidon.config.Config; import io.helidon.config.ConfigException; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -101,22 +102,22 @@ public void download(ServerRequest request, ServerResponse response) { if (getObjectResponse.getContentLength() == 0) { LOGGER.log(Level.SEVERE, "GetObjectResponse is empty"); - response.status(Http.Status.NOT_FOUND_404).send(); + response.status(Status.NOT_FOUND_404).send(); return; } try (InputStream fileStream = getObjectResponse.getInputStream()) { byte[] objectContent = fileStream.readAllBytes(); response - .status(Http.Status.OK_200) - .header(Http.HeaderNames.CONTENT_DISPOSITION.defaultCase(), "attachment; filename=\"" + fileName + "\"") + .status(Status.OK_200) + .header(HeaderNames.CONTENT_DISPOSITION.defaultCase(), "attachment; filename=\"" + fileName + "\"") .header("opc-request-id", getObjectResponse.getOpcRequestId()) - .header(Http.HeaderNames.CONTENT_LENGTH.defaultCase(), getObjectResponse.getContentLength().toString()); + .header(HeaderNames.CONTENT_LENGTH.defaultCase(), getObjectResponse.getContentLength().toString()); response.send(objectContent); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Error processing GetObjectResponse", e); - response.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); + response.status(Status.INTERNAL_SERVER_ERROR_500).send(); } } @@ -141,12 +142,12 @@ public void upload(ServerRequest request, ServerResponse response) { .build(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Error creating PutObjectRequest", e); - response.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); + response.status(Status.INTERNAL_SERVER_ERROR_500).send(); return; } PutObjectResponse putObjectResponse = objectStorageClient.putObject(putObjectRequest); - response.status(Http.Status.OK_200).header("opc-request-id", putObjectResponse.getOpcRequestId()); + response.status(Status.OK_200).header("opc-request-id", putObjectResponse.getOpcRequestId()); response.send(); } @@ -164,7 +165,7 @@ public void delete(ServerRequest request, ServerResponse response) { .bucketName(bucketName) .objectName(fileName) .build()); - response.status(Http.Status.OK_200).header("opc-request-id", deleteObjectResponse.getOpcRequestId()); + response.status(Status.OK_200).header("opc-request-id", deleteObjectResponse.getOpcRequestId()); response.send(); } diff --git a/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java index 4e88260056a..4a017270212 100644 --- a/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java +++ b/examples/integrations/oci/vault/src/main/java/io/helidon/examples/integrations/oci/vault/VaultService.java @@ -24,7 +24,7 @@ import java.util.logging.Logger; import io.helidon.common.Base64Value; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -111,7 +111,7 @@ private void getSecret(ServerRequest req, ServerResponse res) { res.send(Base64Value.createFromEncoded(((Base64SecretBundleContentDetails) content).getContent()) .toDecodedString()); } else { - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send("Invalid secret content type"); + res.status(Status.INTERNAL_SERVER_ERROR_500).send("Invalid secret content type"); } }, res); @@ -218,7 +218,7 @@ private void ociHandler(Consumer consumer, ServerResponse respon consumer.accept(response); } catch (Throwable error) { LOGGER.log(Level.WARNING, "OCI Exception", error); - response.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(error.getMessage()); + response.status(Status.INTERNAL_SERVER_ERROR_500).send(error.getMessage()); } } } diff --git a/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/CubbyholeService.java b/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/CubbyholeService.java index ccb0c4c158c..2fa24d2c8d3 100644 --- a/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/CubbyholeService.java +++ b/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/CubbyholeService.java @@ -19,7 +19,7 @@ import java.util.Map; import java.util.Optional; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.integrations.vault.Secret; import io.helidon.integrations.vault.secrets.cubbyhole.CubbyholeSecrets; import io.helidon.integrations.vault.sys.Sys; @@ -55,7 +55,7 @@ private void getSecret(ServerRequest req, ServerResponse res) { // using toString so we do not need to depend on JSON-B res.send(secret.get().values().toString()); } else { - res.status(Http.Status.NOT_FOUND_404); + res.status(Status.NOT_FOUND_404); res.send(); } } diff --git a/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/Kv1Service.java b/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/Kv1Service.java index 8faf2634d2a..4f8edae62dc 100644 --- a/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/Kv1Service.java +++ b/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/Kv1Service.java @@ -19,7 +19,7 @@ import java.util.Map; import java.util.Optional; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.integrations.vault.Secret; import io.helidon.integrations.vault.secrets.kv1.Kv1Secrets; import io.helidon.integrations.vault.sys.Sys; @@ -75,7 +75,7 @@ private void getSecret(ServerRequest req, ServerResponse res) { // using toString so we do not need to depend on JSON-B res.send(secret.get().values().toString()); } else { - res.status(Http.Status.NOT_FOUND_404); + res.status(Status.NOT_FOUND_404); res.send(); } } diff --git a/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/Kv2Service.java b/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/Kv2Service.java index 165fd457a86..a93395a1715 100644 --- a/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/Kv2Service.java +++ b/examples/integrations/vault/hcp/src/main/java/io/helidon/examples/integrations/vault/hcp/Kv2Service.java @@ -19,7 +19,7 @@ import java.util.Map; import java.util.Optional; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.integrations.vault.secrets.kv2.Kv2Secret; import io.helidon.integrations.vault.secrets.kv2.Kv2Secrets; import io.helidon.integrations.vault.sys.Sys; @@ -64,7 +64,7 @@ private void getSecret(ServerRequest req, ServerResponse res) { Kv2Secret kv2Secret = secret.get(); res.send("Version " + kv2Secret.metadata().version() + ", secret: " + kv2Secret.values().toString()); } else { - res.status(Http.Status.NOT_FOUND_404); + res.status(Status.NOT_FOUND_404); res.send(); } } diff --git a/examples/media/multipart/src/main/java/io/helidon/examples/media/multipart/FileService.java b/examples/media/multipart/src/main/java/io/helidon/examples/media/multipart/FileService.java index 3ea9532cdd1..9000b19bd24 100644 --- a/examples/media/multipart/src/main/java/io/helidon/examples/media/multipart/FileService.java +++ b/examples/media/multipart/src/main/java/io/helidon/examples/media/multipart/FileService.java @@ -28,7 +28,9 @@ import io.helidon.common.media.type.MediaTypes; import io.helidon.http.ContentDisposition; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.ServerResponseHeaders; import io.helidon.http.media.multipart.MultiPart; import io.helidon.http.media.multipart.ReadablePart; @@ -41,15 +43,15 @@ import jakarta.json.JsonArrayBuilder; import jakarta.json.JsonBuilderFactory; -import static io.helidon.http.Http.Status.BAD_REQUEST_400; -import static io.helidon.http.Http.Status.MOVED_PERMANENTLY_301; -import static io.helidon.http.Http.Status.NOT_FOUND_404; +import static io.helidon.http.Status.BAD_REQUEST_400; +import static io.helidon.http.Status.MOVED_PERMANENTLY_301; +import static io.helidon.http.Status.NOT_FOUND_404; /** * File service. */ public final class FileService implements HttpService { - private static final Http.Header UI_LOCATION = Http.Headers.createCached(Http.HeaderNames.LOCATION, "/ui"); + private static final Header UI_LOCATION = HeaderValues.createCached(HeaderNames.LOCATION, "/ui"); private final JsonBuilderFactory jsonFactory; private final Path storage; diff --git a/examples/media/multipart/src/main/java/io/helidon/examples/media/multipart/Main.java b/examples/media/multipart/src/main/java/io/helidon/examples/media/multipart/Main.java index 24aac24c742..b961a934bc7 100644 --- a/examples/media/multipart/src/main/java/io/helidon/examples/media/multipart/Main.java +++ b/examples/media/multipart/src/main/java/io/helidon/examples/media/multipart/Main.java @@ -15,7 +15,10 @@ */ package io.helidon.examples.media.multipart; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.staticcontent.StaticContentService; @@ -24,7 +27,7 @@ * This application provides a simple file upload service with a UI to exercise multipart. */ public final class Main { - private static final Http.Header UI_LOCATION = Http.Headers.createCached(Http.HeaderNames.LOCATION, "/ui"); + private static final Header UI_LOCATION = HeaderValues.createCached(HeaderNames.LOCATION, "/ui"); private Main() { } @@ -51,7 +54,7 @@ public static void main(String[] args) { */ static void routing(HttpRules rules) { rules.any("/", (req, res) -> { - res.status(Http.Status.MOVED_PERMANENTLY_301); + res.status(Status.MOVED_PERMANENTLY_301); res.header(UI_LOCATION); res.send(); }) diff --git a/examples/media/multipart/src/test/java/io/helidon/examples/media/multipart/FileServiceTest.java b/examples/media/multipart/src/test/java/io/helidon/examples/media/multipart/FileServiceTest.java index 23e498c3989..52685cf9a6a 100644 --- a/examples/media/multipart/src/test/java/io/helidon/examples/media/multipart/FileServiceTest.java +++ b/examples/media/multipart/src/test/java/io/helidon/examples/media/multipart/FileServiceTest.java @@ -21,15 +21,16 @@ import java.nio.file.Path; import java.util.List; -import io.helidon.http.Http; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.http.media.multipart.WriteableMultiPart; import io.helidon.http.media.multipart.WriteablePart; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import jakarta.json.JsonObject; import jakarta.json.JsonString; @@ -71,7 +72,7 @@ public void testUpload() throws IOException { .submit(WriteableMultiPart.builder() .addPart(writeablePart("file[]", "foo.txt", file)) .build())) { - assertThat(response.status(), is(Http.Status.MOVED_PERMANENTLY_301)); + assertThat(response.status(), is(Status.MOVED_PERMANENTLY_301)); } } @@ -88,7 +89,7 @@ public void testStreamUpload() throws IOException { .addPart(writeablePart("file[]", "streamed-foo.txt", file)) .addPart(writeablePart("otherPart", "streamed-foo2.txt", file2)) .build())) { - assertThat(response.status(), is(Http.Status.MOVED_PERMANENTLY_301)); + assertThat(response.status(), is(Status.MOVED_PERMANENTLY_301)); } } @@ -96,7 +97,7 @@ public void testStreamUpload() throws IOException { @Order(3) public void testList() { try (Http1ClientResponse response = client.get("/api").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json, Matchers.is(notNullValue())); List files = json.getJsonArray("files").getValuesAs(v -> ((JsonString) v).getString()); @@ -108,8 +109,8 @@ public void testList() { @Order(4) public void testDownload() { try (Http1ClientResponse response = client.get("/api").path("foo.txt").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers().first(Http.HeaderNames.CONTENT_DISPOSITION).orElse(null), + assertThat(response.status(), is(Status.OK_200)); + assertThat(response.headers().first(HeaderNames.CONTENT_DISPOSITION).orElse(null), containsString("filename=\"foo.txt\"")); byte[] bytes = response.as(byte[].class); assertThat(new String(bytes, StandardCharsets.UTF_8), Matchers.is("bar\n")); diff --git a/examples/metrics/exemplar/src/main/java/io/helidon/examples/metrics/exemplar/GreetService.java b/examples/metrics/exemplar/src/main/java/io/helidon/examples/metrics/exemplar/GreetService.java index 23309bb1c8a..17033a78f24 100644 --- a/examples/metrics/exemplar/src/main/java/io/helidon/examples/metrics/exemplar/GreetService.java +++ b/examples/metrics/exemplar/src/main/java/io/helidon/examples/metrics/exemplar/GreetService.java @@ -20,7 +20,7 @@ import java.util.concurrent.atomic.AtomicReference; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.metrics.api.Counter; import io.helidon.metrics.api.Meter; import io.helidon.metrics.api.MeterRegistry; @@ -123,13 +123,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/examples/metrics/filtering/se/src/main/java/io/helidon/examples/metrics/filtering/se/GreetService.java b/examples/metrics/filtering/se/src/main/java/io/helidon/examples/metrics/filtering/se/GreetService.java index ea469a83e4c..371643187ff 100644 --- a/examples/metrics/filtering/se/src/main/java/io/helidon/examples/metrics/filtering/se/GreetService.java +++ b/examples/metrics/filtering/se/src/main/java/io/helidon/examples/metrics/filtering/se/GreetService.java @@ -20,7 +20,7 @@ import java.util.concurrent.atomic.AtomicReference; import io.helidon.common.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.metrics.api.Counter; import io.helidon.metrics.api.MeterRegistry; import io.helidon.metrics.api.Timer; @@ -119,13 +119,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/examples/metrics/http-status-count-se/src/main/java/io/helidon/examples/se/httpstatuscount/GreetService.java b/examples/metrics/http-status-count-se/src/main/java/io/helidon/examples/se/httpstatuscount/GreetService.java index dfade36b292..5a14c09ebb0 100644 --- a/examples/metrics/http-status-count-se/src/main/java/io/helidon/examples/se/httpstatuscount/GreetService.java +++ b/examples/metrics/http-status-count-se/src/main/java/io/helidon/examples/se/httpstatuscount/GreetService.java @@ -19,7 +19,7 @@ import java.util.concurrent.atomic.AtomicReference; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -104,13 +104,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/examples/metrics/http-status-count-se/src/test/java/io/helidon/examples/se/httpstatuscount/StatusService.java b/examples/metrics/http-status-count-se/src/test/java/io/helidon/examples/se/httpstatuscount/StatusService.java index 0f815528a76..756e66d4698 100644 --- a/examples/metrics/http-status-count-se/src/test/java/io/helidon/examples/se/httpstatuscount/StatusService.java +++ b/examples/metrics/http-status-count-se/src/test/java/io/helidon/examples/se/httpstatuscount/StatusService.java @@ -15,7 +15,7 @@ */ package io.helidon.examples.se.httpstatuscount; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -40,7 +40,7 @@ private void respondWithRequestedStatus(ServerRequest request, ServerResponse re status = Integer.parseInt(statusText); msg = "Successful conversion"; } catch (NumberFormatException ex) { - status = Http.Status.INTERNAL_SERVER_ERROR_500.code(); + status = Status.INTERNAL_SERVER_ERROR_500.code(); msg = "Unsuccessful conversion"; } response.status(status).send(msg); diff --git a/examples/metrics/http-status-count-se/src/test/java/io/helidon/examples/se/httpstatuscount/StatusTest.java b/examples/metrics/http-status-count-se/src/test/java/io/helidon/examples/se/httpstatuscount/StatusTest.java index dc7030d3d2f..b8d3751c64d 100644 --- a/examples/metrics/http-status-count-se/src/test/java/io/helidon/examples/se/httpstatuscount/StatusTest.java +++ b/examples/metrics/http-status-count-se/src/test/java/io/helidon/examples/se/httpstatuscount/StatusTest.java @@ -17,18 +17,18 @@ import java.util.Set; -import io.helidon.http.Http.Status; import io.helidon.common.media.type.MediaTypes; import io.helidon.config.Config; +import io.helidon.http.Status; import io.helidon.metrics.api.Counter; import io.helidon.metrics.api.MeterRegistry; import io.helidon.metrics.api.Metrics; import io.helidon.metrics.api.Tag; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; diff --git a/examples/metrics/kpi/src/main/java/io/helidon/examples/metrics/kpi/GreetService.java b/examples/metrics/kpi/src/main/java/io/helidon/examples/metrics/kpi/GreetService.java index 8dd80668a7b..f6dc74ac2a8 100644 --- a/examples/metrics/kpi/src/main/java/io/helidon/examples/metrics/kpi/GreetService.java +++ b/examples/metrics/kpi/src/main/java/io/helidon/examples/metrics/kpi/GreetService.java @@ -20,7 +20,7 @@ import java.util.concurrent.atomic.AtomicReference; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.metrics.api.Counter; import io.helidon.metrics.api.Meter; import io.helidon.metrics.api.MeterRegistry; @@ -124,13 +124,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/examples/microprofile/cors/src/test/java/io/helidon/microprofile/examples/cors/TestCORS.java b/examples/microprofile/cors/src/test/java/io/helidon/microprofile/examples/cors/TestCORS.java index 66a14ace3fd..3a2d3e3ec04 100644 --- a/examples/microprofile/cors/src/test/java/io/helidon/microprofile/examples/cors/TestCORS.java +++ b/examples/microprofile/cors/src/test/java/io/helidon/microprofile/examples/cors/TestCORS.java @@ -18,13 +18,12 @@ import java.util.List; import java.util.Optional; -import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; import io.helidon.common.media.type.MediaTypes; import io.helidon.config.Config; +import io.helidon.http.HeaderNames; +import io.helidon.http.Headers; +import io.helidon.http.Method; import io.helidon.microprofile.server.Server; -import io.helidon.http.media.jsonp.JsonpSupport; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientRequest; import io.helidon.webclient.http1.Http1ClientResponse; @@ -126,9 +125,9 @@ void testGreetingChangeWithCors() { // Send the pre-flight request and check the response. - Http1ClientRequest req = client.method(Http.Method.OPTIONS) + Http1ClientRequest req = client.method(Method.OPTIONS) .header(HeaderNames.ORIGIN, "http://foo.com") - .header(Http.HeaderNames.HOST, "here.com") + .header(HeaderNames.HOST, "here.com") .header(HeaderNames.ACCESS_CONTROL_REQUEST_METHOD, "PUT"); List allowOrigins; diff --git a/examples/microprofile/http-status-count-mp/src/test/java/io/helidon/examples/mp/httpstatuscount/StatusResource.java b/examples/microprofile/http-status-count-mp/src/test/java/io/helidon/examples/mp/httpstatuscount/StatusResource.java index 1651d65d96e..38ca0eb5370 100644 --- a/examples/microprofile/http-status-count-mp/src/test/java/io/helidon/examples/mp/httpstatuscount/StatusResource.java +++ b/examples/microprofile/http-status-count-mp/src/test/java/io/helidon/examples/mp/httpstatuscount/StatusResource.java @@ -15,7 +15,7 @@ */ package io.helidon.examples.mp.httpstatuscount; -import io.helidon.http.Http; +import io.helidon.http.Status; import jakarta.enterprise.context.RequestScoped; import jakarta.ws.rs.GET; @@ -43,7 +43,7 @@ public Response reportStatus(@PathParam("status") String statusText) { status = Integer.parseInt(statusText); msg = "Successful conversion"; } catch (NumberFormatException ex) { - status = Http.Status.INTERNAL_SERVER_ERROR_500.code(); + status = Status.INTERNAL_SERVER_ERROR_500.code(); msg = "Unsuccessful conversion"; } return status == 204 ? Response.status(204).build() : Response.status(status).entity(msg).build(); diff --git a/examples/microprofile/http-status-count-mp/src/test/java/io/helidon/examples/mp/httpstatuscount/StatusTest.java b/examples/microprofile/http-status-count-mp/src/test/java/io/helidon/examples/mp/httpstatuscount/StatusTest.java index 0dcde863d18..4b9c723f2ba 100644 --- a/examples/microprofile/http-status-count-mp/src/test/java/io/helidon/examples/mp/httpstatuscount/StatusTest.java +++ b/examples/microprofile/http-status-count-mp/src/test/java/io/helidon/examples/mp/httpstatuscount/StatusTest.java @@ -15,7 +15,7 @@ */ package io.helidon.examples.mp.httpstatuscount; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.microprofile.tests.junit5.AddBean; import io.helidon.microprofile.tests.junit5.HelidonTest; @@ -74,7 +74,7 @@ void checkStatusAfterGreet() { Response response = webTarget.path("/greet") .request(MediaType.APPLICATION_JSON) .get(); - assertThat("Status of /greet", response.getStatus(), is(Http.Status.OK_200.code())); + assertThat("Status of /greet", response.getStatus(), is(Status.OK_200.code())); checkCounters(response.getStatus(), before); } diff --git a/examples/microprofile/static-content/src/test/java/io/helidon/microprofile/example/staticc/StaticContentTest.java b/examples/microprofile/static-content/src/test/java/io/helidon/microprofile/example/staticc/StaticContentTest.java index 929ea0fe874..d1225185889 100644 --- a/examples/microprofile/static-content/src/test/java/io/helidon/microprofile/example/staticc/StaticContentTest.java +++ b/examples/microprofile/static-content/src/test/java/io/helidon/microprofile/example/staticc/StaticContentTest.java @@ -18,7 +18,7 @@ import java.io.IOException; -import io.helidon.http.Http; +import io.helidon.http.Status; import jakarta.enterprise.inject.se.SeContainer; import jakarta.enterprise.inject.spi.CDI; @@ -69,7 +69,7 @@ void testWelcomePage() { .request() .accept(MediaType.TEXT_HTML_TYPE) .get()) { - assertThat("Status should be 200", response.getStatus(), is(Http.Status.OK_200.code())); + assertThat("Status should be 200", response.getStatus(), is(Status.OK_200.code())); String str = response.readEntity(String.class); @@ -87,7 +87,7 @@ void testStaticResource() { .request() .accept(MediaType.TEXT_HTML_TYPE) .get()) { - assertThat("Status should be 200", response.getStatus(), is(Http.Status.OK_200.code())); + assertThat("Status should be 200", response.getStatus(), is(Status.OK_200.code())); String str = response.readEntity(String.class); diff --git a/examples/openapi/src/main/java/io/helidon/examples/openapi/GreetService.java b/examples/openapi/src/main/java/io/helidon/examples/openapi/GreetService.java index d2b58bb4a1e..6dbde8fd8a6 100644 --- a/examples/openapi/src/main/java/io/helidon/examples/openapi/GreetService.java +++ b/examples/openapi/src/main/java/io/helidon/examples/openapi/GreetService.java @@ -19,7 +19,7 @@ import java.util.Map; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -101,13 +101,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON_BF.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting = GreetingMessage.fromRest(jo).getMessage(); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/examples/openapi/src/test/java/io/helidon/examples/openapi/MainTest.java b/examples/openapi/src/test/java/io/helidon/examples/openapi/MainTest.java index fbed258d3e7..1cf620366ea 100644 --- a/examples/openapi/src/test/java/io/helidon/examples/openapi/MainTest.java +++ b/examples/openapi/src/test/java/io/helidon/examples/openapi/MainTest.java @@ -18,14 +18,14 @@ import java.util.Map; -import io.helidon.http.Http; import io.helidon.common.media.type.MediaTypes; import io.helidon.examples.openapi.internal.SimpleAPIModelReader; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import jakarta.json.Json; import jakarta.json.JsonBuilderFactory; @@ -79,7 +79,7 @@ public void testHelloWorld() { } try (Http1ClientResponse response = client.get("/observe/health").request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); } try (Http1ClientResponse response = client.get("/observe/metrics").request()) { diff --git a/examples/quickstarts/helidon-quickstart-se/src/main/java/io/helidon/examples/quickstart/se/GreetService.java b/examples/quickstarts/helidon-quickstart-se/src/main/java/io/helidon/examples/quickstart/se/GreetService.java index 0312b13b05d..4426c02521a 100644 --- a/examples/quickstarts/helidon-quickstart-se/src/main/java/io/helidon/examples/quickstart/se/GreetService.java +++ b/examples/quickstarts/helidon-quickstart-se/src/main/java/io/helidon/examples/quickstart/se/GreetService.java @@ -19,7 +19,7 @@ import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -105,13 +105,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/examples/quickstarts/helidon-quickstart-se/src/test/java/io/helidon/examples/quickstart/se/MainTest.java b/examples/quickstarts/helidon-quickstart-se/src/test/java/io/helidon/examples/quickstart/se/MainTest.java index 52cf71d2aa7..40917691d99 100644 --- a/examples/quickstarts/helidon-quickstart-se/src/test/java/io/helidon/examples/quickstart/se/MainTest.java +++ b/examples/quickstarts/helidon-quickstart-se/src/test/java/io/helidon/examples/quickstart/se/MainTest.java @@ -16,12 +16,12 @@ package io.helidon.examples.quickstart.se; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import jakarta.json.JsonObject; import org.junit.jupiter.api.Test; @@ -46,7 +46,7 @@ static void routing(HttpRouting.Builder builder) { @Test void testRootRoute() { try (Http1ClientResponse response = client.get("/greet").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("message"), is("Hello World!")); } @@ -55,21 +55,21 @@ void testRootRoute() { @Test void testHealthObserver() { try (Http1ClientResponse response = client.get("/observe/health").request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); } } @Test void testDeadlockHealthCheck() { try (Http1ClientResponse response = client.get("/observe/health/live/deadlock").request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); } } @Test void testMetricsObserver() { try (Http1ClientResponse response = client.get("/observe/metrics").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } } } diff --git a/examples/quickstarts/helidon-standalone-quickstart-se/src/main/java/io/helidon/examples/quickstart/se/GreetService.java b/examples/quickstarts/helidon-standalone-quickstart-se/src/main/java/io/helidon/examples/quickstart/se/GreetService.java index 0312b13b05d..4426c02521a 100644 --- a/examples/quickstarts/helidon-standalone-quickstart-se/src/main/java/io/helidon/examples/quickstart/se/GreetService.java +++ b/examples/quickstarts/helidon-standalone-quickstart-se/src/main/java/io/helidon/examples/quickstart/se/GreetService.java @@ -19,7 +19,7 @@ import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -105,13 +105,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/examples/quickstarts/helidon-standalone-quickstart-se/src/test/java/io/helidon/examples/quickstart/se/MainTest.java b/examples/quickstarts/helidon-standalone-quickstart-se/src/test/java/io/helidon/examples/quickstart/se/MainTest.java index 3d33b31ed54..eeb59c84537 100644 --- a/examples/quickstarts/helidon-standalone-quickstart-se/src/test/java/io/helidon/examples/quickstart/se/MainTest.java +++ b/examples/quickstarts/helidon-standalone-quickstart-se/src/test/java/io/helidon/examples/quickstart/se/MainTest.java @@ -16,12 +16,13 @@ package io.helidon.examples.quickstart.se; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; + import jakarta.json.JsonObject; import org.junit.jupiter.api.Test; @@ -45,7 +46,7 @@ static void routing(HttpRouting.Builder builder) { @Test void testRootRoute() { try (Http1ClientResponse response = client.get("/greet").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("message"), is("Hello World!")); } @@ -54,20 +55,20 @@ void testRootRoute() { @Test void testHealthObserver() { try (Http1ClientResponse response = client.get("/observe/health").request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); } } @Test void testDeadlockHealthCheck() { try (Http1ClientResponse response = client.get("/observe/health/live/deadlock").request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); } } @Test void testMetricsObserver() { try (Http1ClientResponse response = client.get("/observe/metrics").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } } } diff --git a/examples/security/basic-auth-with-static-content/src/test/java/io/helidon/examples/security/basicauth/BasicExampleTest.java b/examples/security/basic-auth-with-static-content/src/test/java/io/helidon/examples/security/basicauth/BasicExampleTest.java index 216a5d4f132..e69f466bcd8 100644 --- a/examples/security/basic-auth-with-static-content/src/test/java/io/helidon/examples/security/basicauth/BasicExampleTest.java +++ b/examples/security/basic-auth-with-static-content/src/test/java/io/helidon/examples/security/basicauth/BasicExampleTest.java @@ -19,7 +19,8 @@ import java.net.URI; import java.util.Set; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.security.EndpointConfig; import io.helidon.security.Security; import io.helidon.security.providers.httpauth.HttpBasicAuthProvider; @@ -61,7 +62,7 @@ protected BasicExampleTest(URI uri) { public void testPublic() { //Must be accessible without authentication try (Http1ClientResponse response = client.get().uri("/public").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, containsString("")); } @@ -122,7 +123,7 @@ public void getNoAuthn() { try (Http1ClientResponse response = client.get().uri(uri).request()) { // authentication is optional, so we are not challenged, only forbidden, as the role can never be there... - assertThat(response.status(), is(Http.Status.FORBIDDEN_403)); + assertThat(response.status(), is(Status.FORBIDDEN_403)); } } @@ -130,8 +131,8 @@ private void testNotAuthorized(String uri) { //Must NOT be accessible without authentication try (Http1ClientResponse response = client.get().uri(uri).request()) { - assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); - String header = response.headers().get(Http.HeaderNames.WWW_AUTHENTICATE).value(); + assertThat(response.status(), is(Status.UNAUTHORIZED_401)); + String header = response.headers().get(HeaderNames.WWW_AUTHENTICATE).value(); assertThat(header.toLowerCase(), containsString("basic")); assertThat(header, containsString("helidon")); @@ -150,7 +151,7 @@ private Http1ClientResponse callProtected(String uri, String username, String pa @SuppressWarnings("SameParameterValue") private void testProtectedDenied(String uri, String username, String password) { try (Http1ClientResponse response = callProtected(uri, username, password)) { - assertThat(response.status(), is(Http.Status.FORBIDDEN_403)); + assertThat(response.status(), is(Status.FORBIDDEN_403)); } } @@ -164,7 +165,7 @@ private void testProtected(String uri, try (Http1ClientResponse response = callProtected(uri, username, password)) { String entity = response.entity().as(String.class); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); // check login assertThat(entity, containsString("id='" + username + "'")); diff --git a/examples/security/google-login/src/test/java/io/helidon/examples/security/google/GoogleMainTest.java b/examples/security/google-login/src/test/java/io/helidon/examples/security/google/GoogleMainTest.java index b1691adf143..3d3fe61d49a 100644 --- a/examples/security/google-login/src/test/java/io/helidon/examples/security/google/GoogleMainTest.java +++ b/examples/security/google-login/src/test/java/io/helidon/examples/security/google/GoogleMainTest.java @@ -16,7 +16,8 @@ package io.helidon.examples.security.google; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; @@ -40,8 +41,8 @@ public abstract class GoogleMainTest { public void testEndpoint() { try (Http1ClientResponse response = client.get("/rest/profile").request()) { - assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); - assertThat(response.headers().first(Http.HeaderNames.WWW_AUTHENTICATE), + assertThat(response.status(), is(Status.UNAUTHORIZED_401)); + assertThat(response.headers().first(HeaderNames.WWW_AUTHENTICATE), optionalValue(is("Bearer realm=\"helidon\",scope=\"openid profile email\""))); } } diff --git a/examples/security/outbound-override/src/main/java/io/helidon/security/examples/outbound/OutboundOverrideJwtExample.java b/examples/security/outbound-override/src/main/java/io/helidon/security/examples/outbound/OutboundOverrideJwtExample.java index f2fb672c8d3..7229cf2dbd3 100644 --- a/examples/security/outbound-override/src/main/java/io/helidon/security/examples/outbound/OutboundOverrideJwtExample.java +++ b/examples/security/outbound-override/src/main/java/io/helidon/security/examples/outbound/OutboundOverrideJwtExample.java @@ -19,7 +19,7 @@ import io.helidon.config.Config; import io.helidon.config.ConfigSources; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.security.Principal; import io.helidon.security.SecurityContext; import io.helidon.security.Subject; @@ -99,7 +99,7 @@ static void setup(WebServerConfig.Builder server) { .get("/hello", (req, res) -> { // This is the token. It should be bearer - req.headers().first(Http.HeaderNames.AUTHORIZATION) + req.headers().first(HeaderNames.AUTHORIZATION) .ifPresent(System.out::println); String username = req.context() diff --git a/examples/security/webserver-digest-auth/src/test/java/io/helidon/examples/security/digest/DigestExampleTest.java b/examples/security/webserver-digest-auth/src/test/java/io/helidon/examples/security/digest/DigestExampleTest.java index d43d6f2ceab..f065afb64fa 100644 --- a/examples/security/webserver-digest-auth/src/test/java/io/helidon/examples/security/digest/DigestExampleTest.java +++ b/examples/security/webserver-digest-auth/src/test/java/io/helidon/examples/security/digest/DigestExampleTest.java @@ -19,7 +19,7 @@ import java.net.URI; import java.util.Set; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; @@ -127,7 +127,7 @@ private void testNotAuthorized(String uri) { //Must NOT be accessible without authentication try (Http1ClientResponse response = client.get().path(uri).request()) { assertThat(response.status().code(), is(401)); - String header = response.headers().first(Http.HeaderNames.create("WWW-Authenticate")).orElse(null); + String header = response.headers().first(HeaderNames.create("WWW-Authenticate")).orElse(null); assertThat(header, notNullValue()); assertThat(header.toLowerCase(), containsString("digest")); assertThat(header, containsString("mic")); diff --git a/examples/security/webserver-digest-auth/src/test/java/io/helidon/examples/security/digest/WebClientAuthenticationService.java b/examples/security/webserver-digest-auth/src/test/java/io/helidon/examples/security/digest/WebClientAuthenticationService.java index fff71d63cf5..76c32d4cb68 100644 --- a/examples/security/webserver-digest-auth/src/test/java/io/helidon/examples/security/digest/WebClientAuthenticationService.java +++ b/examples/security/webserver-digest-auth/src/test/java/io/helidon/examples/security/digest/WebClientAuthenticationService.java @@ -17,7 +17,8 @@ import java.util.Map; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webclient.api.WebClientServiceRequest; import io.helidon.webclient.api.WebClientServiceResponse; import io.helidon.webclient.spi.WebClientService; @@ -43,7 +44,7 @@ class WebClientAuthenticationService implements WebClientService { @Override public WebClientServiceResponse handle(Chain chain, WebClientServiceRequest request) { WebClientServiceResponse response = chain.proceed(request); - if (response.status() != Http.Status.UNAUTHORIZED_401) { + if (response.status() != Status.UNAUTHORIZED_401) { return response; } Map properties = request.properties(); @@ -52,7 +53,7 @@ public WebClientServiceResponse handle(Chain chain, WebClientServiceRequest requ if (username == null || password == null) { return response; } - String challenge = response.headers().first(Http.HeaderNames.WWW_AUTHENTICATE).orElse(null); + String challenge = response.headers().first(HeaderNames.WWW_AUTHENTICATE).orElse(null); if (challenge == null) { return response; } @@ -62,7 +63,7 @@ public WebClientServiceResponse handle(Chain chain, WebClientServiceRequest requ if (atz == null) { return response; } - request.headers().add(Http.HeaderNames.AUTHORIZATION, atz); + request.headers().add(HeaderNames.AUTHORIZATION, atz); return chain.proceed(request); } } diff --git a/examples/security/webserver-signatures/src/main/java/io/helidon/examples/security/signatures/Service1.java b/examples/security/webserver-signatures/src/main/java/io/helidon/examples/security/signatures/Service1.java index 429dd65bc0d..ccb6bc8f11e 100644 --- a/examples/security/webserver-signatures/src/main/java/io/helidon/examples/security/signatures/Service1.java +++ b/examples/security/webserver-signatures/src/main/java/io/helidon/examples/security/signatures/Service1.java @@ -17,8 +17,8 @@ import io.helidon.common.LazyValue; import io.helidon.common.context.Contexts; -import io.helidon.http.Http; import io.helidon.http.HttpMediaTypes; +import io.helidon.http.Status; import io.helidon.security.SecurityContext; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; @@ -57,7 +57,7 @@ private void handle(ServerRequest req, ServerResponse res, String path) { .get(SecurityContext.class) .ifPresentOrElse(context -> { try (Http1ClientResponse clientRes = client.get().get(path).request()) { - if (clientRes.status() == Http.Status.OK_200) { + if (clientRes.status() == Status.OK_200) { res.send(clientRes.entity().as(String.class)); } else { res.send("Request failed, status: " + clientRes.status()); diff --git a/examples/todo-app/backend/src/test/java/io/helidon/examples/todos/backend/BackendTests.java b/examples/todo-app/backend/src/test/java/io/helidon/examples/todos/backend/BackendTests.java index 1ff2b1acc21..fbec45b7e8f 100644 --- a/examples/todo-app/backend/src/test/java/io/helidon/examples/todos/backend/BackendTests.java +++ b/examples/todo-app/backend/src/test/java/io/helidon/examples/todos/backend/BackendTests.java @@ -20,9 +20,9 @@ import java.util.Base64; import java.util.Properties; -import io.helidon.http.Http; import io.helidon.config.mp.MpConfigSources; import io.helidon.config.yaml.mp.YamlMpConfigSource; +import io.helidon.http.HeaderNames; import io.helidon.microprofile.tests.junit5.Configuration; import io.helidon.microprofile.tests.junit5.HelidonTest; @@ -113,7 +113,7 @@ void testTodoScenario() { JsonObject returnedTodo = webTarget .path("/api/backend") .request(MediaType.APPLICATION_JSON_TYPE) - .header(Http.HeaderNames.AUTHORIZATION.defaultCase(), basicAuth) + .header(HeaderNames.AUTHORIZATION.defaultCase(), basicAuth) .post(Entity.json(todo), JsonObject.class); assertThat(returnedTodo.getString("user"), is("john")); @@ -122,7 +122,7 @@ void testTodoScenario() { // Get the todo created earlier JsonObject fromServer = webTarget.path("/api/backend/" + returnedTodo.getString("id")) .request(MediaType.APPLICATION_JSON_TYPE) - .header(Http.HeaderNames.AUTHORIZATION.defaultCase(), basicAuth) + .header(HeaderNames.AUTHORIZATION.defaultCase(), basicAuth) .get(JsonObject.class); assertThat(fromServer, is(returnedTodo)); @@ -135,7 +135,7 @@ void testTodoScenario() { fromServer = webTarget.path("/api/backend/" + returnedTodo.getString("id")) .request(MediaType.APPLICATION_JSON_TYPE) - .header(Http.HeaderNames.AUTHORIZATION.defaultCase(), basicAuth) + .header(HeaderNames.AUTHORIZATION.defaultCase(), basicAuth) .put(Entity.json(updatedTodo), JsonObject.class); assertThat(fromServer.getString("title"), is(updatedTodo.getString("title"))); @@ -143,7 +143,7 @@ void testTodoScenario() { // Delete the todo created earlier fromServer = webTarget.path("/api/backend/" + returnedTodo.getString("id")) .request(MediaType.APPLICATION_JSON_TYPE) - .header(Http.HeaderNames.AUTHORIZATION.defaultCase(), basicAuth) + .header(HeaderNames.AUTHORIZATION.defaultCase(), basicAuth) .delete(JsonObject.class); assertThat(fromServer.getString("id"), is(returnedTodo.getString("id"))); @@ -151,7 +151,7 @@ void testTodoScenario() { // Get list of todos JsonArray jsonValues = webTarget.path("/api/backend") .request(MediaType.APPLICATION_JSON_TYPE) - .header(Http.HeaderNames.AUTHORIZATION.defaultCase(), basicAuth) + .header(HeaderNames.AUTHORIZATION.defaultCase(), basicAuth) .get(JsonArray.class); assertThat("There should be no todos on server", jsonValues.size(), is(0)); diff --git a/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/BackendServiceClient.java b/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/BackendServiceClient.java index 59564a3aba8..7225e5d689b 100644 --- a/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/BackendServiceClient.java +++ b/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/BackendServiceClient.java @@ -20,8 +20,8 @@ import java.util.function.Supplier; import io.helidon.common.LazyValue; -import io.helidon.http.Http.Status.Family; import io.helidon.http.HttpException; +import io.helidon.http.Status.Family; import io.helidon.http.media.jsonp.JsonpSupport; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; diff --git a/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/Main.java b/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/Main.java index 498f9970600..b69d0dd18fa 100644 --- a/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/Main.java +++ b/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/Main.java @@ -22,7 +22,8 @@ import io.helidon.config.Config; import io.helidon.config.ConfigValue; import io.helidon.config.FileSystemWatcher; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.logging.common.LogConfig; import io.helidon.security.Security; import io.helidon.tracing.Tracer; @@ -89,8 +90,8 @@ private static void setup(WebServerConfig.Builder server) { .addFeature(TracingFeature.create(tracer)) // redirect POST / to GET / .post("/", (req, res) -> { - res.header(Http.HeaderNames.LOCATION, "/"); - res.status(Http.Status.SEE_OTHER_303); + res.header(HeaderNames.LOCATION, "/"); + res.status(Status.SEE_OTHER_303); res.send(); }) // register static content support (on "/") diff --git a/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/TodoService.java b/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/TodoService.java index 699f1c83fcc..c8b3f732e01 100644 --- a/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/TodoService.java +++ b/examples/todo-app/frontend/src/main/java/io/helidon/examples/todos/frontend/TodoService.java @@ -15,7 +15,7 @@ */ package io.helidon.examples.todos.frontend; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.metrics.api.Counter; import io.helidon.metrics.api.Meter; import io.helidon.metrics.api.MeterRegistry; @@ -88,7 +88,7 @@ private Counter.Builder counterMetadata(String name, String description) { private void create(ServerRequest req, ServerResponse res) { JsonObject jsonObject = bsc.create(req.content().as(JsonObject.class)); createCounter.increment(); - res.status(Http.Status.CREATED_201); + res.status(Status.CREATED_201); res.send(jsonObject); } diff --git a/examples/todo-app/frontend/src/test/java/io/helidon/examples/todos/frontend/TodoServiceTest.java b/examples/todo-app/frontend/src/test/java/io/helidon/examples/todos/frontend/TodoServiceTest.java index 34fceddb27b..332e67f7e26 100644 --- a/examples/todo-app/frontend/src/test/java/io/helidon/examples/todos/frontend/TodoServiceTest.java +++ b/examples/todo-app/frontend/src/test/java/io/helidon/examples/todos/frontend/TodoServiceTest.java @@ -19,21 +19,23 @@ import java.net.URI; import java.util.Base64; -import io.helidon.http.Http; import io.helidon.config.Config; -import io.helidon.http.Http.Header; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.http.media.jsonp.JsonpSupport; -import io.helidon.webclient.security.WebClientSecurity; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.security.Security; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webclient.security.WebClientSecurity; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.context.ContextFeature; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; -import io.helidon.security.Security; import io.helidon.webserver.security.SecurityFeature; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import io.helidon.webserver.testing.junit5.Socket; import jakarta.json.Json; @@ -51,7 +53,7 @@ class TodoServiceTest { private static final JsonObject TODO = Json.createObjectBuilder().add("msg", "todo").build(); private static final String ENCODED_ID = Base64.getEncoder().encodeToString("john:password".getBytes()); - private static final Header BASIC_AUTH = Http.Headers.create(Http.HeaderNames.AUTHORIZATION, "Basic " + ENCODED_ID); + private static final Header BASIC_AUTH = HeaderValues.create(HeaderNames.AUTHORIZATION, "Basic " + ENCODED_ID); private static URI backendUri; private final Http1Client client; @@ -101,7 +103,7 @@ static void setup(WebServerConfig.Builder server) { @Test void testList() { try (Http1ClientResponse response = client.get().request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(JsonArray.class).getJsonObject(0), is(TODO)); } } @@ -109,7 +111,7 @@ void testList() { @Test void testCreate() { try (Http1ClientResponse response = client.post().submit(TODO)) { - assertThat(response.status(), is(Http.Status.CREATED_201)); + assertThat(response.status(), is(Status.CREATED_201)); assertThat(response.as(JsonObject.class), is(TODO)); } } @@ -117,7 +119,7 @@ void testCreate() { @Test void testGet() { try (Http1ClientResponse response = client.get("1").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(JsonObject.class), is(TODO)); } } @@ -125,7 +127,7 @@ void testGet() { @Test void testDelete() { try (Http1ClientResponse response = client.delete("1").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(JsonObject.class), is(TODO)); } } @@ -133,7 +135,7 @@ void testDelete() { @Test void testUpdate() { try (Http1ClientResponse response = client.put("1").submit(TODO)) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(JsonObject.class), is(TODO)); } } diff --git a/examples/translator-app/frontend/src/main/java/io/helidon/examples/translator/frontend/TranslatorFrontendService.java b/examples/translator-app/frontend/src/main/java/io/helidon/examples/translator/frontend/TranslatorFrontendService.java index fec518b5681..0569de9a905 100644 --- a/examples/translator-app/frontend/src/main/java/io/helidon/examples/translator/frontend/TranslatorFrontendService.java +++ b/examples/translator-app/frontend/src/main/java/io/helidon/examples/translator/frontend/TranslatorFrontendService.java @@ -19,7 +19,7 @@ import java.util.logging.Logger; import io.helidon.http.BadRequestException; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRules; @@ -68,7 +68,7 @@ private void getText(ServerRequest re, ServerResponse res) { .request()) { final String result; - if (clientRes.status().family() == Http.Status.Family.SUCCESSFUL) { + if (clientRes.status().family() == Status.Family.SUCCESSFUL) { result = clientRes.entity().as(String.class); } else { result = "Error: " + clientRes.entity().as(String.class); diff --git a/examples/webclient/standalone/src/main/java/io/helidon/examples/webclient/standalone/ClientMain.java b/examples/webclient/standalone/src/main/java/io/helidon/examples/webclient/standalone/ClientMain.java index e833e4451ea..d20343c05f1 100644 --- a/examples/webclient/standalone/src/main/java/io/helidon/examples/webclient/standalone/ClientMain.java +++ b/examples/webclient/standalone/src/main/java/io/helidon/examples/webclient/standalone/ClientMain.java @@ -24,7 +24,8 @@ import io.helidon.config.Config; import io.helidon.config.ConfigValue; -import io.helidon.http.Http; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.metrics.api.Counter; import io.helidon.metrics.api.MeterRegistry; import io.helidon.metrics.api.Metrics; @@ -93,7 +94,7 @@ public static void main(String[] args) { clientMetricsExample(url, config); } - static Http.Status performPutMethod(WebClient client) { + static Status performPutMethod(WebClient client) { System.out.println("Put request execution."); try (HttpClientResponse response = client.put("/greeting").submit(JSON_NEW_GREETING)) { System.out.println("PUT request executed with status: " + response.status()); @@ -112,7 +113,7 @@ static String performGetMethod(WebClient client) { static String followRedirects(WebClient client) { System.out.println("Following request redirection."); try (HttpClientResponse response = client.get("/redirect").request()) { - if (response.status() != Http.Status.OK_200) { + if (response.status() != Status.OK_200) { throw new IllegalStateException("Follow redirection failed!"); } String result = response.as(String.class); @@ -154,7 +155,7 @@ static String clientMetricsExample(String url, Config config) { //Creates new metric which will count all GET requests and has format of example.metric.GET. WebClientService clientService = WebClientMetrics.counter() - .methods(Http.Method.GET) + .methods(Method.GET) .nameFormat("example.metric.%1$s.%2$s") .build(); diff --git a/examples/webclient/standalone/src/main/java/io/helidon/examples/webclient/standalone/GreetService.java b/examples/webclient/standalone/src/main/java/io/helidon/examples/webclient/standalone/GreetService.java index 2f34f46d88d..920eb83e72a 100644 --- a/examples/webclient/standalone/src/main/java/io/helidon/examples/webclient/standalone/GreetService.java +++ b/examples/webclient/standalone/src/main/java/io/helidon/examples/webclient/standalone/GreetService.java @@ -19,7 +19,8 @@ import java.util.concurrent.atomic.AtomicReference; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; @@ -83,7 +84,7 @@ private void getDefaultMessageHandler(ServerRequest request, } /** - * Return a status code of {@link Http.Status#MOVED_PERMANENTLY_301} and the new location where should + * Return a status code of {@link io.helidon.http.Status#MOVED_PERMANENTLY_301} and the new location where should * client redirect. * * @param request the server request @@ -92,8 +93,8 @@ private void getDefaultMessageHandler(ServerRequest request, private void redirect(ServerRequest request, ServerResponse response) { int port = request.context().get(WebServer.class).orElseThrow().port(); - response.headers().add(Http.HeaderNames.LOCATION, "http://localhost:" + port + "/greet/"); - response.status(Http.Status.MOVED_PERMANENTLY_301).send(); + response.headers().add(HeaderNames.LOCATION, "http://localhost:" + port + "/greet/"); + response.status(Status.MOVED_PERMANENTLY_301).send(); } /** @@ -135,12 +136,12 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } } diff --git a/examples/webserver/basics/src/main/java/io/helidon/examples/webserver/basics/Main.java b/examples/webserver/basics/src/main/java/io/helidon/examples/webserver/basics/Main.java index 945ed6024bb..61952a1568b 100644 --- a/examples/webserver/basics/src/main/java/io/helidon/examples/webserver/basics/Main.java +++ b/examples/webserver/basics/src/main/java/io/helidon/examples/webserver/basics/Main.java @@ -26,9 +26,11 @@ import java.util.List; import io.helidon.common.media.type.MediaTypes; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.http.HttpException; import io.helidon.http.ServerRequestHeaders; +import io.helidon.http.Status; import io.helidon.http.media.EntityReader; import io.helidon.http.media.MediaContext; import io.helidon.http.media.MediaContextConfig; @@ -62,8 +64,8 @@ public class Main { private static final JsonBuilderFactory JSON = Json.createBuilderFactory(Collections.emptyMap()); - private static final Http.HeaderName BAR_HEADER = Http.HeaderNames.create("bar"); - private static final Http.HeaderName FOO_HEADER = Http.HeaderNames.create("foo"); + private static final HeaderName BAR_HEADER = HeaderNames.create("bar"); + private static final HeaderName FOO_HEADER = HeaderNames.create("foo"); // ---------------- EXAMPLES @@ -78,9 +80,9 @@ public class Main { * @param routing routing builder */ public static void firstRouting(HttpRouting.Builder routing) { - routing.post("/firstRouting/post-endpoint", (req, res) -> res.status(Http.Status.CREATED_201) + routing.post("/firstRouting/post-endpoint", (req, res) -> res.status(Status.CREATED_201) .send()) - .get("/firstRouting/get-endpoint", (req, res) -> res.status(Http.Status.OK_200) + .get("/firstRouting/get-endpoint", (req, res) -> res.status(Status.OK_200) .send("Hello World!")); } @@ -110,9 +112,9 @@ public static void routingAsFilter(HttpRouting.Builder routing) { // Filters are just routing handlers which calls next() res.next(); }) - .post("/routingAsFilter/post-endpoint", (req, res) -> res.status(Http.Status.CREATED_201) + .post("/routingAsFilter/post-endpoint", (req, res) -> res.status(Status.CREATED_201) .send()) - .get("/routingAsFilter/get-endpoint", (req, res) -> res.status(Http.Status.OK_200) + .get("/routingAsFilter/get-endpoint", (req, res) -> res.status(Status.OK_200) .send("Hello World!")); } @@ -201,7 +203,7 @@ public static void readContentEntity(HttpRouting.Builder routing) { System.out.println("/foo DATA: " + data); res.send(data); } catch (Throwable th) { - res.status(Http.Status.BAD_REQUEST_400); + res.status(Status.BAD_REQUEST_400); } }) // It is possible to use Handler.of() method to automatically cover all error states. @@ -220,7 +222,7 @@ public static void readContentEntity(HttpRouting.Builder routing) { public static void mediaReader(HttpRouting.Builder routing, MediaContextConfig.Builder mediaContext) { routing.post("/mediaReader/create-record", Handler.create(Name.class, (name, res) -> { System.out.println("Name: " + name); - res.status(Http.Status.CREATED_201) + res.status(Status.CREATED_201) .send(name.toString()); })); @@ -267,9 +269,9 @@ public static void errorHandling(HttpRouting.Builder routing) { res.next(); }) .error(NumberFormatException.class, - (req, res, ex) -> res.status(Http.Status.BAD_REQUEST_400).send()) + (req, res, ex) -> res.status(Status.BAD_REQUEST_400).send()) .error(ArithmeticException.class, - (req, res, ex) -> res.status(Http.Status.PRECONDITION_FAILED_412).send()); + (req, res, ex) -> res.status(Status.PRECONDITION_FAILED_412).send()); } diff --git a/examples/webserver/basics/src/test/java/io/helidon/examples/webserver/basics/MainTest.java b/examples/webserver/basics/src/test/java/io/helidon/examples/webserver/basics/MainTest.java index 36c0a97aba4..d33ab90160a 100644 --- a/examples/webserver/basics/src/test/java/io/helidon/examples/webserver/basics/MainTest.java +++ b/examples/webserver/basics/src/test/java/io/helidon/examples/webserver/basics/MainTest.java @@ -16,23 +16,24 @@ package io.helidon.examples.webserver.basics; -import io.helidon.http.Http; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.http.media.MediaContext; import io.helidon.http.media.MediaContextConfig; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Status.BAD_REQUEST_400; -import static io.helidon.http.Http.Status.CREATED_201; -import static io.helidon.http.Http.Status.INTERNAL_SERVER_ERROR_500; -import static io.helidon.http.Http.Status.OK_200; -import static io.helidon.http.Http.Status.PRECONDITION_FAILED_412; +import static io.helidon.http.Status.BAD_REQUEST_400; +import static io.helidon.http.Status.CREATED_201; +import static io.helidon.http.Status.INTERNAL_SERVER_ERROR_500; +import static io.helidon.http.Status.OK_200; +import static io.helidon.http.Status.PRECONDITION_FAILED_412; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -40,7 +41,7 @@ @ServerTest public class MainTest { - private static final Http.HeaderName FOO_HEADER = Http.HeaderNames.create("foo"); + private static final HeaderName FOO_HEADER = HeaderNames.create("foo"); private final Http1Client client; @@ -157,7 +158,7 @@ public void supports() { // Static content try (Http1ClientResponse response = client.get("/supports/index.html").request()) { assertThat(response.status(), is(OK_200)); - assertThat(response.headers().first(Http.HeaderNames.CONTENT_TYPE).orElse(null), is(MediaTypes.TEXT_HTML.text())); + assertThat(response.headers().first(HeaderNames.CONTENT_TYPE).orElse(null), is(MediaTypes.TEXT_HTML.text())); } // JSON diff --git a/examples/webserver/comment-aas/src/main/java/io/helidon/examples/webserver/comments/Main.java b/examples/webserver/comment-aas/src/main/java/io/helidon/examples/webserver/comments/Main.java index 0e9f37b9652..ce5f90d0509 100644 --- a/examples/webserver/comment-aas/src/main/java/io/helidon/examples/webserver/comments/Main.java +++ b/examples/webserver/comment-aas/src/main/java/io/helidon/examples/webserver/comments/Main.java @@ -19,9 +19,10 @@ import java.util.Optional; import io.helidon.config.Config; -import io.helidon.http.Http; -import io.helidon.http.Http.Status; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.http.HttpException; +import io.helidon.http.Status; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRouting; @@ -36,7 +37,7 @@ */ public final class Main { - static final Http.HeaderName USER_IDENTITY_HEADER = Http.HeaderNames.create("user-identity"); + static final HeaderName USER_IDENTITY_HEADER = HeaderNames.create("user-identity"); private Main() { } diff --git a/examples/webserver/comment-aas/src/test/java/io/helidon/examples/webserver/comments/CommentsServiceTest.java b/examples/webserver/comment-aas/src/test/java/io/helidon/examples/webserver/comments/CommentsServiceTest.java index 11e0c1ab707..17d7e0b61ff 100644 --- a/examples/webserver/comment-aas/src/test/java/io/helidon/examples/webserver/comments/CommentsServiceTest.java +++ b/examples/webserver/comment-aas/src/test/java/io/helidon/examples/webserver/comments/CommentsServiceTest.java @@ -16,13 +16,13 @@ package io.helidon.examples.webserver.comments; -import io.helidon.http.Http; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.Status; +import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.testing.junit5.DirectClient; import io.helidon.webserver.testing.junit5.RoutingTest; import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webclient.http1.Http1ClientResponse; -import io.helidon.webserver.http.HttpRouting; import org.junit.jupiter.api.Test; @@ -70,17 +70,17 @@ public void addAndGetComments() { @Test public void testRouting() { try (Http1ClientResponse response = client.get("/comments/one").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } try (Http1ClientResponse response = client.post("/comments/one") .contentType(MediaTypes.TEXT_PLAIN) .submit("aaa")) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } try (Http1ClientResponse response = client.get("/comments/one").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity().as(String.class), is("anonymous: aaa")); } } diff --git a/examples/webserver/comment-aas/src/test/java/io/helidon/examples/webserver/comments/MainTest.java b/examples/webserver/comment-aas/src/test/java/io/helidon/examples/webserver/comments/MainTest.java index 3a257b0b421..06f8c043a63 100644 --- a/examples/webserver/comment-aas/src/test/java/io/helidon/examples/webserver/comments/MainTest.java +++ b/examples/webserver/comment-aas/src/test/java/io/helidon/examples/webserver/comments/MainTest.java @@ -16,13 +16,13 @@ package io.helidon.examples.webserver.comments; -import io.helidon.http.Http; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.Status; +import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.testing.junit5.DirectClient; import io.helidon.webserver.testing.junit5.RoutingTest; import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webclient.http1.Http1ClientResponse; -import io.helidon.webserver.http.HttpRouting; import org.junit.jupiter.api.Test; @@ -53,14 +53,14 @@ public void argot() { .contentType(MediaTypes.TEXT_PLAIN) .submit("Spring framework is the BEST!")) { - assertThat(response.status(), is(Http.Status.NOT_ACCEPTABLE_406)); + assertThat(response.status(), is(Status.NOT_ACCEPTABLE_406)); } } @Test public void anonymousDisabled() { try (Http1ClientResponse response = client.get("/comment/one").request()) { - assertThat(response.status(), is(Http.Status.FORBIDDEN_403)); + assertThat(response.status(), is(Status.FORBIDDEN_403)); } } } diff --git a/examples/webserver/echo/src/main/java/io/helidon/examples/webserver/echo/EchoClient.java b/examples/webserver/echo/src/main/java/io/helidon/examples/webserver/echo/EchoClient.java index f5bbaf167bc..933fa093bfb 100644 --- a/examples/webserver/echo/src/main/java/io/helidon/examples/webserver/echo/EchoClient.java +++ b/examples/webserver/echo/src/main/java/io/helidon/examples/webserver/echo/EchoClient.java @@ -16,9 +16,9 @@ package io.helidon.examples.webserver.echo; +import io.helidon.http.Header; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; import io.helidon.webclient.api.HttpClientRequest; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.WebClient; @@ -27,8 +27,8 @@ * A client that invokes the echo server. */ public class EchoClient { - private static final Http.Header HEADER = Http.Headers.create("MY-HEADER", "header-value"); - private static final Header HEADERS = Http.Headers.create("MY-HEADERS", "ha", "hb", "hc"); + private static final Header HEADER = HeaderValues.create("MY-HEADER", "header-value"); + private static final Header HEADERS = HeaderValues.create("MY-HEADERS", "ha", "hb", "hc"); private EchoClient() { } @@ -52,7 +52,7 @@ public static void main(String[] args) { .request()) { Headers headers = response.headers(); - for (Http.Header header : headers) { + for (Header header : headers) { System.out.println("Header: " + header.name() + "=" + header.value()); } System.out.println("Entity:"); diff --git a/examples/webserver/echo/src/main/java/io/helidon/examples/webserver/echo/EchoMain.java b/examples/webserver/echo/src/main/java/io/helidon/examples/webserver/echo/EchoMain.java index 0ce75a3a999..22d05c872cc 100644 --- a/examples/webserver/echo/src/main/java/io/helidon/examples/webserver/echo/EchoMain.java +++ b/examples/webserver/echo/src/main/java/io/helidon/examples/webserver/echo/EchoMain.java @@ -22,9 +22,10 @@ import io.helidon.common.parameters.Parameters; import io.helidon.common.uri.UriQuery; +import io.helidon.http.Header; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.RoutedPath; +import io.helidon.http.Status; import io.helidon.logging.common.LogConfig; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.ServerRequest; @@ -76,7 +77,7 @@ private static void echo(ServerRequest req, ServerResponse res) { res.header("R-QUERY_" + queryName, query.all(queryName).toString()); } - for (Http.Header header : headers) { + for (Header header : headers) { res.header("R-" + header.name(), header.allValues().toString()); } @@ -84,7 +85,7 @@ private static void echo(ServerRequest req, ServerResponse res) { OutputStream outputStream = res.outputStream()) { inputStream.transferTo(outputStream); } catch (Exception e) { - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send("failed: " + e.getMessage()); + res.status(Status.INTERNAL_SERVER_ERROR_500).send("failed: " + e.getMessage()); } } } diff --git a/examples/webserver/fault-tolerance/src/main/java/io/helidon/examples/webserver/faulttolerance/Main.java b/examples/webserver/fault-tolerance/src/main/java/io/helidon/examples/webserver/faulttolerance/Main.java index 19a46c4ecf8..c2e15421a55 100644 --- a/examples/webserver/fault-tolerance/src/main/java/io/helidon/examples/webserver/faulttolerance/Main.java +++ b/examples/webserver/fault-tolerance/src/main/java/io/helidon/examples/webserver/faulttolerance/Main.java @@ -19,7 +19,7 @@ import io.helidon.faulttolerance.BulkheadException; import io.helidon.faulttolerance.CircuitBreakerOpenException; import io.helidon.faulttolerance.TimeoutException; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.logging.common.LogConfig; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; @@ -55,13 +55,13 @@ static void setup(WebServerConfig.Builder server) { static void routing(HttpRouting.Builder routing) { routing.register("/ft", new FtService()) .error(BulkheadException.class, - (req, res, ex) -> res.status(Http.Status.SERVICE_UNAVAILABLE_503).send("bulkhead")) + (req, res, ex) -> res.status(Status.SERVICE_UNAVAILABLE_503).send("bulkhead")) .error(CircuitBreakerOpenException.class, - (req, res, ex) -> res.status(Http.Status.SERVICE_UNAVAILABLE_503).send("circuit breaker")) + (req, res, ex) -> res.status(Status.SERVICE_UNAVAILABLE_503).send("circuit breaker")) .error(TimeoutException.class, - (req, res, ex) -> res.status(Http.Status.REQUEST_TIMEOUT_408).send("timeout")) + (req, res, ex) -> res.status(Status.REQUEST_TIMEOUT_408).send("timeout")) .error(Throwable.class, - (req, res, ex) -> res.status(Http.Status.INTERNAL_SERVER_ERROR_500) + (req, res, ex) -> res.status(Status.INTERNAL_SERVER_ERROR_500) .send(ex.getClass().getName() + ": " + ex.getMessage())); } } diff --git a/examples/webserver/fault-tolerance/src/test/java/io/helidon/examples/webserver/faulttolerance/MainTest.java b/examples/webserver/fault-tolerance/src/test/java/io/helidon/examples/webserver/faulttolerance/MainTest.java index 25d96fe620b..5cbc14f71fe 100644 --- a/examples/webserver/fault-tolerance/src/test/java/io/helidon/examples/webserver/faulttolerance/MainTest.java +++ b/examples/webserver/fault-tolerance/src/test/java/io/helidon/examples/webserver/faulttolerance/MainTest.java @@ -19,12 +19,12 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import io.helidon.http.Http; +import io.helidon.http.Status; +import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.testing.junit5.DirectClient; import io.helidon.webserver.testing.junit5.RoutingTest; import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webclient.http1.Http1ClientResponse; -import io.helidon.webserver.http.HttpRouting; import org.junit.jupiter.api.Test; @@ -66,7 +66,7 @@ void testBulkhead() throws InterruptedException { try (Http1ClientResponse response = client.get("/ft/bulkhead/10000").request()) { // registered an error handler in Main - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); assertThat(response.as(String.class), is("bulkhead")); } finally { executor.close(); @@ -93,7 +93,7 @@ void testCircuitBreaker() { try (Http1ClientResponse response = client.get("/ft/circuitBreaker/true").request()) { // registered an error handler in Main - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); assertThat(response.as(String.class), is("circuit breaker")); } } @@ -125,7 +125,7 @@ void testRetry() { try (Http1ClientResponse response = client.get("/ft/retry/4").request()) { // no error handler specified - assertThat(response.status(), is(Http.Status.INTERNAL_SERVER_ERROR_500)); + assertThat(response.status(), is(Status.INTERNAL_SERVER_ERROR_500)); assertThat(response.as(String.class), is("java.lang.RuntimeException: failure")); } } @@ -138,7 +138,7 @@ void testTimeout() { try (Http1ClientResponse response = client.get("/ft/timeout/1000").request()) { // error handler specified in Main - assertThat(response.status(), is(Http.Status.REQUEST_TIMEOUT_408)); + assertThat(response.status(), is(Status.REQUEST_TIMEOUT_408)); assertThat(response.as(String.class), is("timeout")); } } diff --git a/examples/webserver/imperative/src/main/java/io/helidon/examples/webserver/imperative/ImperativeMain.java b/examples/webserver/imperative/src/main/java/io/helidon/examples/webserver/imperative/ImperativeMain.java index 55c06a7f555..4960de5f347 100644 --- a/examples/webserver/imperative/src/main/java/io/helidon/examples/webserver/imperative/ImperativeMain.java +++ b/examples/webserver/imperative/src/main/java/io/helidon/examples/webserver/imperative/ImperativeMain.java @@ -18,7 +18,7 @@ import io.helidon.common.config.Config; import io.helidon.common.config.GlobalConfig; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.HttpRouting; @@ -45,7 +45,7 @@ public static void main(String[] args) { } private static void routing(HttpRouting.Builder routing) { - Http.Method list = Http.Method.create("LIST"); + Method list = Method.create("LIST"); routing.get("/", (req, res) -> res.send("Hello World!")) .route(list, "/", (req, res) -> res.send("lll")) diff --git a/examples/webserver/multiport/src/test/java/io/helidon/webserver/examples/multiport/MainTest.java b/examples/webserver/multiport/src/test/java/io/helidon/webserver/examples/multiport/MainTest.java index 45a6423b2e5..ba396191513 100644 --- a/examples/webserver/multiport/src/test/java/io/helidon/webserver/examples/multiport/MainTest.java +++ b/examples/webserver/multiport/src/test/java/io/helidon/webserver/examples/multiport/MainTest.java @@ -18,15 +18,15 @@ import java.util.stream.Stream; -import io.helidon.http.Http; import io.helidon.config.Config; import io.helidon.config.ConfigSources; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; @@ -72,20 +72,20 @@ static Stream initParams() { final String METRICS_PATH = "/health"; return Stream.of( - new Params(Socket.PUBLIC, PUBLIC_PATH, Http.Status.OK_200), - new Params(Socket.PUBLIC, PRIVATE_PATH, Http.Status.NOT_FOUND_404), - new Params(Socket.PUBLIC, HEALTH_PATH, Http.Status.NOT_FOUND_404), - new Params(Socket.PUBLIC, METRICS_PATH, Http.Status.NOT_FOUND_404), - - new Params(Socket.PRIVATE, PUBLIC_PATH, Http.Status.NOT_FOUND_404), - new Params(Socket.PRIVATE, PRIVATE_PATH, Http.Status.OK_200), - new Params(Socket.PRIVATE, HEALTH_PATH, Http.Status.NOT_FOUND_404), - new Params(Socket.PRIVATE, METRICS_PATH, Http.Status.NOT_FOUND_404), - - new Params(Socket.ADMIN, PUBLIC_PATH, Http.Status.NOT_FOUND_404), - new Params(Socket.ADMIN, PRIVATE_PATH, Http.Status.NOT_FOUND_404), - new Params(Socket.ADMIN, HEALTH_PATH, Http.Status.OK_200), - new Params(Socket.ADMIN, METRICS_PATH, Http.Status.OK_200)); + new Params(Socket.PUBLIC, PUBLIC_PATH, Status.OK_200), + new Params(Socket.PUBLIC, PRIVATE_PATH, Status.NOT_FOUND_404), + new Params(Socket.PUBLIC, HEALTH_PATH, Status.NOT_FOUND_404), + new Params(Socket.PUBLIC, METRICS_PATH, Status.NOT_FOUND_404), + + new Params(Socket.PRIVATE, PUBLIC_PATH, Status.NOT_FOUND_404), + new Params(Socket.PRIVATE, PRIVATE_PATH, Status.OK_200), + new Params(Socket.PRIVATE, HEALTH_PATH, Status.NOT_FOUND_404), + new Params(Socket.PRIVATE, METRICS_PATH, Status.NOT_FOUND_404), + + new Params(Socket.ADMIN, PUBLIC_PATH, Status.NOT_FOUND_404), + new Params(Socket.ADMIN, PRIVATE_PATH, Status.NOT_FOUND_404), + new Params(Socket.ADMIN, HEALTH_PATH, Status.OK_200), + new Params(Socket.ADMIN, METRICS_PATH, Status.OK_200)); } @MethodSource("initParams") @@ -116,7 +116,7 @@ public void portTest() { } } - private record Params(Socket socket, String path, Http.Status httpStatus) { + private record Params(Socket socket, String path, Status httpStatus) { @Override public String toString() { diff --git a/examples/webserver/mutual-tls/src/main/java/io/helidon/examples/webserver/mtls/SecureService.java b/examples/webserver/mutual-tls/src/main/java/io/helidon/examples/webserver/mtls/SecureService.java index 232186f6ba8..c9d3ad33538 100644 --- a/examples/webserver/mutual-tls/src/main/java/io/helidon/examples/webserver/mtls/SecureService.java +++ b/examples/webserver/mutual-tls/src/main/java/io/helidon/examples/webserver/mtls/SecureService.java @@ -15,18 +15,18 @@ */ package io.helidon.examples.webserver.mtls; -import io.helidon.http.Http; +import io.helidon.http.HeaderValues; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; -import static io.helidon.http.Http.HeaderNames.X_HELIDON_CN; +import static io.helidon.http.HeaderNames.X_HELIDON_CN; class SecureService implements HttpService { @Override public void routing(HttpRules rules) { rules.any((req, res) -> { // close to avoid re-using cached connections on the client side - res.header(Http.Headers.CONNECTION_CLOSE); + res.header(HeaderValues.CONNECTION_CLOSE); res.send("Hello " + req.headers().get(X_HELIDON_CN).value() + "!"); }); } diff --git a/examples/webserver/observe/src/test/java/io/helidon/examples/webserver/observe/AbstractObserveTest.java b/examples/webserver/observe/src/test/java/io/helidon/examples/webserver/observe/AbstractObserveTest.java index cf4ec63efbe..e909677e8ea 100644 --- a/examples/webserver/observe/src/test/java/io/helidon/examples/webserver/observe/AbstractObserveTest.java +++ b/examples/webserver/observe/src/test/java/io/helidon/examples/webserver/observe/AbstractObserveTest.java @@ -16,12 +16,12 @@ package io.helidon.examples.webserver.observe; -import io.helidon.http.Http; import io.helidon.config.Config; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -55,21 +55,21 @@ void testRootRoute() { void testConfigObserver() { try (Http1ClientResponse response = client.get("/observe/config/profile").request()) { // this requires basic authentication - assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); + assertThat(response.status(), is(Status.UNAUTHORIZED_401)); } } @Test void testHealthObserver() { try (Http1ClientResponse response = client.get("/observe/health").request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); } } @Test void testInfoObserver() { try (Http1ClientResponse response = client.get("/observe/info").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } } } diff --git a/examples/webserver/protocols/src/main/java/io/helidon/examples/webserver/protocols/ProtocolsMain.java b/examples/webserver/protocols/src/main/java/io/helidon/examples/webserver/protocols/ProtocolsMain.java index b04a3c6f83e..15d2e576aef 100644 --- a/examples/webserver/protocols/src/main/java/io/helidon/examples/webserver/protocols/ProtocolsMain.java +++ b/examples/webserver/protocols/src/main/java/io/helidon/examples/webserver/protocols/ProtocolsMain.java @@ -34,7 +34,7 @@ import io.grpc.stub.StreamObserver; -import static io.helidon.http.Http.Method.GET; +import static io.helidon.http.Method.GET; import static io.helidon.webserver.grpc.ResponseHelper.complete; /** diff --git a/examples/webserver/static-content/src/main/java/io/helidon/examples/webserver/staticcontent/Main.java b/examples/webserver/static-content/src/main/java/io/helidon/examples/webserver/staticcontent/Main.java index 8a7a66b0795..a3ba615d460 100644 --- a/examples/webserver/static-content/src/main/java/io/helidon/examples/webserver/staticcontent/Main.java +++ b/examples/webserver/static-content/src/main/java/io/helidon/examples/webserver/staticcontent/Main.java @@ -16,7 +16,10 @@ package io.helidon.examples.webserver.staticcontent; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.logging.common.LogConfig; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.HttpRouting; @@ -26,7 +29,7 @@ * The application main class. */ public final class Main { - private static final Http.Header UI_REDIRECT = Http.Headers.createCached(Http.HeaderNames.LOCATION, "/ui"); + private static final Header UI_REDIRECT = HeaderValues.createCached(HeaderNames.LOCATION, "/ui"); /** * Cannot be instantiated. @@ -58,7 +61,7 @@ public static void main(String[] args) { static void routing(HttpRouting.Builder routing) { routing.any("/", (req, res) -> { // showing the capability to run on any path, and redirecting from root - res.status(Http.Status.MOVED_PERMANENTLY_301); + res.status(Status.MOVED_PERMANENTLY_301); res.headers().set(UI_REDIRECT); res.send(); }) diff --git a/examples/webserver/static-content/src/test/java/io/helidon/examples/webserver/staticcontent/MainTest.java b/examples/webserver/static-content/src/test/java/io/helidon/examples/webserver/staticcontent/MainTest.java index 1157d9d4e16..d6e3ccce170 100644 --- a/examples/webserver/static-content/src/test/java/io/helidon/examples/webserver/staticcontent/MainTest.java +++ b/examples/webserver/static-content/src/test/java/io/helidon/examples/webserver/staticcontent/MainTest.java @@ -16,12 +16,13 @@ package io.helidon.examples.webserver.staticcontent; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; + import jakarta.json.JsonNumber; import jakarta.json.JsonObject; import org.junit.jupiter.api.Test; @@ -47,15 +48,15 @@ static void routing(HttpRouting.Builder builder) { void testUi() { assertThat(allCounter(), is(1)); try (Http1ClientResponse response = client.get("/ui/index.html").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers().contentType().orElseThrow().text(), is("text/html")); } try (Http1ClientResponse response = client.get("/ui/css/app.css").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers().contentType().orElseThrow().text(), is("text/css")); } try (Http1ClientResponse response = client.get("/ui/js/app.js").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers().contentType().orElseThrow().text(), is("text/javascript")); } assertThat(allCounter(), is(5)); // includes /ui/api/counter calls @@ -63,7 +64,7 @@ void testUi() { private int allCounter() { try (Http1ClientResponse response = client.get("/ui/api/counter").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonNumber number = (JsonNumber) response.as(JsonObject.class).get("all"); return number.intValue(); } diff --git a/examples/webserver/tracing/src/main/java/io/helidon/examples/webserver/tracing/TracingMain.java b/examples/webserver/tracing/src/main/java/io/helidon/examples/webserver/tracing/TracingMain.java index 51e2c51bfb0..aeb8d40d4cc 100644 --- a/examples/webserver/tracing/src/main/java/io/helidon/examples/webserver/tracing/TracingMain.java +++ b/examples/webserver/tracing/src/main/java/io/helidon/examples/webserver/tracing/TracingMain.java @@ -30,7 +30,7 @@ import io.helidon.webserver.http2.Http2Route; import io.helidon.webserver.tracing.TracingFeature; -import static io.helidon.http.Http.Method.GET; +import static io.helidon.http.Method.GET; /** * Tracing example. diff --git a/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/CommentServiceTest.java b/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/CommentServiceTest.java index d483c19319b..93d55859e20 100644 --- a/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/CommentServiceTest.java +++ b/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/CommentServiceTest.java @@ -16,13 +16,13 @@ package io.helidon.examples.webserver.tutorial; -import io.helidon.http.Http; import io.helidon.common.media.type.MediaTypes; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -67,18 +67,18 @@ void addAndGetComments() { @Test void testRouting() { try (Http1ClientResponse response = client.get("/article/one").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } // Add first comment try (Http1ClientResponse response = client.post("/article/one") .contentType(MediaTypes.TEXT_PLAIN) .submit("aaa")) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } try (Http1ClientResponse response = client.get("/article/one").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity().as(String.class), is("anonymous: aaa")); } @@ -87,11 +87,11 @@ void testRouting() { try (Http1ClientResponse response = client.post("/article/one") .contentType(MediaTypes.TEXT_PLAIN) .submit("bbb")) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } try (Http1ClientResponse response = client.get("/article/one").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity().as(String.class), is("anonymous: aaa\nanonymous: bbb")); } } diff --git a/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/MainTest.java b/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/MainTest.java index 7f8fc555e1b..d084d131598 100644 --- a/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/MainTest.java +++ b/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/MainTest.java @@ -16,7 +16,7 @@ package io.helidon.examples.webserver.tutorial; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServer; @@ -52,7 +52,7 @@ static void setup(WebServerConfig.Builder server) { @Test public void testShutDown() throws InterruptedException { try (Http1ClientResponse response = client.post("/mgmt/shutdown").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } // there may be some delay between the request being completed, and the server shutting down // let's give it a second to shut down, then fail diff --git a/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/UserFilterTest.java b/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/UserFilterTest.java index 6722ec98648..95be71d314b 100644 --- a/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/UserFilterTest.java +++ b/examples/webserver/tutorial/src/test/java/io/helidon/examples/webserver/tutorial/UserFilterTest.java @@ -16,12 +16,12 @@ package io.helidon.examples.webserver.tutorial; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.testing.junit5.DirectClient; import io.helidon.webserver.testing.junit5.RoutingTest; import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webclient.http1.Http1ClientResponse; -import io.helidon.webserver.http.HttpRouting; import org.junit.jupiter.api.Test; @@ -56,7 +56,7 @@ public void filter() { } try (Http1ClientResponse response = client.get() - .header(Http.HeaderNames.COOKIE, "Unauthenticated-User-Alias=Foo") + .header(HeaderNames.COOKIE, "Unauthenticated-User-Alias=Foo") .request()) { assertThat(response.entity().as(String.class), is("Foo")); } diff --git a/examples/webserver/websocket/src/test/java/io/helidon/examples/webserver/websocket/MessageBoardTest.java b/examples/webserver/websocket/src/test/java/io/helidon/examples/webserver/websocket/MessageBoardTest.java index 28531a01b9f..9cb3a7f1642 100644 --- a/examples/webserver/websocket/src/test/java/io/helidon/examples/webserver/websocket/MessageBoardTest.java +++ b/examples/webserver/websocket/src/test/java/io/helidon/examples/webserver/websocket/MessageBoardTest.java @@ -20,16 +20,16 @@ import java.util.concurrent.TimeUnit; import java.util.logging.Logger; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webclient.websocket.WsClient; import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import io.helidon.websocket.WsCloseCodes; import io.helidon.websocket.WsListener; import io.helidon.websocket.WsSession; -import io.helidon.webclient.websocket.WsClient; import org.junit.jupiter.api.Test; @@ -62,7 +62,7 @@ public void testBoard() throws InterruptedException { // Post messages using REST resource for (String message : MESSAGES) { try (Http1ClientResponse response = client.post("/rest/board").submit(message)) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); LOGGER.info("Posting message '" + message + "'"); } } diff --git a/http/encoding/deflate/src/main/java/io/helidon/http/encoding/deflate/DeflateEncoding.java b/http/encoding/deflate/src/main/java/io/helidon/http/encoding/deflate/DeflateEncoding.java index c4bc9861eda..a4c0defa09f 100644 --- a/http/encoding/deflate/src/main/java/io/helidon/http/encoding/deflate/DeflateEncoding.java +++ b/http/encoding/deflate/src/main/java/io/helidon/http/encoding/deflate/DeflateEncoding.java @@ -21,7 +21,9 @@ import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.WritableHeaders; import io.helidon.http.encoding.ContentDecoder; import io.helidon.http.encoding.ContentEncoder; @@ -31,8 +33,8 @@ * Support for {@code deflate} content encoding. */ public class DeflateEncoding implements ContentEncoding { - private static final Http.Header CONTENT_ENCODING_DEFLATE = - Http.Headers.createCached(Http.HeaderNames.CONTENT_ENCODING, + private static final Header CONTENT_ENCODING_DEFLATE = + HeaderValues.createCached(HeaderNames.CONTENT_ENCODING, false, false, "deflate"); @@ -92,7 +94,7 @@ public OutputStream encode(OutputStream network) { @Override public void headers(WritableHeaders headers) { headers.add(CONTENT_ENCODING_DEFLATE); - headers.remove(Http.HeaderNames.CONTENT_LENGTH); + headers.remove(HeaderNames.CONTENT_LENGTH); } }; } diff --git a/http/encoding/encoding/src/main/java/io/helidon/http/encoding/ContentEncodingSupportImpl.java b/http/encoding/encoding/src/main/java/io/helidon/http/encoding/ContentEncodingSupportImpl.java index 52fa10d041f..2b52b6da4d2 100644 --- a/http/encoding/encoding/src/main/java/io/helidon/http/encoding/ContentEncodingSupportImpl.java +++ b/http/encoding/encoding/src/main/java/io/helidon/http/encoding/ContentEncodingSupportImpl.java @@ -25,8 +25,8 @@ import java.util.Objects; import java.util.Set; +import io.helidon.http.HeaderNames; import io.helidon.http.Headers; -import io.helidon.http.Http; class ContentEncodingSupportImpl implements ContentEncodingContext { private static final String IDENTITY_ENCODING = "identity"; @@ -116,11 +116,11 @@ public ContentDecoder decoder(String encodingId) throws NoSuchElementException { @Override public ContentEncoder encoder(Headers headers) { - if (!contentEncodingEnabled() || !headers.contains(Http.HeaderNames.ACCEPT_ENCODING)) { + if (!contentEncodingEnabled() || !headers.contains(HeaderNames.ACCEPT_ENCODING)) { return ContentEncoder.NO_OP; } - String acceptEncoding = headers.get(Http.HeaderNames.ACCEPT_ENCODING).value(); + String acceptEncoding = headers.get(HeaderNames.ACCEPT_ENCODING).value(); /* Accept-Encoding: gzip Accept-Encoding: gzip, compress, br diff --git a/http/encoding/gzip/src/main/java/io/helidon/http/encoding/gzip/GzipEncoding.java b/http/encoding/gzip/src/main/java/io/helidon/http/encoding/gzip/GzipEncoding.java index 3874693d0b5..fafbbd62bf7 100644 --- a/http/encoding/gzip/src/main/java/io/helidon/http/encoding/gzip/GzipEncoding.java +++ b/http/encoding/gzip/src/main/java/io/helidon/http/encoding/gzip/GzipEncoding.java @@ -23,22 +23,24 @@ import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.WritableHeaders; import io.helidon.http.encoding.ContentDecoder; import io.helidon.http.encoding.ContentEncoder; import io.helidon.http.encoding.ContentEncoding; -import static io.helidon.http.Http.HeaderNames.CONTENT_LENGTH; +import static io.helidon.http.HeaderNames.CONTENT_LENGTH; /** * Support for gzip content encoding. */ public class GzipEncoding implements ContentEncoding { - private static final Http.Header CONTENT_ENCODING_GZIP = Http.Headers.createCached(Http.HeaderNames.CONTENT_ENCODING, - false, - false, - "gzip"); + private static final Header CONTENT_ENCODING_GZIP = HeaderValues.createCached(HeaderNames.CONTENT_ENCODING, + false, + false, + "gzip"); private final String name; diff --git a/http/http/src/main/java/io/helidon/http/BadRequestException.java b/http/http/src/main/java/io/helidon/http/BadRequestException.java index 2a7256e2174..b5a6d8ceeda 100644 --- a/http/http/src/main/java/io/helidon/http/BadRequestException.java +++ b/http/http/src/main/java/io/helidon/http/BadRequestException.java @@ -17,7 +17,7 @@ package io.helidon.http; /** - * A runtime exception indicating a {@link Http.Status#BAD_REQUEST_400 bad request}. + * A runtime exception indicating a {@link Status#BAD_REQUEST_400 bad request}. */ public class BadRequestException extends HttpException { @@ -27,7 +27,7 @@ public class BadRequestException extends HttpException { * @param message the message */ public BadRequestException(String message) { - super(message, Http.Status.BAD_REQUEST_400); + super(message, Status.BAD_REQUEST_400); } /** @@ -37,6 +37,6 @@ public BadRequestException(String message) { * @param cause the cause of this exception */ public BadRequestException(String message, Throwable cause) { - super(message, Http.Status.BAD_REQUEST_400, cause); + super(message, Status.BAD_REQUEST_400, cause); } } diff --git a/http/http/src/main/java/io/helidon/http/ClientRequestHeaders.java b/http/http/src/main/java/io/helidon/http/ClientRequestHeaders.java index f573cec4e29..d4b8a0a1943 100644 --- a/http/http/src/main/java/io/helidon/http/ClientRequestHeaders.java +++ b/http/http/src/main/java/io/helidon/http/ClientRequestHeaders.java @@ -56,7 +56,7 @@ default ClientRequestHeaders accept(MediaType... accepted) { MediaType mediaType = accepted[i]; values[i] = mediaType.text(); } - set(Http.Headers.create(Http.HeaderNames.ACCEPT, values)); + set(HeaderValues.create(HeaderNames.ACCEPT, values)); return this; } } diff --git a/http/http/src/main/java/io/helidon/http/ClientRequestHeadersImpl.java b/http/http/src/main/java/io/helidon/http/ClientRequestHeadersImpl.java index b14cb554569..eeddbcb0178 100644 --- a/http/http/src/main/java/io/helidon/http/ClientRequestHeadersImpl.java +++ b/http/http/src/main/java/io/helidon/http/ClientRequestHeadersImpl.java @@ -23,8 +23,6 @@ import java.util.function.Consumer; import java.util.function.Supplier; -import io.helidon.http.Http.HeaderName; - /** * Client request headers. */ @@ -48,12 +46,12 @@ public boolean contains(HeaderName name) { } @Override - public boolean contains(Http.Header headerWithValue) { + public boolean contains(Header headerWithValue) { return delegate.contains(headerWithValue); } @Override - public Http.Header get(HeaderName name) { + public Header get(HeaderName name) { return delegate.get(name); } @@ -65,8 +63,8 @@ public int size() { @Override public List acceptedTypes() { if (mediaTypes == null) { - if (delegate.contains(Http.HeaderNames.ACCEPT)) { - List accepts = delegate.get(Http.HeaderNames.ACCEPT).allValues(true); + if (delegate.contains(HeaderNames.ACCEPT)) { + List accepts = delegate.get(HeaderNames.ACCEPT).allValues(true); List mediaTypes = new ArrayList<>(accepts.size()); for (String accept : accepts) { @@ -83,13 +81,13 @@ public List acceptedTypes() { } @Override - public ClientRequestHeaders setIfAbsent(Http.Header header) { + public ClientRequestHeaders setIfAbsent(Header header) { delegate.setIfAbsent(header); return this; } @Override - public ClientRequestHeaders add(Http.Header header) { + public ClientRequestHeaders add(Header header) { delegate.add(header); return this; } @@ -101,19 +99,19 @@ public ClientRequestHeaders remove(HeaderName name) { } @Override - public ClientRequestHeaders remove(HeaderName name, Consumer removedConsumer) { + public ClientRequestHeaders remove(HeaderName name, Consumer
removedConsumer) { delegate.remove(name, removedConsumer); return this; } @Override - public ClientRequestHeaders set(Http.Header header) { + public ClientRequestHeaders set(Header header) { delegate.set(header); return this; } @Override - public Iterator iterator() { + public Iterator
iterator() { return delegate.iterator(); } diff --git a/http/http/src/main/java/io/helidon/http/ClientResponseHeaders.java b/http/http/src/main/java/io/helidon/http/ClientResponseHeaders.java index 91d9551b046..8677c9e7221 100644 --- a/http/http/src/main/java/io/helidon/http/ClientResponseHeaders.java +++ b/http/http/src/main/java/io/helidon/http/ClientResponseHeaders.java @@ -23,12 +23,11 @@ import java.util.Optional; import io.helidon.common.media.type.ParserMode; -import io.helidon.http.Http.DateTime; -import static io.helidon.http.Http.HeaderNames.ACCEPT_PATCH; -import static io.helidon.http.Http.HeaderNames.EXPIRES; -import static io.helidon.http.Http.HeaderNames.LAST_MODIFIED; -import static io.helidon.http.Http.HeaderNames.LOCATION; +import static io.helidon.http.HeaderNames.ACCEPT_PATCH; +import static io.helidon.http.HeaderNames.EXPIRES; +import static io.helidon.http.HeaderNames.LAST_MODIFIED; +import static io.helidon.http.HeaderNames.LOCATION; /** * HTTP Headers of a client response. @@ -71,7 +70,7 @@ default List acceptPatches() { } /** - * Optionally gets the value of {@link io.helidon.http.Http.HeaderNames#LOCATION} header. + * Optionally gets the value of {@link HeaderNames#LOCATION} header. *

* Used in redirection, or when a new resource has been created. * @@ -80,14 +79,14 @@ default List acceptPatches() { default Optional location() { if (contains(LOCATION)) { return Optional.of(get(LOCATION)) - .map(Http.Header::get) + .map(Header::get) .map(URI::create); } return Optional.empty(); } /** - * Optionally gets the value of {@link io.helidon.http.Http.HeaderNames#LAST_MODIFIED} header. + * Optionally gets the value of {@link HeaderNames#LAST_MODIFIED} header. *

* The last modified date for the requested object. * @@ -96,14 +95,14 @@ default Optional location() { default Optional lastModified() { if (contains(LAST_MODIFIED)) { return Optional.of(get(LAST_MODIFIED)) - .map(Http.Header::get) + .map(Header::get) .map(DateTime::parse); } return Optional.empty(); } /** - * Optionally gets the value of {@link io.helidon.http.Http.HeaderNames#EXPIRES} header. + * Optionally gets the value of {@link HeaderNames#EXPIRES} header. *

* Gives the date/time after which the response is considered stale. * @@ -112,7 +111,7 @@ default Optional lastModified() { default Optional expires() { if (contains(EXPIRES)) { return Optional.of(get(EXPIRES)) - .map(Http.Header::get) + .map(Header::get) .map(DateTime::parse); } return Optional.empty(); diff --git a/http/http/src/main/java/io/helidon/http/ClientResponseHeadersImpl.java b/http/http/src/main/java/io/helidon/http/ClientResponseHeadersImpl.java index edb3111e034..3b90ec2969a 100644 --- a/http/http/src/main/java/io/helidon/http/ClientResponseHeadersImpl.java +++ b/http/http/src/main/java/io/helidon/http/ClientResponseHeadersImpl.java @@ -33,22 +33,22 @@ class ClientResponseHeadersImpl implements ClientResponseHeaders { } @Override - public List all(Http.HeaderName name, Supplier> defaultSupplier) { + public List all(HeaderName name, Supplier> defaultSupplier) { return headers.all(name, defaultSupplier); } @Override - public boolean contains(Http.HeaderName name) { + public boolean contains(HeaderName name) { return headers.contains(name); } @Override - public boolean contains(Http.Header headerWithValue) { + public boolean contains(Header headerWithValue) { return headers.contains(headerWithValue); } @Override - public Http.Header get(Http.HeaderName name) { + public Header get(HeaderName name) { return headers.get(name); } @@ -68,7 +68,7 @@ public int size() { } @Override - public Iterator iterator() { + public Iterator

iterator() { return headers.iterator(); } diff --git a/http/http/src/main/java/io/helidon/http/ContentDisposition.java b/http/http/src/main/java/io/helidon/http/ContentDisposition.java index c6e555f0a4e..b33cd4917d1 100644 --- a/http/http/src/main/java/io/helidon/http/ContentDisposition.java +++ b/http/http/src/main/java/io/helidon/http/ContentDisposition.java @@ -51,7 +51,7 @@ * * */ -public class ContentDisposition implements Http.Header { +public class ContentDisposition implements Header { private static final String NAME_PARAMETER = "name"; private static final String FILENAME_PARAMETER = "filename"; private static final String CREATION_DATE_PARAMETER = "creation-date"; @@ -129,12 +129,12 @@ public static ContentDisposition empty() { @Override public String name() { - return Http.HeaderNames.CONTENT_DISPOSITION.defaultCase(); + return HeaderNames.CONTENT_DISPOSITION.defaultCase(); } @Override - public Http.HeaderName headerName() { - return Http.HeaderNames.CONTENT_DISPOSITION; + public HeaderName headerName() { + return HeaderNames.CONTENT_DISPOSITION; } @Override @@ -263,7 +263,7 @@ public Optional filename() { * @return {@code Optional}, never {@code null} */ public Optional creationDate() { - return Optional.ofNullable(parameters.get(CREATION_DATE_PARAMETER)).map(Http.DateTime::parse); + return Optional.ofNullable(parameters.get(CREATION_DATE_PARAMETER)).map(DateTime::parse); } /** @@ -273,7 +273,7 @@ public Optional creationDate() { * @return {@code Optional}, never {@code null} */ public Optional modificationDate() { - return Optional.ofNullable(parameters.get(MODIFICATION_DATE_PARAMETER)).map(Http.DateTime::parse); + return Optional.ofNullable(parameters.get(MODIFICATION_DATE_PARAMETER)).map(DateTime::parse); } /** @@ -283,7 +283,7 @@ public Optional modificationDate() { * @return {@code Optional}, never {@code null} */ public Optional readDate() { - return Optional.ofNullable(parameters.get(READ_DATE_PARAMETER)).map(Http.DateTime::parse); + return Optional.ofNullable(parameters.get(READ_DATE_PARAMETER)).map(DateTime::parse); } /** @@ -380,7 +380,7 @@ public Builder filename(String filename) { * @return this builder */ public Builder creationDate(ZonedDateTime date) { - parameters.put(CREATION_DATE_PARAMETER, date.format(Http.DateTime.RFC_1123_DATE_TIME)); + parameters.put(CREATION_DATE_PARAMETER, date.format(DateTime.RFC_1123_DATE_TIME)); return this; } @@ -391,7 +391,7 @@ public Builder creationDate(ZonedDateTime date) { * @return this builder */ public Builder modificationDate(ZonedDateTime date) { - parameters.put(MODIFICATION_DATE_PARAMETER, date.format(Http.DateTime.RFC_1123_DATE_TIME)); + parameters.put(MODIFICATION_DATE_PARAMETER, date.format(DateTime.RFC_1123_DATE_TIME)); return this; } @@ -402,7 +402,7 @@ public Builder modificationDate(ZonedDateTime date) { * @return this builder */ public Builder readDate(ZonedDateTime date) { - parameters.put(READ_DATE_PARAMETER, date.format(Http.DateTime.RFC_1123_DATE_TIME)); + parameters.put(READ_DATE_PARAMETER, date.format(DateTime.RFC_1123_DATE_TIME)); return this; } diff --git a/http/http/src/main/java/io/helidon/http/CookieParser.java b/http/http/src/main/java/io/helidon/http/CookieParser.java index a13f7167b26..abbd1d303f6 100644 --- a/http/http/src/main/java/io/helidon/http/CookieParser.java +++ b/http/http/src/main/java/io/helidon/http/CookieParser.java @@ -43,7 +43,7 @@ private CookieParser() { * @param httpHeader cookie header * @return a cookie name and values parsed into a parameter format. */ - static Parameters parse(Http.Header httpHeader) { + static Parameters parse(Header httpHeader) { Map> allCookies = new HashMap<>(); for (String value : httpHeader.allValues()) { parse(allCookies, value); diff --git a/http/http/src/main/java/io/helidon/http/DateTime.java b/http/http/src/main/java/io/helidon/http/DateTime.java new file mode 100644 index 00000000000..d530beb71bb --- /dev/null +++ b/http/http/src/main/java/io/helidon/http/DateTime.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.http; + +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Support for HTTP date formats based on RFC2616. + */ +public final class DateTime { + /** + * The RFC850 date-time formatter, such as {@code 'Sunday, 06-Nov-94 08:49:37 GMT'}. + *

+ * This is obsolete standard (obsoleted by RFC1036). Headers MUST NOT be generated in this format. + * However it should be used as a fallback for parsing to achieve compatibility with older HTTP standards. + *

+ * Since the format accepts 2 digits year representation formatter works well for dates between + * {@code (now - 50 Years)} and {@code (now + 49 Years)}. + */ + public static final DateTimeFormatter RFC_850_DATE_TIME = DateTimeHelper.RFC_850_DATE_TIME; + /** + * The RFC1123 date-time formatter, such as {@code 'Tue, 3 Jun 2008 11:05:30 GMT'}. + *

+ * This is standard for RFC2616 and all created headers MUST be in this format! However implementation must + * accept headers also in RFC850 and ANSI C {@code asctime()} format. + *

+ * This is just copy of convenient copy of {@link java.time.format.DateTimeFormatter#RFC_1123_DATE_TIME}. + */ + public static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.RFC_1123_DATE_TIME; + /** + * The ANSI C's {@code asctime()} format, such as {@code 'Sun Nov 6 08:49:37 1994'}. + *

+ * Headers MUST NOT be generated in this format. + * However it should be used as a fallback for parsing to achieve compatibility with older HTTP standards. + */ + public static final DateTimeFormatter ASCTIME_DATE_TIME = DateTimeHelper.ASCTIME_DATE_TIME; + + private DateTime() { + } + + /** + * Parse provided text to {@link java.time.ZonedDateTime} using any possible date / time format specified + * by RFC2616 Hypertext Transfer Protocol. + *

+ * Formats are specified by {@link #RFC_1123_DATE_TIME}, {@link #RFC_850_DATE_TIME} and {@link #ASCTIME_DATE_TIME}. + * + * @param text a text to parse. + * @return parsed date time. + * @throws java.time.format.DateTimeParseException if not in any of supported formats. + */ + public static ZonedDateTime parse(String text) { + return DateTimeHelper.parse(text); + } + + /** + * Last recorded timestamp. + * + * @return timestamp + */ + public static ZonedDateTime timestamp() { + return DateTimeHelper.timestamp(); + } + + /** + * Get current time as RFC-1123 string. + * + * @return formatted current time + * @see #RFC_1123_DATE_TIME + */ + public static String rfc1123String() { + return DateTimeHelper.rfc1123String(); + } + + /** + * Formatted date time terminated by carriage return and new line. + * + * @return date bytes for HTTP/1 + */ + public static byte[] http1Bytes() { + return DateTimeHelper.http1Bytes(); + } +} diff --git a/http/http/src/main/java/io/helidon/http/DirectHandler.java b/http/http/src/main/java/io/helidon/http/DirectHandler.java index ef0f1c7a608..a7a38e6506f 100644 --- a/http/http/src/main/java/io/helidon/http/DirectHandler.java +++ b/http/http/src/main/java/io/helidon/http/DirectHandler.java @@ -57,7 +57,7 @@ static DirectHandler defaultHandler() { */ default TransportResponse handle(TransportRequest request, EventType eventType, - Http.Status defaultStatus, + Status defaultStatus, ServerResponseHeaders responseHeaders, Throwable thrown) { return handle(request, eventType, defaultStatus, responseHeaders, thrown, null); @@ -80,7 +80,7 @@ default TransportResponse handle(TransportRequest request, */ default TransportResponse handle(TransportRequest request, EventType eventType, - Http.Status defaultStatus, + Status defaultStatus, ServerResponseHeaders responseHeaders, Throwable thrown, System.Logger logger) { @@ -115,7 +115,7 @@ default TransportResponse handle(TransportRequest request, */ TransportResponse handle(TransportRequest request, EventType eventType, - Http.Status defaultStatus, + Status defaultStatus, ServerResponseHeaders responseHeaders, String message); @@ -172,28 +172,28 @@ enum EventType { /** * Bad request, such as invalid path, header. */ - BAD_REQUEST(Http.Status.BAD_REQUEST_400, false), + BAD_REQUEST(Status.BAD_REQUEST_400, false), /** * Payload is bigger than the configured maximal size. */ - PAYLOAD_TOO_LARGE(Http.Status.REQUEST_ENTITY_TOO_LARGE_413, false), + PAYLOAD_TOO_LARGE(Status.REQUEST_ENTITY_TOO_LARGE_413, false), /** * Forbidden, such as when CORS forbids this request. */ - FORBIDDEN(Http.Status.FORBIDDEN_403, true), + FORBIDDEN(Status.FORBIDDEN_403, true), /** * Internal server error. */ - INTERNAL_ERROR(Http.Status.INTERNAL_SERVER_ERROR_500, true), + INTERNAL_ERROR(Status.INTERNAL_SERVER_ERROR_500, true), /** * Other type, please specify expected status code. */ - OTHER(Http.Status.INTERNAL_SERVER_ERROR_500, true); + OTHER(Status.INTERNAL_SERVER_ERROR_500, true); - private final Http.Status defaultStatus; + private final Status defaultStatus; private final boolean keepAlive; - EventType(Http.Status defaultStatus, boolean keepAlive) { + EventType(Status defaultStatus, boolean keepAlive) { this.defaultStatus = defaultStatus; this.keepAlive = keepAlive; } @@ -203,7 +203,7 @@ enum EventType { * * @return status */ - public Http.Status defaultStatus() { + public Status defaultStatus() { return defaultStatus; } @@ -221,7 +221,7 @@ public boolean keepAlive() { * Response to correctly reply to the original client. */ class TransportResponse { - private final Http.Status status; + private final Status status; private final ServerResponseHeaders headers; private final byte[] entity; private final boolean keepAlive; @@ -247,7 +247,7 @@ public static Builder builder() { * * @return status */ - public Http.Status status() { + public Status status() { return status; } @@ -282,7 +282,7 @@ public boolean keepAlive() { * Fluent API builder for {@link DirectHandler.TransportResponse}. */ public static class Builder implements io.helidon.common.Builder { - private Http.Status status = Http.Status.BAD_REQUEST_400; + private Status status = Status.BAD_REQUEST_400; private byte[] entity; private ServerResponseHeaders headers = ServerResponseHeaders.create(); private boolean keepAlive = true; @@ -301,7 +301,7 @@ public TransportResponse build() { * @param status status to use, default is bad request * @return updated builder */ - public Builder status(Http.Status status) { + public Builder status(Status status) { this.status = status; return this; } @@ -325,7 +325,7 @@ public Builder headers(ServerResponseHeaders headers) { * @param values value of the header * @return updated builder */ - public Builder header(Http.HeaderName name, String... values) { + public Builder header(HeaderName name, String... values) { this.headers.set(name, List.of(values)); return this; } @@ -337,7 +337,7 @@ public Builder header(Http.HeaderName name, String... values) { * @param header header value * @return updated builder */ - public Builder header(Http.Header header) { + public Builder header(Header header) { this.headers.add(header); return this; } @@ -365,7 +365,7 @@ public Builder keepAlive(boolean keepAlive) { * @return updated builder */ public Builder entity(String entity) { - this.headers.setIfAbsent(Http.Headers.CONTENT_TYPE_TEXT_PLAIN); + this.headers.setIfAbsent(HeaderValues.CONTENT_TYPE_TEXT_PLAIN); return entity(entity.getBytes(StandardCharsets.UTF_8)); } @@ -381,9 +381,9 @@ public Builder entity(String entity) { public Builder entity(byte[] entity) { this.entity = Arrays.copyOf(entity, entity.length); if (this.entity.length == 0) { - this.headers.remove(Http.HeaderNames.CONTENT_LENGTH); + this.headers.remove(HeaderNames.CONTENT_LENGTH); } else { - header(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(entity.length)); + header(HeaderNames.CONTENT_LENGTH, String.valueOf(entity.length)); } return this; } diff --git a/http/http/src/main/java/io/helidon/http/DirectHandlerDefault.java b/http/http/src/main/java/io/helidon/http/DirectHandlerDefault.java index 9cbb09ec6e3..8031bbbcf2f 100644 --- a/http/http/src/main/java/io/helidon/http/DirectHandlerDefault.java +++ b/http/http/src/main/java/io/helidon/http/DirectHandlerDefault.java @@ -25,7 +25,7 @@ private DirectHandlerDefault() { @Override public TransportResponse handle(TransportRequest request, EventType eventType, - Http.Status defaultStatus, + Status defaultStatus, ServerResponseHeaders headers, String message) { return TransportResponse.builder() diff --git a/http/http/src/main/java/io/helidon/http/ForbiddenException.java b/http/http/src/main/java/io/helidon/http/ForbiddenException.java index a1de924a14f..be5f9d25f12 100644 --- a/http/http/src/main/java/io/helidon/http/ForbiddenException.java +++ b/http/http/src/main/java/io/helidon/http/ForbiddenException.java @@ -17,7 +17,7 @@ package io.helidon.http; /** - * A runtime exception indicating a {@link Http.Status#FORBIDDEN_403 forbidden}. + * A runtime exception indicating a {@link Status#FORBIDDEN_403 forbidden}. */ public class ForbiddenException extends HttpException { @@ -27,7 +27,7 @@ public class ForbiddenException extends HttpException { * @param message the message */ public ForbiddenException(String message) { - super(message, Http.Status.FORBIDDEN_403, null, true); + super(message, Status.FORBIDDEN_403, null, true); } /** @@ -37,6 +37,6 @@ public ForbiddenException(String message) { * @param cause the cause of this exception */ public ForbiddenException(String message, Throwable cause) { - super(message, Http.Status.FORBIDDEN_403, cause, true); + super(message, Status.FORBIDDEN_403, cause, true); } } diff --git a/http/http/src/main/java/io/helidon/http/Forwarded.java b/http/http/src/main/java/io/helidon/http/Forwarded.java index 619043adc18..4f72a40d964 100644 --- a/http/http/src/main/java/io/helidon/http/Forwarded.java +++ b/http/http/src/main/java/io/helidon/http/Forwarded.java @@ -21,10 +21,10 @@ import java.util.Locale; import java.util.Optional; -import static io.helidon.http.Http.HeaderNames.FORWARDED; +import static io.helidon.http.HeaderNames.FORWARDED; /** - * A representation of the {@link io.helidon.http.Http.HeaderNames#FORWARDED} HTTP header. + * A representation of the {@link HeaderNames#FORWARDED} HTTP header. */ public class Forwarded { private static final System.Logger LOGGER = System.getLogger(Forwarded.class.getName()); diff --git a/http/http/src/main/java/io/helidon/http/Header.java b/http/http/src/main/java/io/helidon/http/Header.java new file mode 100644 index 00000000000..45727acf8ae --- /dev/null +++ b/http/http/src/main/java/io/helidon/http/Header.java @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.http; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import io.helidon.common.buffers.BufferData; +import io.helidon.common.mapper.Value; + +/** + * HTTP Header with {@link io.helidon.http.HeaderName} and value. + * + * @see io.helidon.http.HeaderValues + */ +public interface Header extends Value { + + /** + * Name of the header as configured by user + * or as received on the wire. + * + * @return header name, always lower case for HTTP/2 headers + */ + @Override + String name(); + + /** + * Value of the header. + * + * @return header value + * @deprecated use {@link #get()} + */ + @Deprecated(forRemoval = true, since = "4.0.0") + default String value() { + return get(); + } + + /** + * Header name for the header. + * + * @return header name + */ + HeaderName headerName(); + + /** + * All values concatenated using a comma. + * + * @return all values joined by a comma + */ + default String values() { + return String.join(",", allValues()); + } + + /** + * All values of this header. + * + * @return all configured values + */ + List allValues(); + + /** + * All values of this header. If this header is defined as a single header with comma separated values, + * set {@code split} to true. + * + * @param split whether to split single value by comma, does nothing if the value is already a list. + * @return list of values + */ + default List allValues(boolean split) { + if (split) { + List values = allValues(); + if (values.size() == 1) { + String value = values.get(0); + if (value.contains(", ")) { + return List.of(value.split(", ")); + } else { + return List.of(value); + } + } + return values; + } else { + return allValues(); + } + } + + /** + * Number of values this header has. + * + * @return number of values (minimal number is 1) + */ + int valueCount(); + + /** + * Sensitive headers should not be logged, or indexed (HTTP/2). + * + * @return whether this header is sensitive + */ + boolean sensitive(); + + /** + * Changing headers should not be cached, and their value should not be indexed (HTTP/2). + * + * @return whether this header's value is changing often + */ + boolean changing(); + + /** + * Cached bytes of a single valued header's value. + * + * @return value bytes + */ + default byte[] valueBytes() { + return get().getBytes(StandardCharsets.US_ASCII); + } + + /** + * Write the current header as an HTTP header to the provided buffer. + * + * @param buffer buffer to write to (should be growing) + */ + default void writeHttp1Header(BufferData buffer) { + byte[] nameBytes = name().getBytes(StandardCharsets.US_ASCII); + if (valueCount() == 1) { + writeHeader(buffer, nameBytes, valueBytes()); + } else { + for (String value : allValues()) { + writeHeader(buffer, nameBytes, value.getBytes(StandardCharsets.US_ASCII)); + } + } + } + + /** + * Check validity of header name and values. + * + * @throws IllegalArgumentException in case the HeaderValue is not valid + */ + default void validate() throws IllegalArgumentException { + String name = name(); + // validate that header name only contains valid characters + HttpToken.validate(name); + // Validate header value + validateValue(name, values()); + } + + // validate header value based on https://www.rfc-editor.org/rfc/rfc7230#section-3.2 and throws IllegalArgumentException + // if invalid. + private static void validateValue(String name, String value) throws IllegalArgumentException { + char[] vChars = value.toCharArray(); + int vLength = vChars.length; + for (int i = 0; i < vLength; i++) { + char vChar = vChars[i]; + if (i == 0) { + if (vChar < '!' || vChar == '\u007f') { + throw new IllegalArgumentException("First character of the header value is invalid" + + " for header '" + name + "'"); + } + } else { + if (vChar < ' ' && vChar != '\t' || vChar == '\u007f') { + throw new IllegalArgumentException("Character at position " + (i + 1) + " of the header value is invalid" + + " for header '" + name + "'"); + } + } + } + } + + private void writeHeader(BufferData buffer, byte[] nameBytes, byte[] valueBytes) { + // header name + buffer.write(nameBytes); + // ": " + buffer.write(':'); + buffer.write(' '); + // header value + buffer.write(valueBytes); + // \r\n + buffer.write('\r'); + buffer.write('\n'); + } +} diff --git a/http/http/src/main/java/io/helidon/http/HeaderName.java b/http/http/src/main/java/io/helidon/http/HeaderName.java new file mode 100644 index 00000000000..d4c1479fed1 --- /dev/null +++ b/http/http/src/main/java/io/helidon/http/HeaderName.java @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.http; + +/** + * HTTP header name. + */ +public sealed interface HeaderName permits HeaderNameImpl, HeaderNameEnum { + /** + * Lowercase value of this header, used by HTTP/2, may be used for lookup by HTTP/1. + * There is no validation of this value, so if this contains an upper-case letter, behavior + * is undefined. + * + * @return name of the header, lowercase + */ + String lowerCase(); + + /** + * Header name as used in HTTP/1, or "human-readable" value of this header. + * + * @return name of the header, may use uppercase and/or lowercase + */ + String defaultCase(); + + /** + * Index of this header (if one of the known indexed headers), or {@code -1} if this is a custom header name. + * + * @return index of this header + */ + default int index() { + return -1; + } + + /** + * Http2 defines pseudoheaders as headers starting with a {@code :} character. These are used instead + * of the prologue line from HTTP/1 (to define path, authority etc.) and instead of status line in response. + * + * @return whether this header is a pseudo-header + */ + default boolean isPseudoHeader() { + return lowerCase().charAt(0) == ':'; + } +} diff --git a/http/http/src/main/java/io/helidon/http/HeaderNameEnum.java b/http/http/src/main/java/io/helidon/http/HeaderNameEnum.java index d4c707065ef..1447633dd47 100644 --- a/http/http/src/main/java/io/helidon/http/HeaderNameEnum.java +++ b/http/http/src/main/java/io/helidon/http/HeaderNameEnum.java @@ -25,7 +25,7 @@ * Do not add random headers here. These headers are optimized for performance, and each header added to this enum * will slightly increase the memory used by each HTTP request. */ -enum HeaderNameEnum implements Http.HeaderName { +enum HeaderNameEnum implements HeaderName { ACCEPT("Accept"), ACCEPT_CHARSET("Accept-Charset"), ACCEPT_ENCODING("Accept-Encoding"), @@ -44,7 +44,7 @@ enum HeaderNameEnum implements Http.HeaderName { EXPECT("Expect"), FORWARDED("Forwarded"), FROM("From"), - HOST(Http.HeaderNames.HOST_STRING), + HOST(HeaderNames.HOST_STRING), IF_MATCH("If-Match"), IF_MODIFIED_SINCE("If-Modified-Since"), IF_NONE_MATCH("If-None-Match"), @@ -101,12 +101,12 @@ enum HeaderNameEnum implements Http.HeaderName { X_FORWARDED_PROTO("X-Forwarded-Proto"), X_HELIDON_CN("X-HELIDON-CN"); - private static final Map BY_NAME; - private static final Map BY_CAP_NAME; + private static final Map BY_NAME; + private static final Map BY_CAP_NAME; static { - Map byName = new HashMap<>(); - Map byCapName = new HashMap<>(); + Map byName = new HashMap<>(); + Map byCapName = new HashMap<>(); for (HeaderNameEnum value : HeaderNameEnum.values()) { byName.put(value.lowerCase(), value); byCapName.put(value.defaultCase(), value); @@ -125,15 +125,15 @@ enum HeaderNameEnum implements Http.HeaderName { this.index = this.ordinal(); } - static Http.HeaderName byCapitalizedName(String name) { - Http.HeaderName found = BY_CAP_NAME.get(name); + static HeaderName byCapitalizedName(String name) { + HeaderName found = BY_CAP_NAME.get(name); if (found == null) { return byName(Ascii.toLowerCase(name)); } return found; } - static Http.HeaderName byName(String lowerCase) { + static HeaderName byName(String lowerCase) { return BY_NAME.get(lowerCase); } diff --git a/http/http/src/main/java/io/helidon/http/HeaderNameImpl.java b/http/http/src/main/java/io/helidon/http/HeaderNameImpl.java index cf1ff32e7a6..90ba3a05fdd 100644 --- a/http/http/src/main/java/io/helidon/http/HeaderNameImpl.java +++ b/http/http/src/main/java/io/helidon/http/HeaderNameImpl.java @@ -18,7 +18,7 @@ import java.util.Objects; -record HeaderNameImpl(String lowerCase, String defaultCase) implements Http.HeaderName { +record HeaderNameImpl(String lowerCase, String defaultCase) implements HeaderName { @Override public boolean equals(Object obj) { diff --git a/http/http/src/main/java/io/helidon/http/HeaderNames.java b/http/http/src/main/java/io/helidon/http/HeaderNames.java new file mode 100644 index 00000000000..5907e08dbc4 --- /dev/null +++ b/http/http/src/main/java/io/helidon/http/HeaderNames.java @@ -0,0 +1,473 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.http; + +import io.helidon.common.buffers.Ascii; + +/** + * Utility class with a list of names of standard HTTP headers and related tooling methods. + */ +public final class HeaderNames { + /** + * The {@code Accept} header name. + * Content-Types that are acceptedTypes for the response. + */ + public static final HeaderName ACCEPT = HeaderNameEnum.ACCEPT; + /** + * The {@code Accept-Charset} header name. + * Character sets that are acceptedTypes. + */ + public static final HeaderName ACCEPT_CHARSET = HeaderNameEnum.ACCEPT_CHARSET; + /** + * The {@code Accept-Encoding} header name. + * List of acceptedTypes encodings. + */ + public static final HeaderName ACCEPT_ENCODING = HeaderNameEnum.ACCEPT_ENCODING; + /** + * The {@code Accept-Language} header name. + * List of acceptedTypes human languages for response. + */ + public static final HeaderName ACCEPT_LANGUAGE = HeaderNameEnum.ACCEPT_LANGUAGE; + /** + * The {@code Accept-Datetime} header name. + * Acceptable version in time. + */ + public static final HeaderName ACCEPT_DATETIME = HeaderNameEnum.ACCEPT_DATETIME; + /** + * The {@code Access-Control-Allow-Credentials} header name. + * CORS configuration. + */ + public static final HeaderName ACCESS_CONTROL_ALLOW_CREDENTIALS = HeaderNameEnum.ACCESS_CONTROL_ALLOW_CREDENTIALS; + /** + * The {@code Access-Control-Allow-Headers} header name. + * CORS configuration + */ + public static final HeaderName ACCESS_CONTROL_ALLOW_HEADERS = HeaderNameEnum.ACCESS_CONTROL_ALLOW_HEADERS; + /** + * The {@code Access-Control-Allow-Methods} header name. + * CORS configuration + */ + public static final HeaderName ACCESS_CONTROL_ALLOW_METHODS = HeaderNameEnum.ACCESS_CONTROL_ALLOW_METHODS; + /** + * The {@code Access-Control-Allow-Origin} header name. + * CORS configuration. + */ + public static final HeaderName ACCESS_CONTROL_ALLOW_ORIGIN = HeaderNameEnum.ACCESS_CONTROL_ALLOW_ORIGIN; + /** + * The {@code Access-Control-Expose-Headers} header name. + * CORS configuration. + */ + public static final HeaderName ACCESS_CONTROL_EXPOSE_HEADERS = HeaderNameEnum.ACCESS_CONTROL_EXPOSE_HEADERS; + /** + * The {@code Access-Control-Max-Age} header name. + * CORS configuration. + */ + public static final HeaderName ACCESS_CONTROL_MAX_AGE = HeaderNameEnum.ACCESS_CONTROL_MAX_AGE; + /** + * The {@code Access-Control-Request-Headers} header name. + * CORS configuration. + */ + public static final HeaderName ACCESS_CONTROL_REQUEST_HEADERS = HeaderNameEnum.ACCESS_CONTROL_REQUEST_HEADERS; + /** + * The {@code Access-Control-Request-Method} header name. + * CORS configuration. + */ + public static final HeaderName ACCESS_CONTROL_REQUEST_METHOD = HeaderNameEnum.ACCESS_CONTROL_REQUEST_METHOD; + /** + * The {@code Authorization} header name. + * Authentication credentials for HTTP authentication. + */ + public static final HeaderName AUTHORIZATION = HeaderNameEnum.AUTHORIZATION; + /** + * The {@code Cookie} header name. + * An HTTP cookie previously sent by the server with {@code Set-Cookie}. + */ + public static final HeaderName COOKIE = HeaderNameEnum.COOKIE; + /** + * The {@code Expect} header name. + * Indicates that particular server behaviors are required by the client. + */ + public static final HeaderName EXPECT = HeaderNameEnum.EXPECT; + /** + * The {@code Forwarded} header name. + * Disclose original information of a client connecting to a web server through an HTTP proxy. + */ + public static final HeaderName FORWARDED = HeaderNameEnum.FORWARDED; + /** + * The {@code From} header name. + * The email address of the user making the request. + */ + public static final HeaderName FROM = HeaderNameEnum.FROM; + /** + * The {@code Host} header name. + * The domain name of the server (for virtual hosting), and the TCP port number on which the server is listening. + * The port number may be omitted if the port is the standard port for the service requested. + */ + public static final HeaderName HOST = HeaderNameEnum.HOST; + /** + * The {@value} header. + * + * @see #HOST + */ + public static final String HOST_STRING = "Host"; + /** + * The {@code If-Match} header name. + * Only perform the action if the client supplied entity matches the same entity on the server. This is mainly + * for methods like PUT to only update a resource if it has not been modified since the user last updated it. + */ + public static final HeaderName IF_MATCH = HeaderNameEnum.IF_MATCH; + /** + * The {@code If-Modified-Since} header name. + * Allows a 304 Not Modified to be returned if content is unchanged. + */ + public static final HeaderName IF_MODIFIED_SINCE = HeaderNameEnum.IF_MODIFIED_SINCE; + /** + * The {@code If-None-Match} header name. + * Allows a 304 Not Modified to be returned if content is unchanged, based on {@link #ETAG}. + */ + public static final HeaderName IF_NONE_MATCH = HeaderNameEnum.IF_NONE_MATCH; + /** + * The {@code If-Range} header name. + * If the entity is unchanged, send me the part(s) that I am missing; otherwise, send me the entire new entity. + */ + public static final HeaderName IF_RANGE = HeaderNameEnum.IF_RANGE; + /** + * The {@code If-Unmodified-Since} header name. + * Only send The {@code response if The Entity} has not been modified since a specific time. + */ + public static final HeaderName IF_UNMODIFIED_SINCE = HeaderNameEnum.IF_UNMODIFIED_SINCE; + /** + * The {@code Max-Forwards} header name. + * Limit the number of times the message can be forwarded through proxies or gateways. + */ + public static final HeaderName MAX_FORWARDS = HeaderNameEnum.MAX_FORWARDS; + /** + * The {@code {@value}} header name. + * Initiates a request for cross-origin resource sharing (asks server for an {@code 'Access-Control-Allow-Origin'} + * response field). + */ + public static final HeaderName ORIGIN = HeaderNameEnum.ORIGIN; + /** + * The {@code Proxy-Authenticate} header name. + * Proxy authentication information. + */ + public static final HeaderName PROXY_AUTHENTICATE = HeaderNameEnum.PROXY_AUTHENTICATE; + /** + * The {@code Proxy-Authorization} header name. + * Proxy authorization information. + */ + public static final HeaderName PROXY_AUTHORIZATION = HeaderNameEnum.PROXY_AUTHORIZATION; + /** + * The {@code Range} header name. + * Request only part of an entity. Bytes are numbered from 0. + */ + public static final HeaderName RANGE = HeaderNameEnum.RANGE; + /** + * The {@code {@value}} header name. + * This is the address of the previous web page from which a link to the currently requested page was followed. + * (The {@code word referrer} has been misspelled in The + * {@code RFC as well as in most implementations to the point that it} has + * become standard usage and is considered correct terminology.) + */ + public static final HeaderName REFERER = HeaderNameEnum.REFERER; + /** + * The {@code {@value}} header name. + */ + public static final HeaderName REFRESH = HeaderNameEnum.REFRESH; + /** + * The {@code {@value}} header name. + * The {@code transfer encodings the user agent is willing to acceptedTypes: the same values as for The Response} header + * field + * {@code Transfer-Encoding} can be used, plus the trailers value (related to the chunked transfer method) + * to notify the server it expects to receive additional fields in the trailer after the last, zero-sized, chunk. + */ + public static final HeaderName TE = HeaderNameEnum.TE; + /** + * The {@code User-Agent} header name. + * The user agent string of the user agent. + */ + public static final HeaderName USER_AGENT = HeaderNameEnum.USER_AGENT; + /** + * The {@code Via} header name. + * Informs the server of proxies through which the request was sent. + */ + public static final HeaderName VIA = HeaderNameEnum.VIA; + /** + * The {@code Accept-Patch} header name. + * Specifies which patch document formats this server supports. + */ + public static final HeaderName ACCEPT_PATCH = HeaderNameEnum.ACCEPT_PATCH; + /** + * The {@code Accept-Ranges} header name. + * What partial content range types this server supports via byte serving. + */ + public static final HeaderName ACCEPT_RANGES = HeaderNameEnum.ACCEPT_RANGES; + /** + * The {@code Age} header name. + * The {@code age The Object} has been in a proxy cache in seconds. + */ + public static final HeaderName AGE = HeaderNameEnum.AGE; + /** + * The {@code Allow} header name. + * Valid actions for a specified resource. To be used for a 405 Method not allowed. + */ + public static final HeaderName ALLOW = HeaderNameEnum.ALLOW; + /** + * The {@code {@value}} header name. + * A server uses Alt-Svc header (meaning Alternative Services) to indicate that its resources can also be + * accessed at a different network location (host or port) or using a different protocol. + */ + public static final HeaderName ALT_SVC = HeaderNameEnum.ALT_SVC; + /** + * The {@code Cache-Control} header name. + * Tells all caching mechanisms from server to client whether they may cache this object. It is measured in seconds. + */ + public static final HeaderName CACHE_CONTROL = HeaderNameEnum.CACHE_CONTROL; + /** + * The {@code Connection} header name. + * Control options for The {@code current connection and list of} hop-by-hop response fields. + */ + public static final HeaderName CONNECTION = HeaderNameEnum.CONNECTION; + /** + * The {@code {@value}} header name. + * An opportunity to raise a File Download dialogue box for a known MIME type with binary format or suggest + * a filename for dynamic content. Quotes are necessary with special characters. + */ + public static final HeaderName CONTENT_DISPOSITION = HeaderNameEnum.CONTENT_DISPOSITION; + /** + * The {@code Content-Encoding} header name. + * The type of encoding used on the data. + */ + public static final HeaderName CONTENT_ENCODING = HeaderNameEnum.CONTENT_ENCODING; + /** + * The {@code Content-Language} header name. + * The natural language or languages of the intended audience for the enclosed content. + */ + public static final HeaderName CONTENT_LANGUAGE = HeaderNameEnum.CONTENT_LANGUAGE; + /** + * The {@code Content-Length} header name. + * The length of the response body in octets. + */ + public static final HeaderName CONTENT_LENGTH = HeaderNameEnum.CONTENT_LENGTH; + /** + * The {@code Content-Location} header name. + * An alternate location for the returned data. + */ + public static final HeaderName CONTENT_LOCATION = HeaderNameEnum.CONTENT_LOCATION; + /** + * The {@code Content-Range} header name. + * Where in a full body message this partial message belongs. + */ + public static final HeaderName CONTENT_RANGE = HeaderNameEnum.CONTENT_RANGE; + /** + * The {@code Content-Type} header name. + * The MIME type of this content. + */ + public static final HeaderName CONTENT_TYPE = HeaderNameEnum.CONTENT_TYPE; + /** + * The {@code Date} header name. + * The date and time that the message was sent (in HTTP-date format as defined by RFC 7231). + */ + public static final HeaderName DATE = HeaderNameEnum.DATE; + /** + * The {@code Etag} header name. + * An identifier for a specific version of a resource, often a message digest. + */ + public static final HeaderName ETAG = HeaderNameEnum.ETAG; + /** + * The {@code Expires} header name. + * Gives the date/time after which the response is considered stale (in HTTP-date format as defined by RFC 7231) + */ + public static final HeaderName EXPIRES = HeaderNameEnum.EXPIRES; + /** + * The {@code Last-Modified} header name. + * The last modified date for the requested object (in HTTP-date format as defined by RFC 7231) + */ + public static final HeaderName LAST_MODIFIED = HeaderNameEnum.LAST_MODIFIED; + /** + * The {@code Link} header name. + * Used to express a typed relationship with another resource, where the relation type is defined by RFC 5988. + */ + public static final HeaderName LINK = HeaderNameEnum.LINK; + /** + * The {@code Location} header name. + * Used in redirection, or whenRequest a new resource has been created. + */ + public static final HeaderName LOCATION = HeaderNameEnum.LOCATION; + /** + * The {@code Pragma} header name. + * Implementation-specific fields that may have various effects anywhere along the request-response chain. + */ + public static final HeaderName PRAGMA = HeaderNameEnum.PRAGMA; + /** + * The {@code Public-Key-Pins} header name. + * HTTP Public Key Pinning, announces hash of website's authentic TLS certificate. + */ + public static final HeaderName PUBLIC_KEY_PINS = HeaderNameEnum.PUBLIC_KEY_PINS; + /** + * The {@code {@value}} header name. + * If an entity is temporarily unavailable, this instructs the client to try again later. Value could be a specified + * period of time (in seconds) or an HTTP-date. + */ + public static final HeaderName RETRY_AFTER = HeaderNameEnum.RETRY_AFTER; + /** + * The {@code Server} header name. + * A name for the server. + */ + public static final HeaderName SERVER = HeaderNameEnum.SERVER; + /** + * The {@code Set-Cookie} header name. + * An HTTP cookie set directive. + */ + public static final HeaderName SET_COOKIE = HeaderNameEnum.SET_COOKIE; + /** + * The {@code Set-Cookie2} header name. + * An HTTP cookie set directive. + */ + public static final HeaderName SET_COOKIE2 = HeaderNameEnum.SET_COOKIE2; + /** + * The {@code Strict-Transport-Security} header name. + * A HSTS Policy informing The {@code HTTP client} how long to cache the HTTPS only policy and whether this applies to + * subdomains. + */ + public static final HeaderName STRICT_TRANSPORT_SECURITY = HeaderNameEnum.STRICT_TRANSPORT_SECURITY; + /** + * The {@code Trailer} header name. + * The Trailer general field value indicates that the given set of} header fields is present in the trailer of + * a message encoded with chunked transfer coding. + */ + public static final HeaderName TRAILER = HeaderNameEnum.TRAILER; + /** + * The {@code Transfer-Encoding} header name. + * The form of encoding used to safely transfer the entity to the user. Currently defined methods are: + * {@code chunked, compress, deflate, gzip, identity}. + */ + public static final HeaderName TRANSFER_ENCODING = HeaderNameEnum.TRANSFER_ENCODING; + /** + * The {@code Tsv} header name. + * Tracking Status Value, value suggested to be sent in response to a DNT(do-not-track). + */ + public static final HeaderName TSV = HeaderNameEnum.TSV; + /** + * The {@code Upgrade} header name. + * Ask to upgrade to another protocol. + */ + public static final HeaderName UPGRADE = HeaderNameEnum.UPGRADE; + /** + * The {@code Vary} header name. + * Tells downstream proxies how to match future request headers to decide whether the cached response can be used rather + * than requesting a fresh one from the origin server. + */ + public static final HeaderName VARY = HeaderNameEnum.VARY; + /** + * The {@code Warning} header name. + * A general warning about possible problems with the entity body. + */ + public static final HeaderName WARNING = HeaderNameEnum.WARNING; + /** + * The {@code WWW-Authenticate} header name. + * Indicates the authentication scheme that should be used to access the requested entity. + */ + public static final HeaderName WWW_AUTHENTICATE = HeaderNameEnum.WWW_AUTHENTICATE; + /** + * The {@code X_HELIDON_CN} header name. + * Corresponds to the certificate CN subject value when client authentication enabled. + * This header will be removed if it is part of the request. + */ + public static final HeaderName X_HELIDON_CN = HeaderNameEnum.X_HELIDON_CN; + /** + * The {@code X-Forwarded-For} header name. + * Represents the originating client and intervening proxies when the request has passed through one or more proxies. + */ + public static final HeaderName X_FORWARDED_FOR = HeaderNameEnum.X_FORWARDED_FOR; + /** + * The {@code X_FORWARDED_HOST} header name. + * Represents the host specified by the originating client when the request has passed through one or more proxies. + */ + public static final HeaderName X_FORWARDED_HOST = HeaderNameEnum.X_FORWARDED_HOST; + + /** + * The {@code X_FORWARDED_PORT} header name. + * Represents the port specified by the originating client when the request has passed through one or more proxies. + */ + public static final HeaderName X_FORWARDED_PORT = HeaderNameEnum.X_FORWARDED_PORT; + + /** + * The {@code X_FORWARDED_PREFIX} header name. + * Represents the path prefix to be applied to relative paths resolved against this request when the request has passed + * through one or more proxies. + */ + public static final HeaderName X_FORWARDED_PREFIX = HeaderNameEnum.X_FORWARDED_PREFIX; + /** + * The {@code X_FORWARDED_PROTO} header name. + * Represents the protocol specified by the originating client when the request has passed through one or more proxies. + */ + public static final HeaderName X_FORWARDED_PROTO = HeaderNameEnum.X_FORWARDED_PROTO; + + private HeaderNames() { + } + + /** + * Find or create a header name. + * If a known indexed header exists for the name, the instance is returned. + * Otherwise a new header name is created with the provided name. + * + * @param name default case to use for custom header names (header names not known by Helidon) + * @return header name instance + */ + public static HeaderName create(String name) { + HeaderName headerName = HeaderNameEnum.byCapitalizedName(name); + if (headerName == null) { + return new HeaderNameImpl(Ascii.toLowerCase(name), name); + } + return headerName; + } + + /** + * Find or create a header name. + * If a known indexed header exists for the lower case name, the instance is returned. + * Otherwise a new header name is created with the provided names. + * + * @param lowerCase lower case name + * @param defaultCase default case to use for custom header names (header names not known by Helidon) + * @return header name instance + */ + public static HeaderName create(String lowerCase, String defaultCase) { + HeaderName headerName = HeaderNameEnum.byName(lowerCase); + if (headerName == null) { + return new HeaderNameImpl(lowerCase, defaultCase); + } else { + return headerName; + } + } + + /** + * Create a header name from lower case letters. + * + * @param lowerCase lower case + * @return a new header name + */ + public static HeaderName createFromLowercase(String lowerCase) { + HeaderName headerName = HeaderNameEnum.byName(lowerCase); + if (headerName == null) { + return new HeaderNameImpl(lowerCase, lowerCase); + } else { + return headerName; + } + } + +} diff --git a/http/http/src/main/java/io/helidon/http/HeaderValueArray.java b/http/http/src/main/java/io/helidon/http/HeaderValueArray.java index f61cea5dcf8..7ce999dbe31 100644 --- a/http/http/src/main/java/io/helidon/http/HeaderValueArray.java +++ b/http/http/src/main/java/io/helidon/http/HeaderValueArray.java @@ -19,8 +19,6 @@ import java.util.ArrayList; import java.util.List; -import io.helidon.http.Http.HeaderName; - class HeaderValueArray extends HeaderValueBase { private final String[] originalValues; private List values; @@ -32,7 +30,7 @@ class HeaderValueArray extends HeaderValueBase { } @Override - public Http.HeaderValueWriteable addValue(String value) { + public HeaderWriteable addValue(String value) { if (values == null) { values = new ArrayList<>(originalValues.length + 1); values.addAll(List.of(originalValues)); diff --git a/http/http/src/main/java/io/helidon/http/HeaderValueBase.java b/http/http/src/main/java/io/helidon/http/HeaderValueBase.java index d2d57c788cc..ba12599a775 100644 --- a/http/http/src/main/java/io/helidon/http/HeaderValueBase.java +++ b/http/http/src/main/java/io/helidon/http/HeaderValueBase.java @@ -24,9 +24,8 @@ import io.helidon.common.mapper.MapperException; import io.helidon.common.mapper.MapperManager; import io.helidon.common.mapper.Value; -import io.helidon.http.Http.HeaderName; -abstract class HeaderValueBase implements Http.HeaderValueWriteable { +abstract class HeaderValueBase implements HeaderWriteable { private static final String[] QUALIFIER = new String[] {"http", "header"}; private final HeaderName name; private final String actualName; @@ -43,7 +42,7 @@ abstract class HeaderValueBase implements Http.HeaderValueWriteable { } @Override - public abstract Http.HeaderValueWriteable addValue(String value); + public abstract HeaderWriteable addValue(String value); @Override public String name() { diff --git a/http/http/src/main/java/io/helidon/http/HeaderValueCached.java b/http/http/src/main/java/io/helidon/http/HeaderValueCached.java index 715f0120ee4..e97baf4fb5a 100644 --- a/http/http/src/main/java/io/helidon/http/HeaderValueCached.java +++ b/http/http/src/main/java/io/helidon/http/HeaderValueCached.java @@ -26,7 +26,7 @@ class HeaderValueCached extends HeaderValueBase { private final String value; private final byte[] cachedHttp1Header; - HeaderValueCached(Http.HeaderName name, boolean changing, boolean sensitive, byte[] cached, String value) { + HeaderValueCached(HeaderName name, boolean changing, boolean sensitive, byte[] cached, String value) { super(name, changing, sensitive, value); this.value = value; @@ -55,7 +55,7 @@ public void writeHttp1Header(BufferData buffer) { } @Override - public Http.HeaderValueWriteable addValue(String value) { + public HeaderWriteable addValue(String value) { throw new UnsupportedOperationException("Cannot change values of a cached header " + name()); } diff --git a/http/http/src/main/java/io/helidon/http/HeaderValueCopy.java b/http/http/src/main/java/io/helidon/http/HeaderValueCopy.java index 9692c0ebccb..e833bedf65d 100644 --- a/http/http/src/main/java/io/helidon/http/HeaderValueCopy.java +++ b/http/http/src/main/java/io/helidon/http/HeaderValueCopy.java @@ -20,17 +20,17 @@ import java.util.List; class HeaderValueCopy extends HeaderValueBase { - private final Http.Header original; + private final Header original; private List values; - HeaderValueCopy(Http.Header header) { + HeaderValueCopy(Header header) { super(header.headerName(), header.changing(), header.sensitive(), header.get()); this.original = header; } @Override - public Http.HeaderValueWriteable addValue(String value) { + public HeaderWriteable addValue(String value) { if (values == null) { values = new ArrayList<>(original.allValues()); } diff --git a/http/http/src/main/java/io/helidon/http/HeaderValueLazy.java b/http/http/src/main/java/io/helidon/http/HeaderValueLazy.java index ab23cfd6665..25a5d25bd13 100644 --- a/http/http/src/main/java/io/helidon/http/HeaderValueLazy.java +++ b/http/http/src/main/java/io/helidon/http/HeaderValueLazy.java @@ -25,14 +25,14 @@ class HeaderValueLazy extends HeaderValueBase { private final LazyString value; private List values; - HeaderValueLazy(Http.HeaderName name, boolean changing, boolean sensitive, LazyString value) { + HeaderValueLazy(HeaderName name, boolean changing, boolean sensitive, LazyString value) { super(name, changing, sensitive, null); this.value = value; } @Override - public Http.HeaderValueWriteable addValue(String value) { + public HeaderWriteable addValue(String value) { if (values == null) { values = new ArrayList<>(2); values.add(this.value.stripOws()); diff --git a/http/http/src/main/java/io/helidon/http/HeaderValueList.java b/http/http/src/main/java/io/helidon/http/HeaderValueList.java index af7ca5b8e4c..933b606bc3a 100644 --- a/http/http/src/main/java/io/helidon/http/HeaderValueList.java +++ b/http/http/src/main/java/io/helidon/http/HeaderValueList.java @@ -23,14 +23,14 @@ class HeaderValueList extends HeaderValueBase { private List values; - HeaderValueList(Http.HeaderName name, boolean changing, boolean sensitive, Collection values) { + HeaderValueList(HeaderName name, boolean changing, boolean sensitive, Collection values) { super(name, changing, sensitive, values.iterator().next()); this.values = new ArrayList<>(values); } @Override - public Http.HeaderValueWriteable addValue(String value) { + public HeaderWriteable addValue(String value) { values.add(value); return this; } diff --git a/http/http/src/main/java/io/helidon/http/HeaderValueSingle.java b/http/http/src/main/java/io/helidon/http/HeaderValueSingle.java index 6a2ecb8b426..305dab2fc43 100644 --- a/http/http/src/main/java/io/helidon/http/HeaderValueSingle.java +++ b/http/http/src/main/java/io/helidon/http/HeaderValueSingle.java @@ -23,14 +23,14 @@ class HeaderValueSingle extends HeaderValueBase { private final String value; private List values; - HeaderValueSingle(Http.HeaderName name, boolean changing, boolean sensitive, String value) { + HeaderValueSingle(HeaderName name, boolean changing, boolean sensitive, String value) { super(name, changing, sensitive, value); this.value = value; } @Override - public Http.HeaderValueWriteable addValue(String value) { + public HeaderWriteable addValue(String value) { if (values == null) { values = new ArrayList<>(2); values.add(this.value); diff --git a/http/http/src/main/java/io/helidon/http/HeaderValues.java b/http/http/src/main/java/io/helidon/http/HeaderValues.java new file mode 100644 index 00000000000..dd94a19c429 --- /dev/null +++ b/http/http/src/main/java/io/helidon/http/HeaderValues.java @@ -0,0 +1,392 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.http; + +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.Objects; + +import io.helidon.common.buffers.LazyString; + +/** + * Values of commonly used headers. + */ +public final class HeaderValues { + /** + * Accept byte ranges for file download. + */ + public static final Header ACCEPT_RANGES_BYTES = createCached(HeaderNames.ACCEPT_RANGES, "bytes"); + /** + * Not accepting byte ranges for file download. + */ + public static final Header ACCEPT_RANGES_NONE = createCached(HeaderNames.ACCEPT_RANGES, "none"); + /** + * Chunked transfer encoding. + * Used in {@code HTTP/1}. + */ + public static final Header TRANSFER_ENCODING_CHUNKED = createCached(HeaderNames.TRANSFER_ENCODING, "chunked"); + /** + * Connection keep-alive. + * Used in {@code HTTP/1}. + */ + public static final Header CONNECTION_KEEP_ALIVE = createCached(HeaderNames.CONNECTION, "keep-alive"); + /** + * Connection close. + * Used in {@code HTTP/1}. + */ + public static final Header CONNECTION_CLOSE = createCached(HeaderNames.CONNECTION, "close"); + /** + * Content type application/json with no charset. + */ + public static final Header CONTENT_TYPE_JSON = createCached(HeaderNames.CONTENT_TYPE, "application/json"); + /** + * Content type text plain with no charset. + */ + public static final Header CONTENT_TYPE_TEXT_PLAIN = createCached(HeaderNames.CONTENT_TYPE, "text/plain"); + /** + * Content type octet stream. + */ + public static final Header CONTENT_TYPE_OCTET_STREAM = createCached(HeaderNames.CONTENT_TYPE, + "application/octet-stream"); + /** + * Content type SSE event stream. + */ + public static final Header CONTENT_TYPE_EVENT_STREAM = createCached(HeaderNames.CONTENT_TYPE, + "text/event-stream"); + + /** + * Accept application/json. + */ + public static final Header ACCEPT_JSON = createCached(HeaderNames.ACCEPT, "application/json"); + /** + * Accept text/plain with UTF-8. + */ + public static final Header ACCEPT_TEXT = createCached(HeaderNames.ACCEPT, "text/plain;charset=UTF-8"); + /** + * Accept text/event-stream. + */ + public static final Header ACCEPT_EVENT_STREAM = createCached(HeaderNames.ACCEPT, "text/event-stream"); + /** + * Expect 100 header. + */ + public static final Header EXPECT_100 = createCached(HeaderNames.EXPECT, "100-continue"); + /** + * Content length with 0 value. + */ + public static final Header CONTENT_LENGTH_ZERO = createCached(HeaderNames.CONTENT_LENGTH, "0"); + /** + * Cache control without any caching. + */ + public static final Header CACHE_NO_CACHE = create(HeaderNames.CACHE_CONTROL, "no-cache", + "no-store", + "must-revalidate", + "no-transform"); + /** + * Cache control that allows caching with no transform. + */ + public static final Header CACHE_NORMAL = createCached(HeaderNames.CACHE_CONTROL, "no-transform"); + + /** + * TE header set to {@code trailers}, used to enable trailer headers. + */ + public static final Header TE_TRAILERS = createCached(HeaderNames.TE, "trailers"); + + private HeaderValues() { + } + + /** + * Create and cache byte value. + * Use this method if the header value is stored in a constant, or used repeatedly. + * + * @param name header name + * @param value value of the header + * @return a new header + */ + public static Header createCached(String name, String value) { + return createCached(HeaderNames.create(name), value); + } + + /** + * Create and cache byte value. + * Use this method if the header value is stored in a constant, or used repeatedly. + * + * @param name header name + * @param value value of the header + * @return a new header + */ + public static Header createCached(String name, int value) { + return createCached(HeaderNames.create(name), value); + } + + /** + * Create and cache byte value. + * Use this method if the header value is stored in a constant, or used repeatedly. + * + * @param name header name + * @param value value of the header + * @return a new header + */ + public static Header createCached(String name, long value) { + return createCached(HeaderNames.create(name), value); + } + + /** + * Create and cache byte value. + * Use this method if the header value is stored in a constant, or used repeatedly. + * + * @param name header name + * @param value value of the header + * @return a new header + */ + public static Header createCached(HeaderName name, String value) { + return new HeaderValueCached(name, false, + false, + value.getBytes(StandardCharsets.US_ASCII), + value); + } + + /** + * Create and cache byte value. + * Use this method if the header value is stored in a constant, or used repeatedly. + * + * @param name header name + * @param value value of the header + * @return a new header + */ + public static Header createCached(HeaderName name, int value) { + return createCached(name, String.valueOf(value)); + } + + /** + * Create and cache byte value. + * Use this method if the header value is stored in a constant, or used repeatedly. + * + * @param name header name + * @param value value of the header + * @return a new header + */ + public static Header createCached(HeaderName name, long value) { + return createCached(name, String.valueOf(value)); + } + + /** + * Create a new header with a single value. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param value lazy string with the value + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(HeaderName name, LazyString value) { + Objects.requireNonNull(name); + Objects.requireNonNull(value); + + return new HeaderValueLazy(name, false, false, value); + } + + /** + * Create a new header with a single value. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param value integer value of the header + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(HeaderName name, int value) { + Objects.requireNonNull(name); + + return new HeaderValueSingle(name, false, false, String.valueOf(value)); + } + + /** + * Create a new header with a single value. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param value long value of the header + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(HeaderName name, long value) { + Objects.requireNonNull(name); + + return new HeaderValueSingle(name, false, false, String.valueOf(value)); + } + + /** + * Create a new header with a single value. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param value value of the header + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(HeaderName name, String value) { + Objects.requireNonNull(name, "HeaderName must not be null"); + Objects.requireNonNull(value, "HeaderValue must not be null"); + + return new HeaderValueSingle(name, + false, + false, + value); + } + + /** + * Create a new header with a single value. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param value value of the header + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(String name, String value) { + Objects.requireNonNull(name, "Header name must not be null"); + + return create(HeaderNames.create(name), value); + } + + /** + * Create a new header with a single value. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param value value of the header + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(String name, int value) { + Objects.requireNonNull(name, "Header name must not be null"); + + return create(HeaderNames.create(name), value); + } + + /** + * Create a new header with a single value. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param value value of the header + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(String name, long value) { + Objects.requireNonNull(name, "Header name must not be null"); + + return create(HeaderNames.create(name), value); + } + + /** + * Create a new header. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param values values of the header + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(HeaderName name, String... values) { + if (values.length == 0) { + throw new IllegalArgumentException("Cannot create a header without a value. Header: " + name); + } + return new HeaderValueArray(name, false, false, values); + } + + /** + * Create a new header. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param values values of the header + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(String name, String... values) { + return create(HeaderNames.create(name), values); + } + + /** + * Create a new header. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param values values of the header + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(HeaderName name, Collection values) { + return new HeaderValueList(name, false, false, values); + } + + /** + * Create a new header. This header is considered unchanging and not sensitive. + * + * @param name name of the header + * @param values values of the header + * @return a new header + * @see #create(io.helidon.http.HeaderName, boolean, boolean, String...) + */ + public static Header create(String name, Collection values) { + return create(HeaderNames.create(name), values); + } + + /** + * Create and cache byte value. + * Use this method if the header value is stored in a constant, or used repeatedly. + * + * @param name header name + * @param changing whether the value is changing often (to disable caching for HTTP/2) + * @param sensitive whether the value is sensitive (to disable caching for HTTP/2) + * @param value value of the header + * @return a new header + */ + public static Header createCached(HeaderName name, boolean changing, boolean sensitive, String value) { + return new HeaderValueCached(name, changing, sensitive, value.getBytes(StandardCharsets.UTF_8), value); + } + + /** + * Create a new header. + * + * @param name name of the header + * @param changing whether the value is changing often (to disable caching for HTTP/2) + * @param sensitive whether the value is sensitive (to disable caching for HTTP/2) + * @param values value(s) of the header + * @return a new header + */ + public static Header create(HeaderName name, boolean changing, boolean sensitive, String... values) { + return new HeaderValueArray(name, changing, sensitive, values); + } + + /** + * Create a new header. + * + * @param name name of the header + * @param changing whether the value is changing often (to disable caching for HTTP/2) + * @param sensitive whether the value is sensitive (to disable caching for HTTP/2) + * @param value value of the header + * @return a new header + */ + public static Header create(HeaderName name, boolean changing, boolean sensitive, int value) { + return create(name, changing, sensitive, String.valueOf(value)); + } + + /** + * Create a new header. + * + * @param name name of the header + * @param changing whether the value is changing often (to disable caching for HTTP/2) + * @param sensitive whether the value is sensitive (to disable caching for HTTP/2) + * @param value value of the header + * @return a new header + */ + public static Header create(HeaderName name, boolean changing, boolean sensitive, long value) { + return create(name, changing, sensitive, String.valueOf(value)); + } +} diff --git a/http/http/src/main/java/io/helidon/http/HeaderWriteable.java b/http/http/src/main/java/io/helidon/http/HeaderWriteable.java new file mode 100644 index 00000000000..27c4a9ff262 --- /dev/null +++ b/http/http/src/main/java/io/helidon/http/HeaderWriteable.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.http; + +/** + * Mutable header value. + */ +public interface HeaderWriteable extends Header { + /** + * Create a new mutable header from an existing header. + * + * @param header header to copy + * @return a new mutable header + */ + static HeaderWriteable create(Header header) { + return new HeaderValueCopy(header); + } + + /** + * Add a value to this header. + * + * @param value value to add + * @return this instance + */ + HeaderWriteable addValue(String value); +} diff --git a/http/http/src/main/java/io/helidon/http/Headers.java b/http/http/src/main/java/io/helidon/http/Headers.java index 973f3be4ca1..4cc13f2b5ae 100644 --- a/http/http/src/main/java/io/helidon/http/Headers.java +++ b/http/http/src/main/java/io/helidon/http/Headers.java @@ -35,11 +35,11 @@ * case. * When you configure headers to be sent using HTTP/2, all names will be lowercase. * When you configure headers to be sent using HTTP/1, names will be sent as configured. - * When you receive headers, the stored values (as can be obtained by {@link io.helidon.http.Http.Header#name()}) + * When you receive headers, the stored values (as can be obtained by {@link Header#name()}) * will be as sent on the transport. These value will be available using any cased names (though performance may be worse * if uppercase letters are used to obtain HTTP/2 headers). */ -public interface Headers extends Iterable { +public interface Headers extends Iterable

{ /** * Get all values of a header. * @@ -47,7 +47,7 @@ public interface Headers extends Iterable { * @param defaultSupplier supplier to obtain default values if the header is not present * @return list of header values */ - List all(Http.HeaderName name, Supplier> defaultSupplier); + List all(HeaderName name, Supplier> defaultSupplier); /** * Whether these headers contain a header with the provided name. @@ -55,7 +55,7 @@ public interface Headers extends Iterable { * @param name header name * @return {@code true} if the header is defined */ - boolean contains(Http.HeaderName name); + boolean contains(HeaderName name); /** * Whether these headers contain a header with the provided name and value. @@ -63,7 +63,7 @@ public interface Headers extends Iterable { * @param value value of the header * @return {@code true} if the header is defined */ - boolean contains(Http.Header value); + boolean contains(Header value); /** * Get a header value. @@ -72,11 +72,11 @@ public interface Headers extends Iterable { * @return value if present * @throws java.util.NoSuchElementException in case the header is not present */ - Http.Header get(Http.HeaderName name); + Header get(HeaderName name); /** * Returns a header value as a single {@link String} potentially concatenated using comma character - * from {@link #all(io.helidon.http.Http.HeaderName, java.util.function.Supplier)} header fields. + * from {@link #all(HeaderName, java.util.function.Supplier)} header fields. *

* According to RFC2616, Message Headers: *

@@ -92,10 +92,10 @@ public interface Headers extends Iterable { * @param headerName the header name * @return all header values concatenated using comma separator * @throws NullPointerException if {@code headerName} is {@code null} - * @see #all(io.helidon.http.Http.HeaderName, java.util.function.Supplier) - * @see #values(io.helidon.http.Http.HeaderName) + * @see #all(HeaderName, java.util.function.Supplier) + * @see #values(HeaderName) */ - default Optional value(Http.HeaderName headerName) { + default Optional value(HeaderName headerName) { if (contains(headerName)) { List hdrs = all(headerName, List::of); return Optional.of(String.join(",", hdrs)); @@ -110,7 +110,7 @@ default Optional value(Http.HeaderName headerName) { * @return the first value * @throws NullPointerException if {@code headerName} is {@code null} */ - default Optional first(Http.HeaderName headerName) { + default Optional first(HeaderName headerName) { if (contains(headerName)) { return Optional.of(get(headerName).get()); } @@ -130,10 +130,10 @@ default Optional first(Http.HeaderName headerName) { * @param headerName the header name * @return a {@code List} of values with zero or greater size, never {@code null} * @throws NullPointerException if {@code headerName} is {@code null} - * @see #all(io.helidon.http.Http.HeaderName, java.util.function.Supplier) - * @see #value(io.helidon.http.Http.HeaderName) + * @see #all(HeaderName, java.util.function.Supplier) + * @see #value(HeaderName) */ - default List values(Http.HeaderName headerName) { + default List values(HeaderName headerName) { return all(headerName, List::of) .stream() .flatMap(val -> Utils.tokenize(',', "\"", true, val).stream()) @@ -144,7 +144,7 @@ default List values(Http.HeaderName headerName) { * Content length if defined. * * @return content length or empty if not defined - * @see io.helidon.http.Http.HeaderNames#CONTENT_LENGTH + * @see HeaderNames#CONTENT_LENGTH */ default OptionalLong contentLength() { if (contains(HeaderNameEnum.CONTENT_LENGTH)) { @@ -157,7 +157,7 @@ default OptionalLong contentLength() { * Content type (if defined). * * @return content type, empty if content type is not present - * @see io.helidon.http.Http.HeaderNames#CONTENT_TYPE + * @see HeaderNames#CONTENT_TYPE */ default Optional contentType() { if (contains(HeaderNameEnum.CONTENT_TYPE)) { @@ -175,7 +175,7 @@ default Optional contentType() { int size(); /** - * Returns a list of acceptedTypes ({@link io.helidon.http.Http.HeaderNames#ACCEPT} header) content discoveryTypes in + * Returns a list of acceptedTypes ({@link HeaderNames#ACCEPT} header) content discoveryTypes in * quality factor order. Never {@code null}. * Returns an empty list by default. * @@ -215,7 +215,7 @@ default Map> toMap() { * * @return stream of header values */ - default Stream stream() { + default Stream
stream() { return StreamSupport.stream(spliterator(), false); } } diff --git a/http/http/src/main/java/io/helidon/http/HeadersImpl.java b/http/http/src/main/java/io/helidon/http/HeadersImpl.java index 1fadbf0d323..5cfc73718bc 100644 --- a/http/http/src/main/java/io/helidon/http/HeadersImpl.java +++ b/http/http/src/main/java/io/helidon/http/HeadersImpl.java @@ -27,19 +27,15 @@ import java.util.function.Consumer; import java.util.function.Supplier; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderName; -import io.helidon.http.Http.HeaderValueWriteable; - @SuppressWarnings("unchecked") class HeadersImpl> implements WritableHeaders { static final int KNOWN_HEADER_SIZE = HeaderNameEnum.values().length; /* Optimization for most commonly used header names */ - private final Header[] knownHeaders = new Http.Header[KNOWN_HEADER_SIZE]; + private final Header[] knownHeaders = new Header[KNOWN_HEADER_SIZE]; // custom (unknown) headers are slower - private final Map customHeaders = new HashMap<>(); + private final Map customHeaders = new HashMap<>(); private IntSet knownHeaderIndices = new IntSet(KNOWN_HEADER_SIZE); HeadersImpl() { @@ -66,8 +62,8 @@ public boolean contains(HeaderName name) { } @Override - public boolean contains(Http.Header headerWithValue) { - Http.Header headerValue = find(headerWithValue.headerName()); + public boolean contains(Header headerWithValue) { + Header headerValue = find(headerWithValue.headerName()); if (headerValue == null) { return false; } @@ -79,7 +75,7 @@ public boolean contains(Http.Header headerWithValue) { } @Override - public Http.Header get(HeaderName name) { + public Header get(HeaderName name) { Header headerValue = find(name); if (headerValue == null) { throw new NoSuchElementException("Header " + name + " is not present in these headers"); @@ -94,8 +90,8 @@ public int size() { @Override public List acceptedTypes() { - if (contains(Http.HeaderNames.ACCEPT)) { - List accepts = get(Http.HeaderNames.ACCEPT).allValues(true); + if (contains(HeaderNames.ACCEPT)) { + List accepts = get(HeaderNames.ACCEPT).allValues(true); List mediaTypes = new ArrayList<>(accepts.size()); for (String accept : accepts) { @@ -109,13 +105,13 @@ public List acceptedTypes() { } @Override - public Iterator iterator() { + public Iterator
iterator() { return new HeaderIterator(); } @Override public T setIfAbsent(Header header) { - Http.Header found = find(header.headerName()); + Header found = find(header.headerName()); if (found == null) { set(header); } @@ -126,16 +122,16 @@ public T setIfAbsent(Header header) { @Override public T add(Header header) { HeaderName name = header.headerName(); - Http.Header headerValue = find(name); + Header headerValue = find(name); if (headerValue == null) { set(header); } else { - HeaderValueWriteable writable; + HeaderWriteable writable; - if (headerValue instanceof HeaderValueWriteable hvw) { + if (headerValue instanceof HeaderWriteable hvw) { writable = hvw; } else { - writable = HeaderValueWriteable.create(header); + writable = HeaderWriteable.create(header); } for (String value : header.allValues()) { writable.addValue(value); @@ -152,8 +148,8 @@ public T remove(HeaderName name) { } @Override - public T remove(HeaderName name, Consumer removedConsumer) { - Http.Header remove = doRemove(name); + public T remove(HeaderName name, Consumer
removedConsumer) { + Header remove = doRemove(name); if (remove != null) { removedConsumer.accept(remove); } @@ -161,11 +157,11 @@ public T remove(HeaderName name, Consumer removedConsumer) { } @Override - public T set(Http.Header header) { + public T set(Header header) { HeaderName name = header.headerName(); Header usedHeader = header; - if (header instanceof HeaderValueWriteable) { + if (header instanceof HeaderWriteable) { // we must create a new instance, as we risk modifying state of the provided header usedHeader = new HeaderValueCopy(header); } @@ -199,7 +195,7 @@ public T from(Headers headers) { public String toString() { StringBuilder builder = new StringBuilder(); - for (Http.Header headerValue : this) { + for (Header headerValue : this) { for (String value : headerValue.allValues()) { builder.append(headerValue.name()) .append(": "); @@ -230,7 +226,7 @@ public String toString() { public Header doRemove(HeaderName name) { if (name instanceof HeaderNameEnum) { int index = ((HeaderNameEnum) name).ordinal(); - Http.Header value = knownHeaders[index]; + Header value = knownHeaders[index]; knownHeaders[index] = null; knownHeaderIndices.remove(index); return value; diff --git a/http/http/src/main/java/io/helidon/http/Http.java b/http/http/src/main/java/io/helidon/http/Http.java index 19b9ca37119..372b025d7c7 100644 --- a/http/http/src/main/java/io/helidon/http/Http.java +++ b/http/http/src/main/java/io/helidon/http/Http.java @@ -16,1879 +16,23 @@ package io.helidon.http; -import java.nio.charset.StandardCharsets; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.function.Predicate; - -import io.helidon.common.buffers.Ascii; -import io.helidon.common.buffers.BufferData; -import io.helidon.common.buffers.LazyString; -import io.helidon.common.mapper.Value; - /** - * HTTP protocol related constants and utilities. - *

- * Utility class + * All types from this class are moved to top-level classes. + * This "container" class will be reused later, kept here for deprecation purposes to point to the right place + * for the time being. + * + * @deprecated please use the top level classes in this package + * @see io.helidon.http.Method + * @see io.helidon.http.Status + * @see io.helidon.http.HeaderName + * @see io.helidon.http.HeaderNames + * @see io.helidon.http.Header + * @see io.helidon.http.HeaderWriteable + * @see io.helidon.http.HeaderValues + * @see io.helidon.http.DateTime */ +@Deprecated(since = "4.0.0") public final class Http { - private Http() { } - - /** - * Interface representing an HTTP request method, all standard methods are in {@link io.helidon.http.Http.Method} - * enumeration. - *

- * Although the constants are instances of this class, they can be compared using instance equality, as the only - * way to obtain an instance is through method {@link #create(String)}, which ensures the same instance is returned for - * known methods. - *

- * Methods that are not known (e.g. there is no constant for them) must be compared using {@link #equals(Object)} as usual. - * - * @see io.helidon.http.Http.Method - */ - public static final class Method { - private static final String GET_STRING = "GET"; - /** - * The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. - * If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity - * in the response and not the source text of the process, unless that text happens to be the output of the tryProcess. - */ - public static final Method GET = new Method(GET_STRING, true); - /** - * The POST method is used to request that the origin server acceptedTypes the entity enclosed in the request - * as a new subordinate of the resource identified by the Request-URI in the Request-Line. - * The actual function performed by the POST method is determined by the server and is usually dependent on the - * Request-URI. The posted entity is subordinate to that URI in the same way that a file is subordinate to a directory - * containing it, a news article is subordinate to a newsgroup to which it is posted, or a record is subordinate - * to a database. - */ - public static final Method POST = new Method("POST", true); - /** - * The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers - * to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing - * on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being - * defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. - * If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. - * If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate - * successful completion of the request. If the resource could not be created or modified with the Request-URI, - * an appropriate error response SHOULD be given that reflects the nature of the problem. The recipient of the entity - * MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return - * a 501 (Not Implemented) response in such cases. - */ - public static final Method PUT = new Method("PUT", true); - /** - * The DELETE method requests that the origin server delete the resource identified by the Request-URI. - * This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot - * be guaranteed that the operation has been carried out, even if the status code returned from the origin server - * indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, - * at the time the response is given, it intends to delete the resource or move it to an inaccessible location. - */ - public static final Method DELETE = new Method("DELETE", true); - /** - * The HEAD method is identical to {@link #GET} except that the server MUST NOT return a message-body in the response. - * The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information - * sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied - * by the request without transferring the entity-body itself. This method is often used for testing hypertext links - * for validity, accessibility, and recent modification. - */ - public static final Method HEAD = new Method("HEAD", true); - /** - * The OPTIONS method represents a request for information about the communication options available - * on the request/response chain identified by the Request-URI. This method allows the client to determine the options - * and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action - * or initiating a resource retrieval. - */ - public static final Method OPTIONS = new Method("OPTIONS", true); - /** - * The TRACE method is used to invoke a remote, application-layer loop- back of the request message. - * The final recipient of the request SHOULD reflect the message received back to the client as the entity-body - * of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive - * a Max-Forwards value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity. - */ - public static final Method TRACE = new Method("TRACE", true); - /** - * The PATCH method as described in RFC 5789 is used to perform an update to an existing resource, where the request - * payload only has to contain the instructions on how to perform the update. This is in contrast to PUT which - * requires that the payload contains the new version of the resource. - * If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate - * successful completion of the request. - */ - public static final Method PATCH = new Method("PATCH", true); - - /** - * The HTTP CONNECT method starts two-way communications with the requested resource. It can be used to open a tunnel. - */ - public static final Method CONNECT = new Method("CONNECT", true); - - static { - // THIS MUST BE AFTER THE LAST CONSTANT - MethodHelper.methodsDone(); - } - - private final String name; - private final int length; - - private final boolean instance; - - private Method(String name, boolean instance) { - this.name = name; - this.length = name.length(); - this.instance = instance; - - if (instance) { - MethodHelper.add(this); - } - } - - /** - * Create new HTTP request method instance from the provided name. - *

- * In case the method name is recognized as one of the {@link io.helidon.http.Http.Method standard HTTP methods}, - * the respective enumeration - * value is returned. - * - * @param name the method name. Must not be {@code null} or empty and must be a legal HTTP method name string. - * @return HTTP request method instance representing an HTTP method with the provided name. - * @throws IllegalArgumentException In case of illegal method name or in case the name is empty or {@code null}. - */ - public static Method create(String name) { - if (name.equals(GET_STRING)) { - return GET; - } - - String methodName = Ascii.toUpperCase(name); - - Method method = MethodHelper.byName(methodName); - if (method == null) { - // validate that it only contains characters allowed by a method - HttpToken.validate(methodName); - return new Method(methodName, false); - } - return method; - } - - /** - * Create a predicate for the provided methods. - * - * @param methods methods to check against - * @return a predicate that will validate the method is one of the methods provided; if methods are empty, the predicate - * will always return {@code true} - */ - public static MethodPredicate predicate(Method... methods) { - return switch (methods.length) { - case 0 -> MethodPredicates.TruePredicate.get(); - case 1 -> methods[0].instance - ? new MethodPredicates.SingleMethodEnumPredicate(methods[0]) - : new MethodPredicates.SingleMethodPredicate(methods[0]); - default -> new MethodPredicates.MethodsPredicate(methods); - }; - } - - /** - * Create a predicate for the provided methods. - * - * @param methods methods to check against - * @return a predicate that will validate the method is one of the methods provided; if methods are empty, the predicate - * will always return {@code true} - */ - public static MethodPredicate predicate(Collection methods) { - switch (methods.size()) { - case 0: - return MethodPredicates.TruePredicate.get(); - case 1: - Method first = methods.iterator().next(); - return first.instance - ? new MethodPredicates.SingleMethodEnumPredicate(first) - : new MethodPredicates.SingleMethodPredicate(first); - - default: - return new MethodPredicates.MethodsPredicate(methods.toArray(new Method[0])); - } - } - - /** - * Name of the method (such as {@code GET} or {@code POST}). - * - * @return a method name. - * @deprecated use {@link #text()} instead, this method conflicts with enum - */ - @Deprecated - public String name() { - return text(); - } - - /** - * Name of the method (such as {@code GET} or {@code POST}). - * - * @return a method name. - */ - public String text() { - return name; - } - - /** - * Number of characters. - * - * @return number of characters of this method - */ - public int length() { - return length; - } - - @Override - public String toString() { - return text(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Method method = (Method) o; - return name.equals(method.name); - } - - @Override - public int hashCode() { - return Objects.hash(name); - } - } - - /** - * HTTP Method predicate. - */ - public interface MethodPredicate extends Predicate { - /** - * Methods accepted by this predicate, may be empty. - * - * @return set of methods accepted - */ - Set acceptedMethods(); - } - - /** - * Commonly used status codes defined by HTTP, see - * HTTP/1.1 documentation. - * Additional status codes can be added by applications - * by call {@link #create(int)} or {@link #create(int, String)} with unkown status code, or with text - * that differs from the predefined status codes. - *

- * Although the constants are instances of this class, they can be compared using instance equality, as the only - * way to obtain an instance is through methods {@link #create(int)} {@link #create(int, String)}, which ensures - * the same instance is returned for known status codes and reason phrases. - *

- * A good reference is the IANA list of HTTP Status Codes (we may not cover all of them in this type): - * IANA HTTP Status Codes - */ - public static class Status { - /** - * 100 Continue, - * see HTTP/1.1 documentations. - */ - public static final Status CONTINUE_100 = new Status(100, "Continue", true); - /** - * 101 Switching Protocols, - * see HTTP/1.1 documentations. - */ - public static final Status SWITCHING_PROTOCOLS_101 = new Status(101, "Switching Protocols", true); - /** - * 200 OK, see HTTP/1.1 documentation. - */ - public static final Status OK_200 = new Status(200, "OK", true); - /** - * 201 Created, see HTTP/1.1 documentation. - */ - public static final Status CREATED_201 = new Status(201, "Created", true); - /** - * 202 Accepted, see HTTP/1.1 documentation - * . - */ - public static final Status ACCEPTED_202 = new Status(202, "Accepted", true); - /** - * 204 No Content, see - * HTTP/1.1 documentation. - */ - public static final Status NO_CONTENT_204 = new Status(204, "No Content", true); - /** - * 205 Reset Content, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status RESET_CONTENT_205 = new Status(205, "Reset Content", true); - /** - * 206 Reset Content, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status PARTIAL_CONTENT_206 = new Status(206, "Partial Content", true); - /** - * 301 Moved Permanently, see - * HTTP/1.1 documentation. - */ - public static final Status MOVED_PERMANENTLY_301 = new Status(301, "Moved Permanently", true); - /** - * 302 Found, see HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status FOUND_302 = new Status(302, "Found", true); - /** - * 303 See Other, see - * HTTP/1.1 documentation. - */ - public static final Status SEE_OTHER_303 = new Status(303, "See Other", true); - /** - * 304 Not Modified, see - * HTTP/1.1 documentation. - */ - public static final Status NOT_MODIFIED_304 = new Status(304, "Not Modified", true); - /** - * 305 Use Proxy, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status USE_PROXY_305 = new Status(305, "Use Proxy", true); - /** - * 307 Temporary Redirect, see - * HTTP/1.1 documentation. - */ - public static final Status TEMPORARY_REDIRECT_307 = new Status(307, "Temporary Redirect", true); - /** - * 308 Permanent Redirect, see - * HTTP Status Code 308 documentation. - */ - public static final Status PERMANENT_REDIRECT_308 = new Status(308, "Permanent Redirect", true); - /** - * 400 Bad Request, see - * HTTP/1.1 documentation. - */ - public static final Status BAD_REQUEST_400 = new Status(400, "Bad Request", true); - /** - * 401 Unauthorized, see - * HTTP/1.1 documentation. - */ - public static final Status UNAUTHORIZED_401 = new Status(401, "Unauthorized", true); - /** - * 402 Payment Required, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status PAYMENT_REQUIRED_402 = new Status(402, "Payment Required", true); - /** - * 403 Forbidden, see - * HTTP/1.1 documentation. - */ - public static final Status FORBIDDEN_403 = new Status(403, "Forbidden", true); - /** - * 404 Not Found, see - * HTTP/1.1 documentation. - */ - public static final Status NOT_FOUND_404 = new Status(404, "Not Found", true); - /** - * 405 Method Not Allowed, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status METHOD_NOT_ALLOWED_405 = new Status(405, "Method Not Allowed", true); - /** - * 406 Not Acceptable, see - * HTTP/1.1 documentation. - */ - public static final Status NOT_ACCEPTABLE_406 = new Status(406, "Not Acceptable", true); - /** - * 407 Proxy Authentication Required, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status PROXY_AUTHENTICATION_REQUIRED_407 = new Status(407, "Proxy Authentication Required", true); - /** - * 408 Request Timeout, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status REQUEST_TIMEOUT_408 = new Status(408, "Request Timeout", true); - /** - * 409 Conflict, see - * HTTP/1.1 documentation. - */ - public static final Status CONFLICT_409 = new Status(409, "Conflict", true); - /** - * 410 Gone, see HTTP/1.1 documentation. - */ - public static final Status GONE_410 = new Status(410, "Gone", true); - /** - * 411 Length Required, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status LENGTH_REQUIRED_411 = new Status(411, "Length Required", true); - /** - * 412 Precondition Failed, see - * HTTP/1.1 documentation. - */ - public static final Status PRECONDITION_FAILED_412 = new Status(412, "Precondition Failed", true); - /** - * 413 Request Entity Too Large, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status REQUEST_ENTITY_TOO_LARGE_413 = new Status(413, "Request Entity Too Large", true); - /** - * 414 Request-URI Too Long, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status REQUEST_URI_TOO_LONG_414 = new Status(414, "Request-URI Too Long", true); - /** - * 415 Unsupported Media Type, see - * HTTP/1.1 documentation. - */ - public static final Status UNSUPPORTED_MEDIA_TYPE_415 = new Status(415, "Unsupported Media Type", true); - /** - * 416 Requested Range Not Satisfiable, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status REQUESTED_RANGE_NOT_SATISFIABLE_416 = new Status(416, "Requested Range Not Satisfiable", true); - /** - * 417 Expectation Failed, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status EXPECTATION_FAILED_417 = new Status(417, "Expectation Failed", true); - /** - * 418 I'm a teapot, see - * Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0). - */ - public static final Status I_AM_A_TEAPOT_418 = new Status(418, "I'm a teapot", true); - /** - * Misdirected request, see - * RFC 9110 - Http Semantics. - */ - public static final Status MISDIRECTED_REQUEST_421 = new Status(421, "Misdirected Request", true); - /** - * Unprocessable content, see - * RFC 9110 - Http Semantics. - */ - public static final Status UNPROCESSABLE_CONTENT_422 = new Status(422, "Unprocessable Content", true); - /** - * Locked, see - * RFC 4918 - HTTP Extensions for WebDAV. - */ - public static final Status LOCKED_423 = new Status(423, "Locked", true); - /** - * Failed dependency, see - * RFC 4918 - HTTP Extensions for WebDAV. - */ - public static final Status FAILED_DEPENDENCY_424 = new Status(424, "Failed Dependency", true); - /** - * Upgrade required, see - * RFC 9110 - Http Semantics. - */ - public static final Status UPGRADE_REQUIRED_426 = new Status(426, "Upgrade Required", true); - /** - * Precondition required, see - * RFC 6585 - Additional HTTP Status Codes. - */ - public static final Status PRECONDITION_REQUIRED_428 = new Status(428, "Precondition Required", true); - /** - * Too many requests, see - * RFC 6585 - Additional HTTP Status Codes. - */ - public static final Status TOO_MANY_REQUESTS_429 = new Status(429, "Too Many Requests", true); - /** - * 500 Internal Server Error, see - * HTTP/1.1 documentation. - */ - public static final Status INTERNAL_SERVER_ERROR_500 = new Status(500, "Internal Server Error", true); - /** - * 501 Not Implemented, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status NOT_IMPLEMENTED_501 = new Status(501, "Not Implemented", true); - /** - * 502 Bad Gateway, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status BAD_GATEWAY_502 = new Status(502, "Bad Gateway", true); - /** - * 503 Service Unavailable, see - * HTTP/1.1 documentation. - */ - public static final Status SERVICE_UNAVAILABLE_503 = new Status(503, "Service Unavailable", true); - /** - * 504 Gateway Timeout, see - * HTTP/1.1 documentation. - * - * @since 2.0 - */ - public static final Status GATEWAY_TIMEOUT_504 = new Status(504, "Gateway Timeout", true); - /** - * 505 HTTP Version Not Supported, see - * HTTP/1.1 documentation. - * - * @since 3.0.3 - */ - public static final Status HTTP_VERSION_NOT_SUPPORTED_505 = new Status(505, "HTTP Version Not Supported", true); - - static { - // THIS MUST BE AFTER THE LAST CONSTANT - StatusHelper.statusesDone(); - } - - private final int code; - private final String reason; - private final Family family; - private final String codeText; - private final String stringValue; - - private Status(int statusCode, String reasonPhrase, boolean instance) { - this.code = statusCode; - this.reason = reasonPhrase; - this.family = Family.of(statusCode); - this.codeText = String.valueOf(code); - this.stringValue = code + " " + reason; - - if (instance) { - StatusHelper.add(this); - } - } - - private Status(int statusCode, String reasonPhrase, Family family, String codeText) { - // for custom codes - this.code = statusCode; - this.reason = reasonPhrase; - this.family = family; - this.codeText = codeText; - this.stringValue = code + " " + reason; - } - - /** - * Convert a numerical status code into the corresponding Status. - *

- * For an unknown code, an ad-hoc {@link io.helidon.http.Http.Status} is created. - * - * @param statusCode the numerical status code - * @return the matching Status; either a constant from this class, or an ad-hoc {@link io.helidon.http.Http.Status} - */ - public static Status create(int statusCode) { - Status found = StatusHelper.find(statusCode); - - if (found == null) { - return createNew(Family.of(statusCode), statusCode, "", String.valueOf(statusCode)); - } - return found; - } - - /** - * Convert a numerical status code into the corresponding Status. - *

- * It either returns an existing {@link io.helidon.http.Http.Status} constant if possible. - * For an unknown code, or code/reason phrase combination it creates - * an ad-hoc {@link io.helidon.http.Http.Status}. - * - * @param statusCode the numerical status code - * @param reasonPhrase the reason phrase; if {@code null} or a known reason phrase, an instance with the default - * phrase is returned; otherwise, a new instance is returned - * @return the matching Status - */ - public static Status create(int statusCode, String reasonPhrase) { - Status found = StatusHelper.find(statusCode); - if (found == null) { - return createNew(Family.of(statusCode), statusCode, reasonPhrase, String.valueOf(statusCode)); - } - if (reasonPhrase == null) { - return found; - } - if (found.reasonPhrase().equalsIgnoreCase(reasonPhrase)) { - return found; - } - return createNew(found.family(), statusCode, reasonPhrase, found.codeText()); - } - - private static Status createNew(Family family, int statusCode, String reasonPhrase, String codeText) { - return new Status(statusCode, reasonPhrase, family, codeText); - } - - /** - * Get the associated integer value representing the status code. - * - * @return the integer value representing the status code. - */ - public int code() { - return code; - } - - /** - * Get the class of status code. - * - * @return the class of status code. - */ - public Family family() { - return family; - } - - /** - * Get the reason phrase. - * - * @return the reason phrase. - */ - public String reasonPhrase() { - return reason; - } - - /** - * Text of the {@link #code()}. - * - * @return code string (number as a string) - */ - public String codeText() { - return codeText; - } - - /** - * Get the response status as string. - * - * @return the response status string in the form of a partial HTTP response status line, - * i.e. {@code "Status-Code SP Reason-Phrase"}. - */ - public String toString() { - return stringValue; - } - - /** - * Text of the status as used in HTTP/1, such as "200 OK". - * @return text of this status - */ - public String text() { - return stringValue; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Status status = (Status) o; - return code == status.code && reason.equals(status.reason); - } - - @Override - public int hashCode() { - return Objects.hash(code, reason); - } - - /** - * An enumeration representing the class of status code. Family is used - * here since class is overloaded in Java. - *

- * Copied from JAX-RS. - */ - public enum Family { - - /** - * {@code 1xx} HTTP status codes. - */ - INFORMATIONAL, - /** - * {@code 2xx} HTTP status codes. - */ - SUCCESSFUL, - /** - * {@code 3xx} HTTP status codes. - */ - REDIRECTION, - /** - * {@code 4xx} HTTP status codes. - */ - CLIENT_ERROR, - /** - * {@code 5xx} HTTP status codes. - */ - SERVER_ERROR, - /** - * Other, unrecognized HTTP status codes. - */ - OTHER; - - /** - * Get the family for the response status code. - * - * @param statusCode response status code to get the family for. - * @return family of the response status code. - */ - public static Family of(int statusCode) { - return switch (statusCode / 100) { - case 1 -> Family.INFORMATIONAL; - case 2 -> Family.SUCCESSFUL; - case 3 -> Family.REDIRECTION; - case 4 -> Family.CLIENT_ERROR; - case 5 -> Family.SERVER_ERROR; - default -> Family.OTHER; - }; - } - } - } - - /** - * HTTP header name. - */ - public sealed interface HeaderName permits HeaderNameImpl, HeaderNameEnum { - /** - * Lowercase value of this header, used by HTTP/2, may be used for lookup by HTTP/1. - * There is no validation of this value, so if this contains an upper-case letter, behavior - * is undefined. - * - * @return name of the header, lowercase - */ - String lowerCase(); - - /** - * Header name as used in HTTP/1, or "human-readable" value of this header. - * - * @return name of the header, may use uppercase and/or lowercase - */ - String defaultCase(); - - /** - * Index of this header (if one of the known indexed headers), or {@code -1} if this is a custom header name. - * - * @return index of this header - */ - default int index() { - return -1; - } - - /** - * Http2 defines pseudoheaders as headers starting with a {@code :} character. These are used instead - * of the prologue line from HTTP/1 (to define path, authority etc.) and instead of status line in response. - * - * @return whether this header is a pseudo-header - */ - default boolean isPseudoHeader() { - return lowerCase().charAt(0) == ':'; - } - } - - /** - * HTTP Header with {@link io.helidon.http.Http.HeaderName} and value. - * - * @see io.helidon.http.Http.Headers - */ - public interface Header extends Value { - - /** - * Name of the header as configured by user - * or as received on the wire. - * - * @return header name, always lower case for HTTP/2 headers - */ - @Override - String name(); - - /** - * Value of the header. - * - * @return header value - * @deprecated use {@link #get()} - */ - @Deprecated(forRemoval = true, since = "4.0.0") - default String value() { - return get(); - } - - /** - * Header name for the header. - * - * @return header name - */ - HeaderName headerName(); - - /** - * All values concatenated using a comma. - * - * @return all values joined by a comma - */ - default String values() { - return String.join(",", allValues()); - } - - /** - * All values of this header. - * - * @return all configured values - */ - List allValues(); - - /** - * All values of this header. If this header is defined as a single header with comma separated values, - * set {@code split} to true. - * - * @param split whether to split single value by comma, does nothing if the value is already a list. - * @return list of values - */ - default List allValues(boolean split) { - if (split) { - List values = allValues(); - if (values.size() == 1) { - String value = values.get(0); - if (value.contains(", ")) { - return List.of(value.split(", ")); - } else { - return List.of(value); - } - } - return values; - } else { - return allValues(); - } - } - - /** - * Number of values this header has. - * - * @return number of values (minimal number is 1) - */ - int valueCount(); - - /** - * Sensitive headers should not be logged, or indexed (HTTP/2). - * - * @return whether this header is sensitive - */ - boolean sensitive(); - - /** - * Changing headers should not be cached, and their value should not be indexed (HTTP/2). - * - * @return whether this header's value is changing often - */ - boolean changing(); - - /** - * Cached bytes of a single valued header's value. - * - * @return value bytes - */ - default byte[] valueBytes() { - return get().getBytes(StandardCharsets.US_ASCII); - } - - /** - * Write the current header as an HTTP header to the provided buffer. - * - * @param buffer buffer to write to (should be growing) - */ - default void writeHttp1Header(BufferData buffer) { - byte[] nameBytes = name().getBytes(StandardCharsets.US_ASCII); - if (valueCount() == 1) { - writeHeader(buffer, nameBytes, valueBytes()); - } else { - for (String value : allValues()) { - writeHeader(buffer, nameBytes, value.getBytes(StandardCharsets.US_ASCII)); - } - } - } - - /** - * Check validity of header name and values. - * - * @throws IllegalArgumentException in case the HeaderValue is not valid - */ - default void validate() throws IllegalArgumentException { - String name = name(); - // validate that header name only contains valid characters - HttpToken.validate(name); - // Validate header value - validateValue(name, values()); - } - - - // validate header value based on https://www.rfc-editor.org/rfc/rfc7230#section-3.2 and throws IllegalArgumentException - // if invalid. - private static void validateValue(String name, String value) throws IllegalArgumentException { - char[] vChars = value.toCharArray(); - int vLength = vChars.length; - for (int i = 0; i < vLength; i++) { - char vChar = vChars[i]; - if (i == 0) { - if (vChar < '!' || vChar == '\u007f') { - throw new IllegalArgumentException("First character of the header value is invalid" - + " for header '" + name + "'"); - } - } else { - if (vChar < ' ' && vChar != '\t' || vChar == '\u007f') { - throw new IllegalArgumentException("Character at position " + (i + 1) + " of the header value is invalid" - + " for header '" + name + "'"); - } - } - } - } - - private void writeHeader(BufferData buffer, byte[] nameBytes, byte[] valueBytes) { - // header name - buffer.write(nameBytes); - // ": " - buffer.write(':'); - buffer.write(' '); - // header value - buffer.write(valueBytes); - // \r\n - buffer.write('\r'); - buffer.write('\n'); - } - } - - /** - * Mutable header value. - */ - public interface HeaderValueWriteable extends Header { - /** - * Create a new mutable header from an existing header. - * - * @param header header to copy - * @return a new mutable header - */ - static HeaderValueWriteable create(Header header) { - return new HeaderValueCopy(header); - } - - /** - * Add a value to this header. - * - * @param value value to add - * @return this instance - */ - HeaderValueWriteable addValue(String value); - } - - /** - * Utility class with a list of names of standard HTTP headers and related tooling methods. - */ - public static final class HeaderNames { - /** - * The {@code Accept} header name. - * Content-Types that are acceptedTypes for the response. - */ - public static final HeaderName ACCEPT = HeaderNameEnum.ACCEPT; - /** - * The {@code Accept-Charset} header name. - * Character sets that are acceptedTypes. - */ - public static final HeaderName ACCEPT_CHARSET = HeaderNameEnum.ACCEPT_CHARSET; - /** - * The {@code Accept-Encoding} header name. - * List of acceptedTypes encodings. - */ - public static final HeaderName ACCEPT_ENCODING = HeaderNameEnum.ACCEPT_ENCODING; - /** - * The {@code Accept-Language} header name. - * List of acceptedTypes human languages for response. - */ - public static final HeaderName ACCEPT_LANGUAGE = HeaderNameEnum.ACCEPT_LANGUAGE; - /** - * The {@code Accept-Datetime} header name. - * Acceptable version in time. - */ - public static final HeaderName ACCEPT_DATETIME = HeaderNameEnum.ACCEPT_DATETIME; - /** - * The {@code Access-Control-Allow-Credentials} header name. - * CORS configuration. - */ - public static final HeaderName ACCESS_CONTROL_ALLOW_CREDENTIALS = HeaderNameEnum.ACCESS_CONTROL_ALLOW_CREDENTIALS; - /** - * The {@code Access-Control-Allow-Headers} header name. - * CORS configuration - */ - public static final HeaderName ACCESS_CONTROL_ALLOW_HEADERS = HeaderNameEnum.ACCESS_CONTROL_ALLOW_HEADERS; - /** - * The {@code Access-Control-Allow-Methods} header name. - * CORS configuration - */ - public static final HeaderName ACCESS_CONTROL_ALLOW_METHODS = HeaderNameEnum.ACCESS_CONTROL_ALLOW_METHODS; - /** - * The {@code Access-Control-Allow-Origin} header name. - * CORS configuration. - */ - public static final HeaderName ACCESS_CONTROL_ALLOW_ORIGIN = HeaderNameEnum.ACCESS_CONTROL_ALLOW_ORIGIN; - /** - * The {@code Access-Control-Expose-Headers} header name. - * CORS configuration. - */ - public static final HeaderName ACCESS_CONTROL_EXPOSE_HEADERS = HeaderNameEnum.ACCESS_CONTROL_EXPOSE_HEADERS; - /** - * The {@code Access-Control-Max-Age} header name. - * CORS configuration. - */ - public static final HeaderName ACCESS_CONTROL_MAX_AGE = HeaderNameEnum.ACCESS_CONTROL_MAX_AGE; - /** - * The {@code Access-Control-Request-Headers} header name. - * CORS configuration. - */ - public static final HeaderName ACCESS_CONTROL_REQUEST_HEADERS = HeaderNameEnum.ACCESS_CONTROL_REQUEST_HEADERS; - /** - * The {@code Access-Control-Request-Method} header name. - * CORS configuration. - */ - public static final HeaderName ACCESS_CONTROL_REQUEST_METHOD = HeaderNameEnum.ACCESS_CONTROL_REQUEST_METHOD; - /** - * The {@code Authorization} header name. - * Authentication credentials for HTTP authentication. - */ - public static final HeaderName AUTHORIZATION = HeaderNameEnum.AUTHORIZATION; - /** - * The {@code Cookie} header name. - * An HTTP cookie previously sent by the server with {@code Set-Cookie}. - */ - public static final HeaderName COOKIE = HeaderNameEnum.COOKIE; - /** - * The {@code Expect} header name. - * Indicates that particular server behaviors are required by the client. - */ - public static final HeaderName EXPECT = HeaderNameEnum.EXPECT; - /** - * The {@code Forwarded} header name. - * Disclose original information of a client connecting to a web server through an HTTP proxy. - */ - public static final HeaderName FORWARDED = HeaderNameEnum.FORWARDED; - /** - * The {@code From} header name. - * The email address of the user making the request. - */ - public static final HeaderName FROM = HeaderNameEnum.FROM; - /** - * The {@code Host} header name. - * The domain name of the server (for virtual hosting), and the TCP port number on which the server is listening. - * The port number may be omitted if the port is the standard port for the service requested. - */ - public static final HeaderName HOST = HeaderNameEnum.HOST; - /** - * The {@value} header. - * - * @see #HOST - */ - public static final String HOST_STRING = "Host"; - /** - * The {@code If-Match} header name. - * Only perform the action if the client supplied entity matches the same entity on the server. This is mainly - * for methods like PUT to only update a resource if it has not been modified since the user last updated it. - */ - public static final HeaderName IF_MATCH = HeaderNameEnum.IF_MATCH; - /** - * The {@code If-Modified-Since} header name. - * Allows a 304 Not Modified to be returned if content is unchanged. - */ - public static final HeaderName IF_MODIFIED_SINCE = HeaderNameEnum.IF_MODIFIED_SINCE; - /** - * The {@code If-None-Match} header name. - * Allows a 304 Not Modified to be returned if content is unchanged, based on {@link #ETAG}. - */ - public static final HeaderName IF_NONE_MATCH = HeaderNameEnum.IF_NONE_MATCH; - /** - * The {@code If-Range} header name. - * If the entity is unchanged, send me the part(s) that I am missing; otherwise, send me the entire new entity. - */ - public static final HeaderName IF_RANGE = HeaderNameEnum.IF_RANGE; - /** - * The {@code If-Unmodified-Since} header name. - * Only send The {@code response if The Entity} has not been modified since a specific time. - */ - public static final HeaderName IF_UNMODIFIED_SINCE = HeaderNameEnum.IF_UNMODIFIED_SINCE; - /** - * The {@code Max-Forwards} header name. - * Limit the number of times the message can be forwarded through proxies or gateways. - */ - public static final HeaderName MAX_FORWARDS = HeaderNameEnum.MAX_FORWARDS; - /** - * The {@code {@value}} header name. - * Initiates a request for cross-origin resource sharing (asks server for an {@code 'Access-Control-Allow-Origin'} - * response field). - */ - public static final HeaderName ORIGIN = HeaderNameEnum.ORIGIN; - /** - * The {@code Proxy-Authenticate} header name. - * Proxy authentication information. - */ - public static final HeaderName PROXY_AUTHENTICATE = HeaderNameEnum.PROXY_AUTHENTICATE; - /** - * The {@code Proxy-Authorization} header name. - * Proxy authorization information. - */ - public static final HeaderName PROXY_AUTHORIZATION = HeaderNameEnum.PROXY_AUTHORIZATION; - /** - * The {@code Range} header name. - * Request only part of an entity. Bytes are numbered from 0. - */ - public static final HeaderName RANGE = HeaderNameEnum.RANGE; - /** - * The {@code {@value}} header name. - * This is the address of the previous web page from which a link to the currently requested page was followed. - * (The {@code word referrer} has been misspelled in The - * {@code RFC as well as in most implementations to the point that it} has - * become standard usage and is considered correct terminology.) - */ - public static final HeaderName REFERER = HeaderNameEnum.REFERER; - /** - * The {@code {@value}} header name. - */ - public static final HeaderName REFRESH = HeaderNameEnum.REFRESH; - /** - * The {@code {@value}} header name. - * The {@code transfer encodings the user agent is willing to acceptedTypes: the same values as for The Response} header - * field - * {@code Transfer-Encoding} can be used, plus the trailers value (related to the chunked transfer method) - * to notify the server it expects to receive additional fields in the trailer after the last, zero-sized, chunk. - */ - public static final HeaderName TE = HeaderNameEnum.TE; - /** - * The {@code User-Agent} header name. - * The user agent string of the user agent. - */ - public static final HeaderName USER_AGENT = HeaderNameEnum.USER_AGENT; - /** - * The {@code Via} header name. - * Informs the server of proxies through which the request was sent. - */ - public static final HeaderName VIA = HeaderNameEnum.VIA; - /** - * The {@code Accept-Patch} header name. - * Specifies which patch document formats this server supports. - */ - public static final HeaderName ACCEPT_PATCH = HeaderNameEnum.ACCEPT_PATCH; - /** - * The {@code Accept-Ranges} header name. - * What partial content range types this server supports via byte serving. - */ - public static final HeaderName ACCEPT_RANGES = HeaderNameEnum.ACCEPT_RANGES; - /** - * The {@code Age} header name. - * The {@code age The Object} has been in a proxy cache in seconds. - */ - public static final HeaderName AGE = HeaderNameEnum.AGE; - /** - * The {@code Allow} header name. - * Valid actions for a specified resource. To be used for a 405 Method not allowed. - */ - public static final HeaderName ALLOW = HeaderNameEnum.ALLOW; - /** - * The {@code {@value}} header name. - * A server uses Alt-Svc header (meaning Alternative Services) to indicate that its resources can also be - * accessed at a different network location (host or port) or using a different protocol. - */ - public static final HeaderName ALT_SVC = HeaderNameEnum.ALT_SVC; - /** - * The {@code Cache-Control} header name. - * Tells all caching mechanisms from server to client whether they may cache this object. It is measured in seconds. - */ - public static final HeaderName CACHE_CONTROL = HeaderNameEnum.CACHE_CONTROL; - /** - * The {@code Connection} header name. - * Control options for The {@code current connection and list of} hop-by-hop response fields. - */ - public static final HeaderName CONNECTION = HeaderNameEnum.CONNECTION; - /** - * The {@code {@value}} header name. - * An opportunity to raise a File Download dialogue box for a known MIME type with binary format or suggest - * a filename for dynamic content. Quotes are necessary with special characters. - */ - public static final HeaderName CONTENT_DISPOSITION = HeaderNameEnum.CONTENT_DISPOSITION; - /** - * The {@code Content-Encoding} header name. - * The type of encoding used on the data. - */ - public static final HeaderName CONTENT_ENCODING = HeaderNameEnum.CONTENT_ENCODING; - /** - * The {@code Content-Language} header name. - * The natural language or languages of the intended audience for the enclosed content. - */ - public static final HeaderName CONTENT_LANGUAGE = HeaderNameEnum.CONTENT_LANGUAGE; - /** - * The {@code Content-Length} header name. - * The length of the response body in octets. - */ - public static final HeaderName CONTENT_LENGTH = HeaderNameEnum.CONTENT_LENGTH; - /** - * The {@code Content-Location} header name. - * An alternate location for the returned data. - */ - public static final HeaderName CONTENT_LOCATION = HeaderNameEnum.CONTENT_LOCATION; - /** - * The {@code Content-Range} header name. - * Where in a full body message this partial message belongs. - */ - public static final HeaderName CONTENT_RANGE = HeaderNameEnum.CONTENT_RANGE; - /** - * The {@code Content-Type} header name. - * The MIME type of this content. - */ - public static final HeaderName CONTENT_TYPE = HeaderNameEnum.CONTENT_TYPE; - /** - * The {@code Date} header name. - * The date and time that the message was sent (in HTTP-date format as defined by RFC 7231). - */ - public static final HeaderName DATE = HeaderNameEnum.DATE; - /** - * The {@code Etag} header name. - * An identifier for a specific version of a resource, often a message digest. - */ - public static final HeaderName ETAG = HeaderNameEnum.ETAG; - /** - * The {@code Expires} header name. - * Gives the date/time after which the response is considered stale (in HTTP-date format as defined by RFC 7231) - */ - public static final HeaderName EXPIRES = HeaderNameEnum.EXPIRES; - /** - * The {@code Last-Modified} header name. - * The last modified date for the requested object (in HTTP-date format as defined by RFC 7231) - */ - public static final HeaderName LAST_MODIFIED = HeaderNameEnum.LAST_MODIFIED; - /** - * The {@code Link} header name. - * Used to express a typed relationship with another resource, where the relation type is defined by RFC 5988. - */ - public static final HeaderName LINK = HeaderNameEnum.LINK; - /** - * The {@code Location} header name. - * Used in redirection, or whenRequest a new resource has been created. - */ - public static final HeaderName LOCATION = HeaderNameEnum.LOCATION; - /** - * The {@code Pragma} header name. - * Implementation-specific fields that may have various effects anywhere along the request-response chain. - */ - public static final HeaderName PRAGMA = HeaderNameEnum.PRAGMA; - /** - * The {@code Public-Key-Pins} header name. - * HTTP Public Key Pinning, announces hash of website's authentic TLS certificate. - */ - public static final HeaderName PUBLIC_KEY_PINS = HeaderNameEnum.PUBLIC_KEY_PINS; - /** - * The {@code {@value}} header name. - * If an entity is temporarily unavailable, this instructs the client to try again later. Value could be a specified - * period of time (in seconds) or an HTTP-date. - */ - public static final HeaderName RETRY_AFTER = HeaderNameEnum.RETRY_AFTER; - /** - * The {@code Server} header name. - * A name for the server. - */ - public static final HeaderName SERVER = HeaderNameEnum.SERVER; - /** - * The {@code Set-Cookie} header name. - * An HTTP cookie set directive. - */ - public static final HeaderName SET_COOKIE = HeaderNameEnum.SET_COOKIE; - /** - * The {@code Set-Cookie2} header name. - * An HTTP cookie set directive. - */ - public static final HeaderName SET_COOKIE2 = HeaderNameEnum.SET_COOKIE2; - /** - * The {@code Strict-Transport-Security} header name. - * A HSTS Policy informing The {@code HTTP client} how long to cache the HTTPS only policy and whether this applies to - * subdomains. - */ - public static final HeaderName STRICT_TRANSPORT_SECURITY = HeaderNameEnum.STRICT_TRANSPORT_SECURITY; - /** - * The {@code Trailer} header name. - * The Trailer general field value indicates that the given set of} header fields is present in the trailer of - * a message encoded with chunked transfer coding. - */ - public static final HeaderName TRAILER = HeaderNameEnum.TRAILER; - /** - * The {@code Transfer-Encoding} header name. - * The form of encoding used to safely transfer the entity to the user. Currently defined methods are: - * {@code chunked, compress, deflate, gzip, identity}. - */ - public static final HeaderName TRANSFER_ENCODING = HeaderNameEnum.TRANSFER_ENCODING; - /** - * The {@code Tsv} header name. - * Tracking Status Value, value suggested to be sent in response to a DNT(do-not-track). - */ - public static final HeaderName TSV = HeaderNameEnum.TSV; - /** - * The {@code Upgrade} header name. - * Ask to upgrade to another protocol. - */ - public static final HeaderName UPGRADE = HeaderNameEnum.UPGRADE; - /** - * The {@code Vary} header name. - * Tells downstream proxies how to match future request headers to decide whether the cached response can be used rather - * than requesting a fresh one from the origin server. - */ - public static final HeaderName VARY = HeaderNameEnum.VARY; - /** - * The {@code Warning} header name. - * A general warning about possible problems with the entity body. - */ - public static final HeaderName WARNING = HeaderNameEnum.WARNING; - /** - * The {@code WWW-Authenticate} header name. - * Indicates the authentication scheme that should be used to access the requested entity. - */ - public static final HeaderName WWW_AUTHENTICATE = HeaderNameEnum.WWW_AUTHENTICATE; - /** - * The {@code X_HELIDON_CN} header name. - * Corresponds to the certificate CN subject value when client authentication enabled. - * This header will be removed if it is part of the request. - */ - public static final HeaderName X_HELIDON_CN = HeaderNameEnum.X_HELIDON_CN; - /** - * The {@code X-Forwarded-For} header name. - * Represents the originating client and intervening proxies when the request has passed through one or more proxies. - */ - public static final HeaderName X_FORWARDED_FOR = HeaderNameEnum.X_FORWARDED_FOR; - /** - * The {@code X_FORWARDED_HOST} header name. - * Represents the host specified by the originating client when the request has passed through one or more proxies. - */ - public static final HeaderName X_FORWARDED_HOST = HeaderNameEnum.X_FORWARDED_HOST; - - /** - * The {@code X_FORWARDED_PORT} header name. - * Represents the port specified by the originating client when the request has passed through one or more proxies. - */ - public static final HeaderName X_FORWARDED_PORT = HeaderNameEnum.X_FORWARDED_PORT; - - /** - * The {@code X_FORWARDED_PREFIX} header name. - * Represents the path prefix to be applied to relative paths resolved against this request when the request has passed - * through one or more proxies. - * - */ - public static final HeaderName X_FORWARDED_PREFIX = HeaderNameEnum.X_FORWARDED_PREFIX; - /** - * The {@code X_FORWARDED_PROTO} header name. - * Represents the protocol specified by the originating client when the request has passed through one or more proxies. - */ - public static final HeaderName X_FORWARDED_PROTO = HeaderNameEnum.X_FORWARDED_PROTO; - - private HeaderNames() { - } - - /** - * Find or create a header name. - * If a known indexed header exists for the name, the instance is returned. - * Otherwise a new header name is created with the provided name. - * - * @param name default case to use for custom header names (header names not known by Helidon) - * @return header name instance - */ - public static HeaderName create(String name) { - HeaderName headerName = HeaderNameEnum.byCapitalizedName(name); - if (headerName == null) { - return new HeaderNameImpl(Ascii.toLowerCase(name), name); - } - return headerName; - } - - /** - * Find or create a header name. - * If a known indexed header exists for the lower case name, the instance is returned. - * Otherwise a new header name is created with the provided names. - * - * @param lowerCase lower case name - * @param defaultCase default case to use for custom header names (header names not known by Helidon) - * @return header name instance - */ - public static HeaderName create(String lowerCase, String defaultCase) { - HeaderName headerName = HeaderNameEnum.byName(lowerCase); - if (headerName == null) { - return new HeaderNameImpl(lowerCase, defaultCase); - } else { - return headerName; - } - } - - /** - * Create a header name from lower case letters. - * - * @param lowerCase lower case - * @return a new header name - */ - public static HeaderName createFromLowercase(String lowerCase) { - HeaderName headerName = HeaderNameEnum.byName(lowerCase); - if (headerName == null) { - return new HeaderNameImpl(lowerCase, lowerCase); - } else { - return headerName; - } - } - - } - - /** - * Values of commonly used headers. - */ - public static final class Headers { - /** - * Accept byte ranges for file download. - */ - public static final Header ACCEPT_RANGES_BYTES = createCached(HeaderNames.ACCEPT_RANGES, "bytes"); - /** - * Not accepting byte ranges for file download. - */ - public static final Header ACCEPT_RANGES_NONE = createCached(HeaderNames.ACCEPT_RANGES, "none"); - /** - * Chunked transfer encoding. - * Used in {@code HTTP/1}. - */ - public static final Header TRANSFER_ENCODING_CHUNKED = createCached(HeaderNames.TRANSFER_ENCODING, "chunked"); - /** - * Connection keep-alive. - * Used in {@code HTTP/1}. - */ - public static final Header CONNECTION_KEEP_ALIVE = createCached(HeaderNames.CONNECTION, "keep-alive"); - /** - * Connection close. - * Used in {@code HTTP/1}. - */ - public static final Header CONNECTION_CLOSE = createCached(HeaderNames.CONNECTION, "close"); - /** - * Content type application/json with no charset. - */ - public static final Header CONTENT_TYPE_JSON = createCached(HeaderNames.CONTENT_TYPE, "application/json"); - /** - * Content type text plain with no charset. - */ - public static final Header CONTENT_TYPE_TEXT_PLAIN = createCached(HeaderNames.CONTENT_TYPE, "text/plain"); - /** - * Content type octet stream. - */ - public static final Header CONTENT_TYPE_OCTET_STREAM = createCached(HeaderNames.CONTENT_TYPE, - "application/octet-stream"); - /** - * Content type SSE event stream. - */ - public static final Header CONTENT_TYPE_EVENT_STREAM = createCached(HeaderNames.CONTENT_TYPE, - "text/event-stream"); - - /** - * Accept application/json. - */ - public static final Header ACCEPT_JSON = createCached(HeaderNames.ACCEPT, "application/json"); - /** - * Accept text/plain with UTF-8. - */ - public static final Header ACCEPT_TEXT = createCached(HeaderNames.ACCEPT, "text/plain;charset=UTF-8"); - /** - * Accept text/event-stream. - */ - public static final Header ACCEPT_EVENT_STREAM = createCached(HeaderNames.ACCEPT, "text/event-stream"); - /** - * Expect 100 header. - */ - public static final Header EXPECT_100 = createCached(HeaderNames.EXPECT, "100-continue"); - /** - * Content length with 0 value. - */ - public static final Header CONTENT_LENGTH_ZERO = createCached(HeaderNames.CONTENT_LENGTH, "0"); - /** - * Cache control without any caching. - */ - public static final Header CACHE_NO_CACHE = create(HeaderNames.CACHE_CONTROL, "no-cache", - "no-store", - "must-revalidate", - "no-transform"); - /** - * Cache control that allows caching with no transform. - */ - public static final Header CACHE_NORMAL = createCached(HeaderNames.CACHE_CONTROL, "no-transform"); - - /** - * TE header set to {@code trailers}, used to enable trailer headers. - */ - public static final Header TE_TRAILERS = createCached(HeaderNames.TE, "trailers"); - - private Headers() { - } - - /** - * Create and cache byte value. - * Use this method if the header value is stored in a constant, or used repeatedly. - * - * @param name header name - * @param value value of the header - * @return a new header - */ - public static Header createCached(String name, String value) { - return createCached(HeaderNames.create(name), value); - } - - /** - * Create and cache byte value. - * Use this method if the header value is stored in a constant, or used repeatedly. - * - * @param name header name - * @param value value of the header - * @return a new header - */ - public static Header createCached(String name, int value) { - return createCached(HeaderNames.create(name), value); - } - - /** - * Create and cache byte value. - * Use this method if the header value is stored in a constant, or used repeatedly. - * - * @param name header name - * @param value value of the header - * @return a new header - */ - public static Header createCached(String name, long value) { - return createCached(HeaderNames.create(name), value); - } - - /** - * Create and cache byte value. - * Use this method if the header value is stored in a constant, or used repeatedly. - * - * @param name header name - * @param value value of the header - * @return a new header - */ - public static Header createCached(HeaderName name, String value) { - return new HeaderValueCached(name, false, - false, - value.getBytes(StandardCharsets.US_ASCII), - value); - } - - /** - * Create and cache byte value. - * Use this method if the header value is stored in a constant, or used repeatedly. - * - * @param name header name - * @param value value of the header - * @return a new header - */ - public static Header createCached(HeaderName name, int value) { - return createCached(name, String.valueOf(value)); - } - - /** - * Create and cache byte value. - * Use this method if the header value is stored in a constant, or used repeatedly. - * - * @param name header name - * @param value value of the header - * @return a new header - */ - public static Header createCached(HeaderName name, long value) { - return createCached(name, String.valueOf(value)); - } - - /** - * Create a new header with a single value. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param value lazy string with the value - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(HeaderName name, LazyString value) { - Objects.requireNonNull(name); - Objects.requireNonNull(value); - - return new HeaderValueLazy(name, false, false, value); - } - - /** - * Create a new header with a single value. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param value integer value of the header - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(HeaderName name, int value) { - Objects.requireNonNull(name); - - return new HeaderValueSingle(name, false, false, String.valueOf(value)); - } - - /** - * Create a new header with a single value. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param value long value of the header - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(HeaderName name, long value) { - Objects.requireNonNull(name); - - return new HeaderValueSingle(name, false, false, String.valueOf(value)); - } - - /** - * Create a new header with a single value. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param value value of the header - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(HeaderName name, String value) { - Objects.requireNonNull(name, "HeaderName must not be null"); - Objects.requireNonNull(value, "HeaderValue must not be null"); - - return new HeaderValueSingle(name, - false, - false, - value); - } - - /** - * Create a new header with a single value. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param value value of the header - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(String name, String value) { - Objects.requireNonNull(name, "Header name must not be null"); - - return create(HeaderNames.create(name), value); - } - - /** - * Create a new header with a single value. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param value value of the header - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(String name, int value) { - Objects.requireNonNull(name, "Header name must not be null"); - - return create(HeaderNames.create(name), value); - } - - /** - * Create a new header with a single value. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param value value of the header - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(String name, long value) { - Objects.requireNonNull(name, "Header name must not be null"); - - return create(HeaderNames.create(name), value); - } - - /** - * Create a new header. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param values values of the header - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(HeaderName name, String... values) { - if (values.length == 0) { - throw new IllegalArgumentException("Cannot create a header without a value. Header: " + name); - } - return new HeaderValueArray(name, false, false, values); - } - - /** - * Create a new header. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param values values of the header - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(String name, String... values) { - return create(HeaderNames.create(name), values); - } - - /** - * Create a new header. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param values values of the header - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(HeaderName name, Collection values) { - return new HeaderValueList(name, false, false, values); - } - - /** - * Create a new header. This header is considered unchanging and not sensitive. - * - * @param name name of the header - * @param values values of the header - * @return a new header - * @see #create(io.helidon.http.Http.HeaderName, boolean, boolean, String...) - */ - public static Header create(String name, Collection values) { - return create(HeaderNames.create(name), values); - } - - /** - * Create and cache byte value. - * Use this method if the header value is stored in a constant, or used repeatedly. - * - * @param name header name - * @param changing whether the value is changing often (to disable caching for HTTP/2) - * @param sensitive whether the value is sensitive (to disable caching for HTTP/2) - * @param value value of the header - * @return a new header - */ - public static Header createCached(HeaderName name, boolean changing, boolean sensitive, String value) { - return new HeaderValueCached(name, changing, sensitive, value.getBytes(StandardCharsets.UTF_8), value); - } - - /** - * Create a new header. - * - * @param name name of the header - * @param changing whether the value is changing often (to disable caching for HTTP/2) - * @param sensitive whether the value is sensitive (to disable caching for HTTP/2) - * @param values value(s) of the header - * @return a new header - */ - public static Header create(HeaderName name, boolean changing, boolean sensitive, String... values) { - return new HeaderValueArray(name, changing, sensitive, values); - } - - /** - * Create a new header. - * - * @param name name of the header - * @param changing whether the value is changing often (to disable caching for HTTP/2) - * @param sensitive whether the value is sensitive (to disable caching for HTTP/2) - * @param value value of the header - * @return a new header - */ - public static Header create(HeaderName name, boolean changing, boolean sensitive, int value) { - return create(name, changing, sensitive, String.valueOf(value)); - } - - /** - * Create a new header. - * - * @param name name of the header - * @param changing whether the value is changing often (to disable caching for HTTP/2) - * @param sensitive whether the value is sensitive (to disable caching for HTTP/2) - * @param value value of the header - * @return a new header - */ - public static Header create(HeaderName name, boolean changing, boolean sensitive, long value) { - return create(name, changing, sensitive, String.valueOf(value)); - } - } - - /** - * Support for HTTP date formats based on RFC2616. - */ - public static final class DateTime { - /** - * The RFC850 date-time formatter, such as {@code 'Sunday, 06-Nov-94 08:49:37 GMT'}. - *

- * This is obsolete standard (obsoleted by RFC1036). Headers MUST NOT be generated in this format. - * However it should be used as a fallback for parsing to achieve compatibility with older HTTP standards. - *

- * Since the format accepts 2 digits year representation formatter works well for dates between - * {@code (now - 50 Years)} and {@code (now + 49 Years)}. - */ - public static final DateTimeFormatter RFC_850_DATE_TIME = DateTimeHelper.RFC_850_DATE_TIME; - /** - * The RFC1123 date-time formatter, such as {@code 'Tue, 3 Jun 2008 11:05:30 GMT'}. - *

- * This is standard for RFC2616 and all created headers MUST be in this format! However implementation must - * accept headers also in RFC850 and ANSI C {@code asctime()} format. - *

- * This is just copy of convenient copy of {@link java.time.format.DateTimeFormatter#RFC_1123_DATE_TIME}. - */ - public static final DateTimeFormatter RFC_1123_DATE_TIME = DateTimeFormatter.RFC_1123_DATE_TIME; - /** - * The ANSI C's {@code asctime()} format, such as {@code 'Sun Nov 6 08:49:37 1994'}. - *

- * Headers MUST NOT be generated in this format. - * However it should be used as a fallback for parsing to achieve compatibility with older HTTP standards. - */ - public static final DateTimeFormatter ASCTIME_DATE_TIME = DateTimeHelper.ASCTIME_DATE_TIME; - - private DateTime() { - } - - /** - * Parse provided text to {@link java.time.ZonedDateTime} using any possible date / time format specified - * by RFC2616 Hypertext Transfer Protocol. - *

- * Formats are specified by {@link #RFC_1123_DATE_TIME}, {@link #RFC_850_DATE_TIME} and {@link #ASCTIME_DATE_TIME}. - * - * @param text a text to parse. - * @return parsed date time. - * @throws java.time.format.DateTimeParseException if not in any of supported formats. - */ - public static ZonedDateTime parse(String text) { - return DateTimeHelper.parse(text); - } - - /** - * Last recorded timestamp. - * - * @return timestamp - */ - public static ZonedDateTime timestamp() { - return DateTimeHelper.timestamp(); - } - - /** - * Get current time as RFC-1123 string. - * - * @return formatted current time - * @see #RFC_1123_DATE_TIME - */ - public static String rfc1123String() { - return DateTimeHelper.rfc1123String(); - } - - /** - * Formatted date time terminated by carriage return and new line. - * - * @return date bytes for HTTP/1 - */ - public static byte[] http1Bytes() { - return DateTimeHelper.http1Bytes(); - } - } } diff --git a/http/http/src/main/java/io/helidon/http/Http1HeadersParser.java b/http/http/src/main/java/io/helidon/http/Http1HeadersParser.java index 1051190db19..2c158c816c8 100644 --- a/http/http/src/main/java/io/helidon/http/Http1HeadersParser.java +++ b/http/http/src/main/java/io/helidon/http/Http1HeadersParser.java @@ -56,7 +56,7 @@ public static WritableHeaders readHeaders(DataReader reader, int maxHeadersSi return headers; } - Http.HeaderName header = readHeaderName(reader, maxLength, validate); + HeaderName header = readHeaderName(reader, maxLength, validate); maxLength -= header.defaultCase().length() + 2; int eol = reader.findNewLine(maxLength); if (eol == maxLength) { @@ -67,7 +67,7 @@ public static WritableHeaders readHeaders(DataReader reader, int maxHeadersSi reader.skip(2); maxLength -= eol + 1; - Http.Header headerValue = Http.Headers.create(header, value); + Header headerValue = HeaderValues.create(header, value); headers.add(headerValue); if (validate) { headerValue.validate(); @@ -78,9 +78,9 @@ public static WritableHeaders readHeaders(DataReader reader, int maxHeadersSi } } - private static Http.HeaderName readHeaderName(DataReader reader, - int maxLength, - boolean validate) { + private static HeaderName readHeaderName(DataReader reader, + int maxLength, + boolean validate) { switch (reader.lookup()) { case (byte) 'H' -> { if (reader.startsWith(HD_HOST)) { @@ -117,7 +117,7 @@ private static Http.HeaderName readHeaderName(DataReader reader, } String headerName = reader.readAsciiString(col); - Http.HeaderName header = Http.HeaderNames.create(headerName); + HeaderName header = HeaderNames.create(headerName); reader.skip(1); // skip the colon character return header; diff --git a/http/http/src/main/java/io/helidon/http/HttpException.java b/http/http/src/main/java/io/helidon/http/HttpException.java index 8314203288b..5be7056d323 100644 --- a/http/http/src/main/java/io/helidon/http/HttpException.java +++ b/http/http/src/main/java/io/helidon/http/HttpException.java @@ -25,26 +25,26 @@ */ public class HttpException extends RuntimeException { - private final Http.Status status; + private final Status status; private final boolean keepAlive; /** - * Creates {@link HttpException} associated with {@link Http.Status#INTERNAL_SERVER_ERROR_500}. + * Creates {@link HttpException} associated with {@link Status#INTERNAL_SERVER_ERROR_500}. * * @param message the message */ public HttpException(String message) { - this(message, Http.Status.INTERNAL_SERVER_ERROR_500); + this(message, Status.INTERNAL_SERVER_ERROR_500); } /** - * Creates {@link HttpException} associated with {@link Http.Status#INTERNAL_SERVER_ERROR_500}. + * Creates {@link HttpException} associated with {@link Status#INTERNAL_SERVER_ERROR_500}. * * @param message the message * @param cause the cause of this exception */ public HttpException(String message, Throwable cause) { - this(message, Http.Status.INTERNAL_SERVER_ERROR_500, cause); + this(message, Status.INTERNAL_SERVER_ERROR_500, cause); } /** @@ -53,7 +53,7 @@ public HttpException(String message, Throwable cause) { * @param message the message * @param status the http status */ - public HttpException(String message, Http.Status status) { + public HttpException(String message, Status status) { this(message, status, null); } @@ -64,7 +64,7 @@ public HttpException(String message, Http.Status status) { * @param status the http status * @param keepAlive whether to keep the connection alive */ - public HttpException(String message, Http.Status status, boolean keepAlive) { + public HttpException(String message, Status status, boolean keepAlive) { this(message, status, null, keepAlive); } @@ -76,7 +76,7 @@ public HttpException(String message, Http.Status status, boolean keepAlive) { * @param status the http status * @param cause the cause of this exception */ - public HttpException(String message, Http.Status status, Throwable cause) { + public HttpException(String message, Status status, Throwable cause) { this(message, status, cause, false); } @@ -88,7 +88,7 @@ public HttpException(String message, Http.Status status, Throwable cause) { * @param cause the cause of this exception * @param keepAlive whether to keep this connection alive */ - public HttpException(String message, Http.Status status, Throwable cause, boolean keepAlive) { + public HttpException(String message, Status status, Throwable cause, boolean keepAlive) { super(message, cause); this.status = status; @@ -100,7 +100,7 @@ public HttpException(String message, Http.Status status, Throwable cause, boolea * * @return the http status */ - public final Http.Status status() { + public final Status status() { return status; } diff --git a/http/http/src/main/java/io/helidon/http/HttpPrologue.java b/http/http/src/main/java/io/helidon/http/HttpPrologue.java index bfe9792cc6e..0f241b154d0 100644 --- a/http/http/src/main/java/io/helidon/http/HttpPrologue.java +++ b/http/http/src/main/java/io/helidon/http/HttpPrologue.java @@ -29,7 +29,7 @@ public class HttpPrologue { private final String rawProtocol; private final String protocol; private final String protocolVersion; - private final Http.Method method; + private final Method method; private final UriPath uriPath; private final String rawQuery; private final String rawFragment; @@ -49,7 +49,7 @@ public class HttpPrologue { private HttpPrologue(String rawProtocol, String protocol, String protocolVersion, - Http.Method method, + Method method, UriPath path, String rawQuery, String rawFragment) { @@ -65,7 +65,7 @@ private HttpPrologue(String rawProtocol, private HttpPrologue(String rawProtocol, String protocol, String protocolVersion, - Http.Method httpMethod, + Method httpMethod, UriPath uriPath, UriQuery uriQuery, UriFragment uriFragment) { @@ -95,7 +95,7 @@ private HttpPrologue(String rawProtocol, public static HttpPrologue create(String rawProtocol, String protocol, String protocolVersion, - Http.Method httpMethod, + Method httpMethod, String unresolvedPath, boolean validatePath) { @@ -148,7 +148,7 @@ public static HttpPrologue create(String rawProtocol, public static HttpPrologue create(String rawProtocol, String protocol, String protocolVersion, - Http.Method httpMethod, + Method httpMethod, UriPath uriPath, UriQuery uriQuery, UriFragment uriFragment) { @@ -187,7 +187,7 @@ public String protocolVersion() { * * @return method */ - public Http.Method method() { + public Method method() { return method; } diff --git a/http/http/src/main/java/io/helidon/http/InternalServerException.java b/http/http/src/main/java/io/helidon/http/InternalServerException.java index 74ac5b0fb0d..1427ca6e215 100644 --- a/http/http/src/main/java/io/helidon/http/InternalServerException.java +++ b/http/http/src/main/java/io/helidon/http/InternalServerException.java @@ -17,7 +17,7 @@ package io.helidon.http; /** - * A runtime exception indicating a {@link Http.Status#INTERNAL_SERVER_ERROR_500 internal server error}. + * A runtime exception indicating a {@link Status#INTERNAL_SERVER_ERROR_500 internal server error}. */ public class InternalServerException extends HttpException { /** @@ -27,7 +27,7 @@ public class InternalServerException extends HttpException { * @param cause the cause of this exception */ public InternalServerException(String message, Throwable cause) { - super(message, Http.Status.INTERNAL_SERVER_ERROR_500, cause); + super(message, Status.INTERNAL_SERVER_ERROR_500, cause); } /** @@ -38,6 +38,6 @@ public InternalServerException(String message, Throwable cause) { * @param keepAlive whether to keep the connection alive (if keep alives are enabled) */ public InternalServerException(String message, Throwable cause, boolean keepAlive) { - super(message, Http.Status.INTERNAL_SERVER_ERROR_500, cause, keepAlive); + super(message, Status.INTERNAL_SERVER_ERROR_500, cause, keepAlive); } } diff --git a/http/http/src/main/java/io/helidon/http/Method.java b/http/http/src/main/java/io/helidon/http/Method.java new file mode 100644 index 00000000000..b85fc93083c --- /dev/null +++ b/http/http/src/main/java/io/helidon/http/Method.java @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.http; + +import java.util.Collection; +import java.util.Objects; + +import io.helidon.common.buffers.Ascii; + +/** + * Interface representing an HTTP request method, all standard methods are in {@link Method} + * enumeration. + *

+ * Although the constants are instances of this class, they can be compared using instance equality, as the only + * way to obtain an instance is through method {@link #create(String)}, which ensures the same instance is returned for + * known methods. + *

+ * Methods that are not known (e.g. there is no constant for them) must be compared using {@link #equals(Object)} as usual. + * + * @see Method + */ +public final class Method { + private static final String GET_STRING = "GET"; + /** + * The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. + * If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity + * in the response and not the source text of the process, unless that text happens to be the output of the tryProcess. + */ + public static final Method GET = new Method(GET_STRING, true); + /** + * The POST method is used to request that the origin server acceptedTypes the entity enclosed in the request + * as a new subordinate of the resource identified by the Request-URI in the Request-Line. + * The actual function performed by the POST method is determined by the server and is usually dependent on the + * Request-URI. The posted entity is subordinate to that URI in the same way that a file is subordinate to a directory + * containing it, a news article is subordinate to a newsgroup to which it is posted, or a record is subordinate + * to a database. + */ + public static final Method POST = new Method("POST", true); + /** + * The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers + * to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing + * on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being + * defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. + * If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. + * If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate + * successful completion of the request. If the resource could not be created or modified with the Request-URI, + * an appropriate error response SHOULD be given that reflects the nature of the problem. The recipient of the entity + * MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return + * a 501 (Not Implemented) response in such cases. + */ + public static final Method PUT = new Method("PUT", true); + /** + * The DELETE method requests that the origin server delete the resource identified by the Request-URI. + * This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot + * be guaranteed that the operation has been carried out, even if the status code returned from the origin server + * indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, + * at the time the response is given, it intends to delete the resource or move it to an inaccessible location. + */ + public static final Method DELETE = new Method("DELETE", true); + /** + * The HEAD method is identical to {@link #GET} except that the server MUST NOT return a message-body in the response. + * The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information + * sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied + * by the request without transferring the entity-body itself. This method is often used for testing hypertext links + * for validity, accessibility, and recent modification. + */ + public static final Method HEAD = new Method("HEAD", true); + /** + * The OPTIONS method represents a request for information about the communication options available + * on the request/response chain identified by the Request-URI. This method allows the client to determine the options + * and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action + * or initiating a resource retrieval. + */ + public static final Method OPTIONS = new Method("OPTIONS", true); + /** + * The TRACE method is used to invoke a remote, application-layer loop- back of the request message. + * The final recipient of the request SHOULD reflect the message received back to the client as the entity-body + * of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive + * a Max-Forwards value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity. + */ + public static final Method TRACE = new Method("TRACE", true); + /** + * The PATCH method as described in RFC 5789 is used to perform an update to an existing resource, where the request + * payload only has to contain the instructions on how to perform the update. This is in contrast to PUT which + * requires that the payload contains the new version of the resource. + * If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate + * successful completion of the request. + */ + public static final Method PATCH = new Method("PATCH", true); + + /** + * The HTTP CONNECT method starts two-way communications with the requested resource. It can be used to open a tunnel. + */ + public static final Method CONNECT = new Method("CONNECT", true); + + static { + // THIS MUST BE AFTER THE LAST CONSTANT + MethodHelper.methodsDone(); + } + + private final String name; + private final int length; + + private final boolean instance; + + private Method(String name, boolean instance) { + this.name = name; + this.length = name.length(); + this.instance = instance; + + if (instance) { + MethodHelper.add(this); + } + } + + /** + * Create new HTTP request method instance from the provided name. + *

+ * In case the method name is recognized as one of the {@link Method standard HTTP methods}, + * the respective enumeration + * value is returned. + * + * @param name the method name. Must not be {@code null} or empty and must be a legal HTTP method name string. + * @return HTTP request method instance representing an HTTP method with the provided name. + * @throws IllegalArgumentException In case of illegal method name or in case the name is empty or {@code null}. + */ + public static Method create(String name) { + if (name.equals(GET_STRING)) { + return GET; + } + + String methodName = Ascii.toUpperCase(name); + + Method method = MethodHelper.byName(methodName); + if (method == null) { + // validate that it only contains characters allowed by a method + HttpToken.validate(methodName); + return new Method(methodName, false); + } + return method; + } + + /** + * Create a predicate for the provided methods. + * + * @param methods methods to check against + * @return a predicate that will validate the method is one of the methods provided; if methods are empty, the predicate + * will always return {@code true} + */ + public static MethodPredicate predicate(Method... methods) { + return switch (methods.length) { + case 0 -> MethodPredicates.TruePredicate.get(); + case 1 -> methods[0].instance + ? new MethodPredicates.SingleMethodEnumPredicate(methods[0]) + : new MethodPredicates.SingleMethodPredicate(methods[0]); + default -> new MethodPredicates.MethodsPredicate(methods); + }; + } + + /** + * Create a predicate for the provided methods. + * + * @param methods methods to check against + * @return a predicate that will validate the method is one of the methods provided; if methods are empty, the predicate + * will always return {@code true} + */ + public static MethodPredicate predicate(Collection methods) { + switch (methods.size()) { + case 0: + return MethodPredicates.TruePredicate.get(); + case 1: + Method first = methods.iterator().next(); + return first.instance + ? new MethodPredicates.SingleMethodEnumPredicate(first) + : new MethodPredicates.SingleMethodPredicate(first); + + default: + return new MethodPredicates.MethodsPredicate(methods.toArray(new Method[0])); + } + } + + /** + * Name of the method (such as {@code GET} or {@code POST}). + * + * @return a method name. + * @deprecated use {@link #text()} instead, this method conflicts with enum + */ + @Deprecated + public String name() { + return text(); + } + + /** + * Name of the method (such as {@code GET} or {@code POST}). + * + * @return a method name. + */ + public String text() { + return name; + } + + /** + * Number of characters. + * + * @return number of characters of this method + */ + public int length() { + return length; + } + + @Override + public String toString() { + return text(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Method method = (Method) o; + return name.equals(method.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } +} diff --git a/http/http/src/main/java/io/helidon/http/MethodHelper.java b/http/http/src/main/java/io/helidon/http/MethodHelper.java index 3897c409dc8..919132fe50b 100644 --- a/http/http/src/main/java/io/helidon/http/MethodHelper.java +++ b/http/http/src/main/java/io/helidon/http/MethodHelper.java @@ -19,13 +19,13 @@ import java.util.List; final class MethodHelper { - private static final List KNOWN = new ArrayList<>(10); + private static final List KNOWN = new ArrayList<>(10); private static AsciiMethodPair[] methods; private MethodHelper() { } - static void add(Http.Method method) { + static void add(Method method) { KNOWN.add(method); } @@ -37,7 +37,7 @@ static void methodsDone() { KNOWN.clear(); } - static Http.Method byName(String upperCase) { + static Method byName(String upperCase) { // optimization over Map (most commonly used methods fastest) for (AsciiMethodPair method : methods) { if (method.string().equals(upperCase)) { @@ -47,8 +47,8 @@ static Http.Method byName(String upperCase) { return null; } - private record AsciiMethodPair(String string, Http.Method method) { - public static AsciiMethodPair create(Http.Method method) { + private record AsciiMethodPair(String string, Method method) { + public static AsciiMethodPair create(Method method) { return new AsciiMethodPair(method.text(), method); } } diff --git a/http/http/src/main/java/io/helidon/http/MethodPredicate.java b/http/http/src/main/java/io/helidon/http/MethodPredicate.java new file mode 100644 index 00000000000..77bdc9665b2 --- /dev/null +++ b/http/http/src/main/java/io/helidon/http/MethodPredicate.java @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.http; + +import java.util.Set; +import java.util.function.Predicate; + +/** + * HTTP Method predicate. + */ +public interface MethodPredicate extends Predicate { + /** + * Methods accepted by this predicate, may be empty. + * + * @return set of methods accepted + */ + Set acceptedMethods(); +} diff --git a/http/http/src/main/java/io/helidon/http/MethodPredicates.java b/http/http/src/main/java/io/helidon/http/MethodPredicates.java index b1564c5af70..116a301e61b 100644 --- a/http/http/src/main/java/io/helidon/http/MethodPredicates.java +++ b/http/http/src/main/java/io/helidon/http/MethodPredicates.java @@ -18,9 +18,6 @@ import java.util.Set; -import io.helidon.http.Http.Method; -import io.helidon.http.Http.MethodPredicate; - class MethodPredicates { static class TruePredicate implements MethodPredicate { private static final TruePredicate INSTANCE = new TruePredicate(); @@ -30,7 +27,7 @@ static MethodPredicate get() { } @Override - public boolean test(Http.Method t) { + public boolean test(Method t) { return true; } diff --git a/http/http/src/main/java/io/helidon/http/NotFoundException.java b/http/http/src/main/java/io/helidon/http/NotFoundException.java index d6fc847ca4c..21451e57d7e 100644 --- a/http/http/src/main/java/io/helidon/http/NotFoundException.java +++ b/http/http/src/main/java/io/helidon/http/NotFoundException.java @@ -17,7 +17,7 @@ package io.helidon.http; /** - * A runtime exception indicating a {@link Http.Status#NOT_FOUND_404 not found}. + * A runtime exception indicating a {@link Status#NOT_FOUND_404 not found}. */ public class NotFoundException extends HttpException { @@ -27,7 +27,7 @@ public class NotFoundException extends HttpException { * @param message the message */ public NotFoundException(String message) { - super(message, Http.Status.NOT_FOUND_404, null, true); + super(message, Status.NOT_FOUND_404, null, true); } /** @@ -37,6 +37,6 @@ public NotFoundException(String message) { * @param cause the cause of this exception */ public NotFoundException(String message, Throwable cause) { - super(message, Http.Status.NOT_FOUND_404, cause, true); + super(message, Status.NOT_FOUND_404, cause, true); } } diff --git a/http/http/src/main/java/io/helidon/http/RequestException.java b/http/http/src/main/java/io/helidon/http/RequestException.java index a9c5bf758aa..6b19ad27723 100644 --- a/http/http/src/main/java/io/helidon/http/RequestException.java +++ b/http/http/src/main/java/io/helidon/http/RequestException.java @@ -23,7 +23,7 @@ */ public class RequestException extends RuntimeException { private final DirectHandler.EventType eventType; - private final Http.Status status; + private final Status status; private final DirectHandler.TransportRequest transportRequest; private final boolean keepAlive; private final ServerResponseHeaders responseHeaders; @@ -59,7 +59,7 @@ public static Builder builder() { * * @return status */ - public Http.Status status() { + public Status status() { return status; } @@ -117,7 +117,7 @@ public static class Builder implements io.helidon.common.Builder { - authority = headers.first(Http.HeaderNames.HOST).orElse(null); + authority = headers.first(HeaderNames.HOST).orElse(null); break nextDiscoveryType; } default -> { - authority = headers.first(Http.HeaderNames.HOST).orElse(null); + authority = headers.first(HeaderNames.HOST).orElse(null); break nextDiscoveryType; } } @@ -343,7 +343,7 @@ public UriInfo uriInfo(String remoteAddress, // now we must fill values that were not discovered (to have a valid URI information) if (host == null && authority == null) { - authority = headers.first(Http.HeaderNames.HOST).orElse(null); + authority = headers.first(HeaderNames.HOST).orElse(null); } uriInfo.path(path == null ? requestPath : path); @@ -422,7 +422,7 @@ private XForwardedDiscovery discoverUsingXForwarded(ServerRequestHeaders headers int port = -1; String path = null; - List xForwardedFors = headers.values(Http.HeaderNames.X_FORWARDED_FOR); + List xForwardedFors = headers.values(HeaderNames.X_FORWARDED_FOR); boolean areProxiesTrusted = true; if (xForwardedFors.size() > 0) { // Intentionally skip the first X-Forwarded-For value. That is the originating client, and as such it @@ -432,10 +432,10 @@ private XForwardedDiscovery discoverUsingXForwarded(ServerRequestHeaders headers } } if (areProxiesTrusted) { - scheme = headers.first(Http.HeaderNames.X_FORWARDED_PROTO).orElse(null); - host = headers.first(Http.HeaderNames.X_FORWARDED_HOST).orElse(null); - port = headers.first(Http.HeaderNames.X_FORWARDED_PORT).map(Integer::parseInt).orElse(-1); - path = headers.first(Http.HeaderNames.X_FORWARDED_PREFIX) + scheme = headers.first(HeaderNames.X_FORWARDED_PROTO).orElse(null); + host = headers.first(HeaderNames.X_FORWARDED_HOST).orElse(null); + port = headers.first(HeaderNames.X_FORWARDED_PORT).map(Integer::parseInt).orElse(-1); + path = headers.first(HeaderNames.X_FORWARDED_PREFIX) .map(prefix -> { String absolute = requestPath; return prefix + (absolute.startsWith("/") ? "" : "/") + absolute; @@ -460,20 +460,20 @@ private record XForwardedDiscovery(String scheme, String host, int port, String */ enum RequestedUriDiscoveryType { /** - * The {@code io.helidon.http.Http.Header#FORWARDED} header is used to discover the original requested URI. + * The {@code io.helidon.http.Header#FORWARDED} header is used to discover the original requested URI. */ FORWARDED, /** * The - * {@code io.helidon.http.Http.Header#X_FORWARDED_PROTO}, - * {@code io.helidon.http.Http.Header#X_FORWARDED_HOST}, - * {@code io.helidon.http.Http.Header#X_FORWARDED_PORT}, - * {@code io.helidon.http.Http.Header#X_FORWARDED_PREFIX} + * {@code io.helidon.http.Header#X_FORWARDED_PROTO}, + * {@code io.helidon.http.Header#X_FORWARDED_HOST}, + * {@code io.helidon.http.Header#X_FORWARDED_PORT}, + * {@code io.helidon.http.Header#X_FORWARDED_PREFIX} * headers are used to discover the original requested URI. */ X_FORWARDED, /** - * This is the default, only the {@code io.helidon.http.Http.Header#HOST} header is used to discover + * This is the default, only the {@code io.helidon.http.Header#HOST} header is used to discover * requested URI. */ HOST diff --git a/http/http/src/main/java/io/helidon/http/ServerRequestHeaders.java b/http/http/src/main/java/io/helidon/http/ServerRequestHeaders.java index fafea8126fa..3aa1c5ac04e 100644 --- a/http/http/src/main/java/io/helidon/http/ServerRequestHeaders.java +++ b/http/http/src/main/java/io/helidon/http/ServerRequestHeaders.java @@ -24,7 +24,6 @@ import io.helidon.common.media.type.MediaType; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.parameters.Parameters; -import io.helidon.http.Http.Header; /** * HTTP headers of a server request. @@ -36,8 +35,8 @@ public interface ServerRequestHeaders extends Headers { * * @see JDK-8163921 */ - Http.Header HUC_ACCEPT_DEFAULT = Http.Headers.create(Http.HeaderNames.ACCEPT, - "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"); + Header HUC_ACCEPT_DEFAULT = HeaderValues.create(HeaderNames.ACCEPT, + "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"); /** * Accepted types for {@link #HUC_ACCEPT_DEFAULT}. @@ -70,34 +69,34 @@ static ServerRequestHeaders create() { } /** - * Optionally returns a value of {@link io.helidon.http.Http.HeaderNames#IF_MODIFIED_SINCE} header. + * Optionally returns a value of {@link HeaderNames#IF_MODIFIED_SINCE} header. *

* Allows a 304 Not Modified to be returned if content is unchanged. * - * @return Content of {@link io.helidon.http.Http.HeaderNames#IF_MODIFIED_SINCE} header. + * @return Content of {@link HeaderNames#IF_MODIFIED_SINCE} header. */ default Optional ifModifiedSince() { - if (contains(Http.HeaderNames.IF_MODIFIED_SINCE)) { - return Optional.of(get(Http.HeaderNames.IF_MODIFIED_SINCE)) + if (contains(HeaderNames.IF_MODIFIED_SINCE)) { + return Optional.of(get(HeaderNames.IF_MODIFIED_SINCE)) .map(Header::value) - .map(Http.DateTime::parse); + .map(DateTime::parse); } return Optional.empty(); } /** - * Optionally returns a value of {@link io.helidon.http.Http.HeaderNames#IF_UNMODIFIED_SINCE} header. + * Optionally returns a value of {@link HeaderNames#IF_UNMODIFIED_SINCE} header. *

* Only send the response if the entity has not been modified since a specific time. * - * @return Content of {@link io.helidon.http.Http.HeaderNames#IF_UNMODIFIED_SINCE} header. + * @return Content of {@link HeaderNames#IF_UNMODIFIED_SINCE} header. */ default Optional ifUnmodifiedSince() { - if (contains(Http.HeaderNames.IF_UNMODIFIED_SINCE)) { - return Optional.of(get(Http.HeaderNames.IF_UNMODIFIED_SINCE)) - .map(Http.Header::value) - .map(Http.DateTime::parse); + if (contains(HeaderNames.IF_UNMODIFIED_SINCE)) { + return Optional.of(get(HeaderNames.IF_UNMODIFIED_SINCE)) + .map(Header::value) + .map(DateTime::parse); } return Optional.empty(); } @@ -127,7 +126,7 @@ default boolean isAccepted(MediaType mediaType) { /** * Optionally returns a single media type from the given media types that is the * best one accepted by the client. - * Method uses content negotiation {@link io.helidon.http.Http.HeaderNames#ACCEPT} + * Method uses content negotiation {@link HeaderNames#ACCEPT} * header parameter and returns an empty value in case nothing matches. * * @param mediaTypes media type candidates, never null @@ -172,43 +171,43 @@ default Optional bestAccepted(MediaType... mediaTypes) { * values are cookie values. */ default Parameters cookies() { - if (contains(Http.HeaderNames.COOKIE)) { - return CookieParser.parse(get(Http.HeaderNames.COOKIE)); + if (contains(HeaderNames.COOKIE)) { + return CookieParser.parse(get(HeaderNames.COOKIE)); } else { return CookieParser.empty(); } } /** - * Optionally returns acceptedTypes version in time ({@link io.helidon.http.Http.HeaderNames#ACCEPT_DATETIME} header). + * Optionally returns acceptedTypes version in time ({@link HeaderNames#ACCEPT_DATETIME} header). * * @return Acceptable version in time. */ default Optional acceptDatetime() { - if (contains(Http.HeaderNames.ACCEPT_DATETIME)) { - return Optional.of(get(Http.HeaderNames.ACCEPT_DATETIME)) - .map(Http.Header::value) - .map(Http.DateTime::parse); + if (contains(HeaderNames.ACCEPT_DATETIME)) { + return Optional.of(get(HeaderNames.ACCEPT_DATETIME)) + .map(Header::value) + .map(DateTime::parse); } return Optional.empty(); } /** - * Optionally returns request date ({@link io.helidon.http.Http.HeaderNames#DATE} header). + * Optionally returns request date ({@link HeaderNames#DATE} header). * * @return Request date. */ default Optional date() { - if (contains(Http.HeaderNames.DATE)) { - return Optional.of(get(Http.HeaderNames.DATE)) + if (contains(HeaderNames.DATE)) { + return Optional.of(get(HeaderNames.DATE)) .map(Header::value) - .map(Http.DateTime::parse); + .map(DateTime::parse); } return Optional.empty(); } /** - * Optionally returns the address of the previous web page (header {@link io.helidon.http.Http.HeaderNames#REFERER}) from which a link + * Optionally returns the address of the previous web page (header {@link HeaderNames#REFERER}) from which a link * to the currently requested page was followed. *

* The word {@code referrer} has been misspelled in the RFC as well as in most implementations to the point that it @@ -217,8 +216,8 @@ default Optional date() { * @return Referrers URI */ default Optional referer() { - if (contains(Http.HeaderNames.REFERER)) { - return Optional.of(get(Http.HeaderNames.REFERER)) + if (contains(HeaderNames.REFERER)) { + return Optional.of(get(HeaderNames.REFERER)) .map(Header::value) .map(URI::create); } diff --git a/http/http/src/main/java/io/helidon/http/ServerRequestHeadersImpl.java b/http/http/src/main/java/io/helidon/http/ServerRequestHeadersImpl.java index 6817d3697b9..4570ebaca08 100644 --- a/http/http/src/main/java/io/helidon/http/ServerRequestHeadersImpl.java +++ b/http/http/src/main/java/io/helidon/http/ServerRequestHeadersImpl.java @@ -24,7 +24,6 @@ import java.util.function.Supplier; import io.helidon.common.parameters.Parameters; -import io.helidon.http.Http.HeaderName; class ServerRequestHeadersImpl implements ServerRequestHeaders { private final Headers headers; @@ -47,12 +46,12 @@ public boolean contains(HeaderName name) { } @Override - public boolean contains(Http.Header headerWithValue) { + public boolean contains(Header headerWithValue) { return headers.contains(headerWithValue); } @Override - public Http.Header get(HeaderName name) { + public Header get(HeaderName name) { return headers.get(name); } @@ -77,7 +76,7 @@ public List acceptedTypes() { } List acceptedTypes; - List acceptValues = all(Http.HeaderNames.ACCEPT, List::of); + List acceptValues = all(HeaderNames.ACCEPT, List::of); if (acceptValues.size() == 1 && HUC_ACCEPT_DEFAULT.value().equals(acceptValues.get(0))) { acceptedTypes = HUC_ACCEPT_DEFAULT_TYPES; } else { @@ -97,7 +96,7 @@ public List acceptedTypes() { } @Override - public Iterator iterator() { + public Iterator

iterator() { return headers.iterator(); } diff --git a/http/http/src/main/java/io/helidon/http/ServerResponseHeaders.java b/http/http/src/main/java/io/helidon/http/ServerResponseHeaders.java index 053844dd149..c662f4f9ed8 100644 --- a/http/http/src/main/java/io/helidon/http/ServerResponseHeaders.java +++ b/http/http/src/main/java/io/helidon/http/ServerResponseHeaders.java @@ -24,9 +24,9 @@ import io.helidon.common.media.type.MediaType; -import static io.helidon.http.Http.HeaderNames.EXPIRES; -import static io.helidon.http.Http.HeaderNames.LAST_MODIFIED; -import static io.helidon.http.Http.HeaderNames.LOCATION; +import static io.helidon.http.HeaderNames.EXPIRES; +import static io.helidon.http.HeaderNames.LAST_MODIFIED; +import static io.helidon.http.HeaderNames.LOCATION; /** * Mutable headers of a server response. @@ -55,7 +55,7 @@ static ServerResponseHeaders create(Headers existing) { /** * Adds one or more acceptedTypes path document formats - * (header {@link io.helidon.http.Http.HeaderNames#ACCEPT_PATCH}). + * (header {@link HeaderNames#ACCEPT_PATCH}). * * @param acceptableMediaTypes media types to add. * @return this instance @@ -66,7 +66,7 @@ default ServerResponseHeaders addAcceptPatches(MediaType... acceptableMediaTypes MediaType acceptableMediaType = acceptableMediaTypes[i]; values[i] = acceptableMediaType.text(); } - return add(Http.Headers.create(Http.HeaderNames.ACCEPT_PATCH, + return add(HeaderValues.create(HeaderNames.ACCEPT_PATCH, values)); } @@ -113,7 +113,7 @@ default ServerResponseHeaders addCookie(String name, String value) { ServerResponseHeaders clearCookie(String name); /** - * Sets the value of {@link io.helidon.http.Http.HeaderNames#LAST_MODIFIED} header. + * Sets the value of {@link HeaderNames#LAST_MODIFIED} header. *

* The last modified date for the requested object * @@ -122,11 +122,11 @@ default ServerResponseHeaders addCookie(String name, String value) { */ default ServerResponseHeaders lastModified(Instant modified) { ZonedDateTime dt = ZonedDateTime.ofInstant(modified, ZoneId.systemDefault()); - return set(Http.Headers.create(LAST_MODIFIED, true, false, dt.format(Http.DateTime.RFC_1123_DATE_TIME))); + return set(HeaderValues.create(LAST_MODIFIED, true, false, dt.format(DateTime.RFC_1123_DATE_TIME))); } /** - * Sets the value of {@link io.helidon.http.Http.HeaderNames#LAST_MODIFIED} header. + * Sets the value of {@link HeaderNames#LAST_MODIFIED} header. *

* The last modified date for the requested object * @@ -134,11 +134,11 @@ default ServerResponseHeaders lastModified(Instant modified) { * @return this instance */ default ServerResponseHeaders lastModified(ZonedDateTime modified) { - return set(Http.Headers.create(LAST_MODIFIED, true, false, modified.format(Http.DateTime.RFC_1123_DATE_TIME))); + return set(HeaderValues.create(LAST_MODIFIED, true, false, modified.format(DateTime.RFC_1123_DATE_TIME))); } /** - * Sets the value of {@link io.helidon.http.Http.HeaderNames#LOCATION} header. + * Sets the value of {@link HeaderNames#LOCATION} header. *

* Used in redirection, or when a new resource has been created. * @@ -146,11 +146,11 @@ default ServerResponseHeaders lastModified(ZonedDateTime modified) { * @return updated headers */ default ServerResponseHeaders location(URI location) { - return set(Http.Headers.create(LOCATION, true, false, location.toASCIIString())); + return set(HeaderValues.create(LOCATION, true, false, location.toASCIIString())); } /** - * Sets the value of {@link io.helidon.http.Http.HeaderNames#EXPIRES} header. + * Sets the value of {@link HeaderNames#EXPIRES} header. *

* The date/time after which the response is considered stale. * @@ -158,11 +158,11 @@ default ServerResponseHeaders location(URI location) { * @return updated headers */ default ServerResponseHeaders expires(ZonedDateTime dateTime) { - return set(Http.Headers.create(EXPIRES, dateTime.format(Http.DateTime.RFC_1123_DATE_TIME))); + return set(HeaderValues.create(EXPIRES, dateTime.format(DateTime.RFC_1123_DATE_TIME))); } /** - * Sets the value of {@link io.helidon.http.Http.HeaderNames#EXPIRES} header. + * Sets the value of {@link HeaderNames#EXPIRES} header. *

* The date/time after which the response is considered stale. * @@ -170,7 +170,7 @@ default ServerResponseHeaders expires(ZonedDateTime dateTime) { * @return updated headers */ default ServerResponseHeaders expires(Instant dateTime) { - return set(Http.Headers.create(EXPIRES, ZonedDateTime.ofInstant(dateTime, ZoneId.systemDefault()) - .format(Http.DateTime.RFC_1123_DATE_TIME))); + return set(HeaderValues.create(EXPIRES, ZonedDateTime.ofInstant(dateTime, ZoneId.systemDefault()) + .format(DateTime.RFC_1123_DATE_TIME))); } } diff --git a/http/http/src/main/java/io/helidon/http/ServerResponseHeadersImpl.java b/http/http/src/main/java/io/helidon/http/ServerResponseHeadersImpl.java index 29f78e59094..5906d5f4aec 100644 --- a/http/http/src/main/java/io/helidon/http/ServerResponseHeadersImpl.java +++ b/http/http/src/main/java/io/helidon/http/ServerResponseHeadersImpl.java @@ -35,7 +35,7 @@ class ServerResponseHeadersImpl extends HeadersImpl imple @Override public ServerResponseHeaders addCookie(SetCookie cookie) { - add(Http.Headers.create(Http.HeaderNames.SET_COOKIE, cookie.toString())); + add(HeaderValues.create(HeaderNames.SET_COOKIE, cookie.toString())); return this; } @@ -46,8 +46,8 @@ public ServerResponseHeaders clearCookie(String name) { .expires(START_OF_YEAR_1970.get()) .build(); - if (contains(Http.HeaderNames.SET_COOKIE)) { - remove(Http.HeaderNames.SET_COOKIE, it -> { + if (contains(HeaderNames.SET_COOKIE)) { + remove(HeaderNames.SET_COOKIE, it -> { List currentValues = it.allValues(); String[] newValues = new String[currentValues.size()]; boolean found = false; @@ -67,7 +67,7 @@ public ServerResponseHeaders clearCookie(String name) { newValues = values; } - set(Http.Headers.create(Http.HeaderNames.SET_COOKIE, newValues)); + set(HeaderValues.create(HeaderNames.SET_COOKIE, newValues)); }); } else { addCookie(expiredCookie); diff --git a/http/http/src/main/java/io/helidon/http/SetCookie.java b/http/http/src/main/java/io/helidon/http/SetCookie.java index 36c36ea7b12..efa15b0b8dd 100644 --- a/http/http/src/main/java/io/helidon/http/SetCookie.java +++ b/http/http/src/main/java/io/helidon/http/SetCookie.java @@ -103,7 +103,7 @@ public static SetCookie parse(String setCookie) { switch (partName.toLowerCase()) { case "expires": hasValue(partName, partValue); - builder.expires(Http.DateTime.parse(partValue)); + builder.expires(DateTime.parse(partValue)); break; case "max-age": hasValue(partName, partValue); @@ -178,7 +178,7 @@ public String toString() { if (expires != null) { result.append(PARAM_SEPARATOR); result.append("Expires="); - result.append(expires.format(Http.DateTime.RFC_1123_DATE_TIME)); + result.append(expires.format(DateTime.RFC_1123_DATE_TIME)); } if ((maxAge != null) && !maxAge.isNegative() && !maxAge.isZero()) { result.append(PARAM_SEPARATOR); diff --git a/http/http/src/main/java/io/helidon/http/Status.java b/http/http/src/main/java/io/helidon/http/Status.java new file mode 100644 index 00000000000..66525c3b0e4 --- /dev/null +++ b/http/http/src/main/java/io/helidon/http/Status.java @@ -0,0 +1,503 @@ +/* + * Copyright (c) 2023 Oracle and/or its affiliates. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.helidon.http; + +import java.util.Objects; + +/** + * Commonly used status codes defined by HTTP, see + * HTTP/1.1 documentation. + * Additional status codes can be added by applications + * by call {@link #create(int)} or {@link #create(int, String)} with unknown status code, or with text + * that differs from the predefined status codes. + *

+ * Although the constants are instances of this class, they can be compared using instance equality, as the only + * way to obtain an instance is through methods {@link #create(int)} {@link #create(int, String)}, which ensures + * the same instance is returned for known status codes and reason phrases. + *

+ * A good reference is the IANA list of HTTP Status Codes (we may not cover all of them in this type): + * IANA HTTP Status Codes + */ +public class Status { + /** + * 100 Continue, + * see HTTP/1.1 documentations. + */ + public static final Status CONTINUE_100 = new Status(100, "Continue", true); + /** + * 101 Switching Protocols, + * see HTTP/1.1 documentations. + */ + public static final Status SWITCHING_PROTOCOLS_101 = new Status(101, "Switching Protocols", true); + /** + * 200 OK, see HTTP/1.1 documentation. + */ + public static final Status OK_200 = new Status(200, "OK", true); + /** + * 201 Created, see HTTP/1.1 documentation. + */ + public static final Status CREATED_201 = new Status(201, "Created", true); + /** + * 202 Accepted, see HTTP/1.1 documentation + * . + */ + public static final Status ACCEPTED_202 = new Status(202, "Accepted", true); + /** + * 204 No Content, see + * HTTP/1.1 documentation. + */ + public static final Status NO_CONTENT_204 = new Status(204, "No Content", true); + /** + * 205 Reset Content, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status RESET_CONTENT_205 = new Status(205, "Reset Content", true); + /** + * 206 Reset Content, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status PARTIAL_CONTENT_206 = new Status(206, "Partial Content", true); + /** + * 301 Moved Permanently, see + * HTTP/1.1 documentation. + */ + public static final Status MOVED_PERMANENTLY_301 = new Status(301, "Moved Permanently", true); + /** + * 302 Found, see HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status FOUND_302 = new Status(302, "Found", true); + /** + * 303 See Other, see + * HTTP/1.1 documentation. + */ + public static final Status SEE_OTHER_303 = new Status(303, "See Other", true); + /** + * 304 Not Modified, see + * HTTP/1.1 documentation. + */ + public static final Status NOT_MODIFIED_304 = new Status(304, "Not Modified", true); + /** + * 305 Use Proxy, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status USE_PROXY_305 = new Status(305, "Use Proxy", true); + /** + * 307 Temporary Redirect, see + * HTTP/1.1 documentation. + */ + public static final Status TEMPORARY_REDIRECT_307 = new Status(307, "Temporary Redirect", true); + /** + * 308 Permanent Redirect, see + * HTTP Status Code 308 documentation. + */ + public static final Status PERMANENT_REDIRECT_308 = new Status(308, "Permanent Redirect", true); + /** + * 400 Bad Request, see + * HTTP/1.1 documentation. + */ + public static final Status BAD_REQUEST_400 = new Status(400, "Bad Request", true); + /** + * 401 Unauthorized, see + * HTTP/1.1 documentation. + */ + public static final Status UNAUTHORIZED_401 = new Status(401, "Unauthorized", true); + /** + * 402 Payment Required, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status PAYMENT_REQUIRED_402 = new Status(402, "Payment Required", true); + /** + * 403 Forbidden, see + * HTTP/1.1 documentation. + */ + public static final Status FORBIDDEN_403 = new Status(403, "Forbidden", true); + /** + * 404 Not Found, see + * HTTP/1.1 documentation. + */ + public static final Status NOT_FOUND_404 = new Status(404, "Not Found", true); + /** + * 405 Method Not Allowed, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status METHOD_NOT_ALLOWED_405 = new Status(405, "Method Not Allowed", true); + /** + * 406 Not Acceptable, see + * HTTP/1.1 documentation. + */ + public static final Status NOT_ACCEPTABLE_406 = new Status(406, "Not Acceptable", true); + /** + * 407 Proxy Authentication Required, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status PROXY_AUTHENTICATION_REQUIRED_407 = new Status(407, "Proxy Authentication Required", true); + /** + * 408 Request Timeout, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status REQUEST_TIMEOUT_408 = new Status(408, "Request Timeout", true); + /** + * 409 Conflict, see + * HTTP/1.1 documentation. + */ + public static final Status CONFLICT_409 = new Status(409, "Conflict", true); + /** + * 410 Gone, see HTTP/1.1 documentation. + */ + public static final Status GONE_410 = new Status(410, "Gone", true); + /** + * 411 Length Required, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status LENGTH_REQUIRED_411 = new Status(411, "Length Required", true); + /** + * 412 Precondition Failed, see + * HTTP/1.1 documentation. + */ + public static final Status PRECONDITION_FAILED_412 = new Status(412, "Precondition Failed", true); + /** + * 413 Request Entity Too Large, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status REQUEST_ENTITY_TOO_LARGE_413 = new Status(413, "Request Entity Too Large", true); + /** + * 414 Request-URI Too Long, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status REQUEST_URI_TOO_LONG_414 = new Status(414, "Request-URI Too Long", true); + /** + * 415 Unsupported Media Type, see + * HTTP/1.1 documentation. + */ + public static final Status UNSUPPORTED_MEDIA_TYPE_415 = new Status(415, "Unsupported Media Type", true); + /** + * 416 Requested Range Not Satisfiable, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status REQUESTED_RANGE_NOT_SATISFIABLE_416 = new Status(416, "Requested Range Not Satisfiable", true); + /** + * 417 Expectation Failed, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status EXPECTATION_FAILED_417 = new Status(417, "Expectation Failed", true); + /** + * 418 I'm a teapot, see + * Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0). + */ + public static final Status I_AM_A_TEAPOT_418 = new Status(418, "I'm a teapot", true); + /** + * Misdirected request, see + * RFC 9110 - Http Semantics. + */ + public static final Status MISDIRECTED_REQUEST_421 = new Status(421, "Misdirected Request", true); + /** + * Unprocessable content, see + * RFC 9110 - Http Semantics. + */ + public static final Status UNPROCESSABLE_CONTENT_422 = new Status(422, "Unprocessable Content", true); + /** + * Locked, see + * RFC 4918 - HTTP Extensions for WebDAV. + */ + public static final Status LOCKED_423 = new Status(423, "Locked", true); + /** + * Failed dependency, see + * RFC 4918 - HTTP Extensions for WebDAV. + */ + public static final Status FAILED_DEPENDENCY_424 = new Status(424, "Failed Dependency", true); + /** + * Upgrade required, see + * RFC 9110 - Http Semantics. + */ + public static final Status UPGRADE_REQUIRED_426 = new Status(426, "Upgrade Required", true); + /** + * Precondition required, see + * RFC 6585 - Additional HTTP Status Codes. + */ + public static final Status PRECONDITION_REQUIRED_428 = new Status(428, "Precondition Required", true); + /** + * Too many requests, see + * RFC 6585 - Additional HTTP Status Codes. + */ + public static final Status TOO_MANY_REQUESTS_429 = new Status(429, "Too Many Requests", true); + /** + * 500 Internal Server Error, see + * HTTP/1.1 documentation. + */ + public static final Status INTERNAL_SERVER_ERROR_500 = new Status(500, "Internal Server Error", true); + /** + * 501 Not Implemented, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status NOT_IMPLEMENTED_501 = new Status(501, "Not Implemented", true); + /** + * 502 Bad Gateway, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status BAD_GATEWAY_502 = new Status(502, "Bad Gateway", true); + /** + * 503 Service Unavailable, see + * HTTP/1.1 documentation. + */ + public static final Status SERVICE_UNAVAILABLE_503 = new Status(503, "Service Unavailable", true); + /** + * 504 Gateway Timeout, see + * HTTP/1.1 documentation. + * + * @since 2.0 + */ + public static final Status GATEWAY_TIMEOUT_504 = new Status(504, "Gateway Timeout", true); + /** + * 505 HTTP Version Not Supported, see + * HTTP/1.1 documentation. + * + * @since 3.0.3 + */ + public static final Status HTTP_VERSION_NOT_SUPPORTED_505 = new Status(505, "HTTP Version Not Supported", true); + + static { + // THIS MUST BE AFTER THE LAST CONSTANT + StatusHelper.statusesDone(); + } + + private final int code; + private final String reason; + private final Family family; + private final String codeText; + private final String stringValue; + + private Status(int statusCode, String reasonPhrase, boolean instance) { + this.code = statusCode; + this.reason = reasonPhrase; + this.family = Family.of(statusCode); + this.codeText = String.valueOf(code); + this.stringValue = code + " " + reason; + + if (instance) { + StatusHelper.add(this); + } + } + + private Status(int statusCode, String reasonPhrase, Family family, String codeText) { + // for custom codes + this.code = statusCode; + this.reason = reasonPhrase; + this.family = family; + this.codeText = codeText; + this.stringValue = code + " " + reason; + } + + /** + * Convert a numerical status code into the corresponding Status. + *

+ * For an unknown code, an ad-hoc {@link Status} is created. + * + * @param statusCode the numerical status code + * @return the matching Status; either a constant from this class, or an ad-hoc {@link Status} + */ + public static Status create(int statusCode) { + Status found = StatusHelper.find(statusCode); + + if (found == null) { + return createNew(Family.of(statusCode), statusCode, "", String.valueOf(statusCode)); + } + return found; + } + + /** + * Convert a numerical status code into the corresponding Status. + *

+ * It either returns an existing {@link Status} constant if possible. + * For an unknown code, or code/reason phrase combination it creates + * an ad-hoc {@link Status}. + * + * @param statusCode the numerical status code + * @param reasonPhrase the reason phrase; if {@code null} or a known reason phrase, an instance with the default + * phrase is returned; otherwise, a new instance is returned + * @return the matching Status + */ + public static Status create(int statusCode, String reasonPhrase) { + Status found = StatusHelper.find(statusCode); + if (found == null) { + return createNew(Family.of(statusCode), statusCode, reasonPhrase, String.valueOf(statusCode)); + } + if (reasonPhrase == null) { + return found; + } + if (found.reasonPhrase().equalsIgnoreCase(reasonPhrase)) { + return found; + } + return createNew(found.family(), statusCode, reasonPhrase, found.codeText()); + } + + private static Status createNew(Family family, int statusCode, String reasonPhrase, String codeText) { + return new Status(statusCode, reasonPhrase, family, codeText); + } + + /** + * Get the associated integer value representing the status code. + * + * @return the integer value representing the status code. + */ + public int code() { + return code; + } + + /** + * Get the class of status code. + * + * @return the class of status code. + */ + public Family family() { + return family; + } + + /** + * Get the reason phrase. + * + * @return the reason phrase. + */ + public String reasonPhrase() { + return reason; + } + + /** + * Text of the {@link #code()}. + * + * @return code string (number as a string) + */ + public String codeText() { + return codeText; + } + + /** + * Get the response status as string. + * + * @return the response status string in the form of a partial HTTP response status line, + * i.e. {@code "Status-Code SP Reason-Phrase"}. + */ + public String toString() { + return stringValue; + } + + /** + * Text of the status as used in HTTP/1, such as "200 OK". + * + * @return text of this status + */ + public String text() { + return stringValue; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Status status = (Status) o; + return code == status.code && reason.equals(status.reason); + } + + @Override + public int hashCode() { + return Objects.hash(code, reason); + } + + /** + * An enumeration representing the class of status code. Family is used + * here since class is overloaded in Java. + *

+ * Copied from JAX-RS. + */ + public enum Family { + + /** + * {@code 1xx} HTTP status codes. + */ + INFORMATIONAL, + /** + * {@code 2xx} HTTP status codes. + */ + SUCCESSFUL, + /** + * {@code 3xx} HTTP status codes. + */ + REDIRECTION, + /** + * {@code 4xx} HTTP status codes. + */ + CLIENT_ERROR, + /** + * {@code 5xx} HTTP status codes. + */ + SERVER_ERROR, + /** + * Other, unrecognized HTTP status codes. + */ + OTHER; + + /** + * Get the family for the response status code. + * + * @param statusCode response status code to get the family for. + * @return family of the response status code. + */ + public static Family of(int statusCode) { + return switch (statusCode / 100) { + case 1 -> Family.INFORMATIONAL; + case 2 -> Family.SUCCESSFUL; + case 3 -> Family.REDIRECTION; + case 4 -> Family.CLIENT_ERROR; + case 5 -> Family.SERVER_ERROR; + default -> Family.OTHER; + }; + } + } +} diff --git a/http/http/src/main/java/io/helidon/http/StatusHelper.java b/http/http/src/main/java/io/helidon/http/StatusHelper.java index a77de58e3c9..679557c2109 100644 --- a/http/http/src/main/java/io/helidon/http/StatusHelper.java +++ b/http/http/src/main/java/io/helidon/http/StatusHelper.java @@ -19,13 +19,13 @@ import java.util.List; final class StatusHelper { - private static final List KNOWN = new ArrayList<>(40); + private static final List KNOWN = new ArrayList<>(40); private static StatusPair[] statuses; private StatusHelper() { } - static Http.Status find(int statusCode) { + static Status find(int statusCode) { for (StatusPair status : statuses) { if (status.code == statusCode) { return status.status; @@ -35,7 +35,7 @@ static Http.Status find(int statusCode) { return null; } - static void add(Http.Status status) { + static void add(Status status) { KNOWN.add(status); } @@ -47,8 +47,8 @@ static void statusesDone() { KNOWN.clear(); } - private record StatusPair(int code, Http.Status status) { - public static StatusPair create(Http.Status status) { + private record StatusPair(int code, Status status) { + public static StatusPair create(Status status) { return new StatusPair(status.code(), status); } } diff --git a/http/http/src/main/java/io/helidon/http/UnauthorizedException.java b/http/http/src/main/java/io/helidon/http/UnauthorizedException.java index f52e4ed0ea2..7bee9cdd6d3 100644 --- a/http/http/src/main/java/io/helidon/http/UnauthorizedException.java +++ b/http/http/src/main/java/io/helidon/http/UnauthorizedException.java @@ -16,10 +16,10 @@ package io.helidon.http; -import static io.helidon.http.Http.Status.UNAUTHORIZED_401; +import static io.helidon.http.Status.UNAUTHORIZED_401; /** - * A runtime exception indicating a {@link Http.Status#UNAUTHORIZED_401 unauthorized}. + * A runtime exception indicating a {@link Status#UNAUTHORIZED_401 unauthorized}. */ public class UnauthorizedException extends HttpException { diff --git a/http/http/src/main/java/io/helidon/http/WritableHeaders.java b/http/http/src/main/java/io/helidon/http/WritableHeaders.java index 3be2232417b..5ce520d220d 100644 --- a/http/http/src/main/java/io/helidon/http/WritableHeaders.java +++ b/http/http/src/main/java/io/helidon/http/WritableHeaders.java @@ -20,8 +20,6 @@ import java.util.function.Consumer; import io.helidon.common.media.type.MediaType; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderName; /** * HTTP Headers that are mutable. @@ -54,7 +52,7 @@ static WritableHeaders create(Headers headers) { * @param header header with value to set * @return this instance */ - B setIfAbsent(Http.Header header); + B setIfAbsent(Header header); /** * Add a header or add a header value if the header is already present. @@ -72,7 +70,7 @@ static WritableHeaders create(Headers headers) { * @return this instance */ default B add(HeaderName header, String... value) { - return add(Http.Headers.create(header, value)); + return add(HeaderValues.create(header, value)); } /** @@ -83,7 +81,7 @@ default B add(HeaderName header, String... value) { * @return this instance */ default B add(HeaderName header, int value) { - return add(Http.Headers.create(header, value)); + return add(HeaderValues.create(header, value)); } /** @@ -94,7 +92,7 @@ default B add(HeaderName header, int value) { * @return this instance */ default B add(HeaderName header, long value) { - return add(Http.Headers.create(header, value)); + return add(HeaderValues.create(header, value)); } /** @@ -122,7 +120,7 @@ default B add(HeaderName header, long value) { * @return this instance */ default B contentType(MediaType contentType) { - return set(Http.Headers.create(HeaderNameEnum.CONTENT_TYPE, contentType.text())); + return set(HeaderValues.create(HeaderNameEnum.CONTENT_TYPE, contentType.text())); } /** @@ -131,11 +129,11 @@ default B contentType(MediaType contentType) { * @param header header to set * @return this instance */ - B set(Http.Header header); + B set(Header header); /** * Set a header and replace it if it already existed. - * Use {@link #set(io.helidon.http.Http.Header)} for headers that are known in advance (use a constant), + * Use {@link #set(Header)} for headers that are known in advance (use a constant), * or for headers obtained from Helidon server or client. This method is intended for headers that are unknown or change * value often. * @@ -144,13 +142,13 @@ default B contentType(MediaType contentType) { * @return this instance */ default B set(HeaderName name, String... values) { - return set(Http.Headers.create(name, true, false, values)); + return set(HeaderValues.create(name, true, false, values)); } /** * Set a header and replace it if it already existed. - * Use {@link #set(io.helidon.http.Http.Header)} for headers that are known in advance (use a constant), + * Use {@link #set(Header)} for headers that are known in advance (use a constant), * or for headers obtained from Helidon server or client. This method is intended for headers that are unknown or change * value often. * @@ -159,12 +157,12 @@ default B set(HeaderName name, String... values) { * @return this instance */ default B set(HeaderName name, int value) { - return set(Http.Headers.create(name, true, false, value)); + return set(HeaderValues.create(name, true, false, value)); } /** * Set a header and replace it if it already existed. - * Use {@link #set(io.helidon.http.Http.Header)} for headers that are known in advance (use a constant), + * Use {@link #set(Header)} for headers that are known in advance (use a constant), * or for headers obtained from Helidon server or client. This method is intended for headers that are unknown or change * value often. * @@ -173,12 +171,12 @@ default B set(HeaderName name, int value) { * @return this instance */ default B set(HeaderName name, long value) { - return set(Http.Headers.create(name, true, false, value)); + return set(HeaderValues.create(name, true, false, value)); } /** * Set a header and replace it if it already existed. - * Use {@link #set(io.helidon.http.Http.Header)} for headers that are known in advance (use a constant), + * Use {@link #set(Header)} for headers that are known in advance (use a constant), * or for headers obtained from Helidon server or client. This method is intended for headers that are unknown or change * value often. * @@ -187,7 +185,7 @@ default B set(HeaderName name, long value) { * @return this instance */ default B set(HeaderName name, Collection values) { - return set(Http.Headers.create(name, values)); + return set(HeaderValues.create(name, values)); } /** @@ -200,7 +198,7 @@ default B set(HeaderName name, Collection values) { * @return this instance */ default B contentLength(long length) { - return set(Http.Headers.create(HeaderNameEnum.CONTENT_LENGTH, + return set(HeaderValues.create(HeaderNameEnum.CONTENT_LENGTH, true, false, String.valueOf(length))); diff --git a/http/http/src/test/java/io/helidon/http/ContentDispositionTest.java b/http/http/src/test/java/io/helidon/http/ContentDispositionTest.java index 85dc4b8f5ad..bef61a70b63 100644 --- a/http/http/src/test/java/io/helidon/http/ContentDispositionTest.java +++ b/http/http/src/test/java/io/helidon/http/ContentDispositionTest.java @@ -230,7 +230,7 @@ void testQuotes() { @Test void testDateQuotes() { ZonedDateTime zonedDateTime = ZonedDateTime.now(); - String date = zonedDateTime.format(Http.DateTime.RFC_1123_DATE_TIME); + String date = zonedDateTime.format(DateTime.RFC_1123_DATE_TIME); // order is in order of insertion backed by LinkedMap -> we want to preserve this String template = "form-data;" + "creation-date=\"" + date + "\";" diff --git a/http/http/src/test/java/io/helidon/http/CookieParserTest.java b/http/http/src/test/java/io/helidon/http/CookieParserTest.java index bc6a6e29220..06212724262 100644 --- a/http/http/src/test/java/io/helidon/http/CookieParserTest.java +++ b/http/http/src/test/java/io/helidon/http/CookieParserTest.java @@ -20,7 +20,7 @@ import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.COOKIE; +import static io.helidon.http.HeaderNames.COOKIE; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; @@ -30,7 +30,7 @@ class CookieParserTest { @Test public void rfc2965() throws Exception { String header = "$version=1; foo=bar; $Domain=google.com, aaa=bbb, c=cool; $Domain=google.com; $Path=\"/foo\""; - Parameters p = CookieParser.parse(Http.Headers.create(COOKIE, header)); + Parameters p = CookieParser.parse(HeaderValues.create(COOKIE, header)); assertThat(p, notNullValue()); assertThat(p.all("foo"), contains("bar")); assertThat(p.all("aaa"), contains("bbb")); @@ -42,7 +42,7 @@ public void rfc2965() throws Exception { @Test public void unquote() throws Exception { - Parameters p = CookieParser.parse(Http.Headers.create(COOKIE, "foo=\"bar\"; aaa=bbb; c=\"what_the_hell\"; aaa=\"ccc\"")); + Parameters p = CookieParser.parse(HeaderValues.create(COOKIE, "foo=\"bar\"; aaa=bbb; c=\"what_the_hell\"; aaa=\"ccc\"")); assertThat(p, notNullValue()); assertThat(p.all("foo"), contains("bar")); assertThat(p.all("aaa"), contains("bbb", "ccc")); @@ -56,7 +56,7 @@ void testEmpty() { @Test void testMultiValueSingleHeader() { - Parameters cookies = CookieParser.parse(Http.Headers.create(COOKIE, "foo=bar; aaa=bbb; c=here; aaa=ccc")); + Parameters cookies = CookieParser.parse(HeaderValues.create(COOKIE, "foo=bar; aaa=bbb; c=here; aaa=ccc")); assertThat(cookies, notNullValue()); assertThat(cookies.all("foo"), contains("bar")); assertThat(cookies.all("aaa"), contains("bbb", "ccc")); @@ -65,7 +65,7 @@ void testMultiValueSingleHeader() { @Test void testMultiValueMultiHeader() { - Parameters cookies = CookieParser.parse(Http.Headers.create(COOKIE, "foo=bar; aaa=bbb; c=here", "aaa=ccc")); + Parameters cookies = CookieParser.parse(HeaderValues.create(COOKIE, "foo=bar; aaa=bbb; c=here", "aaa=ccc")); assertThat(cookies, notNullValue()); assertThat(cookies.all("foo"), contains("bar")); assertThat(cookies.all("aaa"), contains("bbb", "ccc")); diff --git a/http/http/src/test/java/io/helidon/http/DateTimeTest.java b/http/http/src/test/java/io/helidon/http/DateTimeTest.java index 9c0bc8f8e53..d35265bbc56 100644 --- a/http/http/src/test/java/io/helidon/http/DateTimeTest.java +++ b/http/http/src/test/java/io/helidon/http/DateTimeTest.java @@ -27,7 +27,7 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; /** - * Tests {@link Http.DateTime}. + * Tests {@link DateTime}. */ public class DateTimeTest { @@ -37,48 +37,48 @@ public class DateTimeTest { @Test public void rfc1123() { String text = "Tue, 3 Jun 2008 11:05:30 GMT"; - ZonedDateTime zdt = ZonedDateTime.parse(text, Http.DateTime.RFC_1123_DATE_TIME); + ZonedDateTime zdt = ZonedDateTime.parse(text, DateTime.RFC_1123_DATE_TIME); assertThat(zdt, is(ZDT)); - assertThat(zdt.format(Http.DateTime.RFC_1123_DATE_TIME), is(text)); + assertThat(zdt.format(DateTime.RFC_1123_DATE_TIME), is(text)); text = "Tue, 17 Jun 2008 11:05:30 GMT"; - zdt = ZonedDateTime.parse(text, Http.DateTime.RFC_1123_DATE_TIME); + zdt = ZonedDateTime.parse(text, DateTime.RFC_1123_DATE_TIME); assertThat(zdt, is(ZDT2)); - assertThat(zdt.format(Http.DateTime.RFC_1123_DATE_TIME), is(text)); + assertThat(zdt.format(DateTime.RFC_1123_DATE_TIME), is(text)); } @Test public void rfc850() { assumeTrue(LocalDate.now().getYear() < 2057); String text = "Tuesday, 03-Jun-08 11:05:30 GMT"; - ZonedDateTime zdt = ZonedDateTime.parse(text, Http.DateTime.RFC_850_DATE_TIME); + ZonedDateTime zdt = ZonedDateTime.parse(text, DateTime.RFC_850_DATE_TIME); assertThat(zdt, is(ZDT)); - assertThat(zdt.format(Http.DateTime.RFC_850_DATE_TIME), is(text)); + assertThat(zdt.format(DateTime.RFC_850_DATE_TIME), is(text)); text = "Tuesday, 17-Jun-08 11:05:30 GMT"; - zdt = ZonedDateTime.parse(text, Http.DateTime.RFC_850_DATE_TIME); + zdt = ZonedDateTime.parse(text, DateTime.RFC_850_DATE_TIME); assertThat(zdt, is(ZDT2)); - assertThat(zdt.format(Http.DateTime.RFC_850_DATE_TIME), is(text)); + assertThat(zdt.format(DateTime.RFC_850_DATE_TIME), is(text)); } @Test public void rfc851() { String text = "Tue Jun 3 11:05:30 2008"; - ZonedDateTime zdt = ZonedDateTime.parse(text, Http.DateTime.ASCTIME_DATE_TIME); + ZonedDateTime zdt = ZonedDateTime.parse(text, DateTime.ASCTIME_DATE_TIME); assertThat(zdt, is(ZDT)); - assertThat(zdt.format(Http.DateTime.ASCTIME_DATE_TIME), is(text)); + assertThat(zdt.format(DateTime.ASCTIME_DATE_TIME), is(text)); text = "Tue Jun 17 11:05:30 2008"; - zdt = ZonedDateTime.parse(text, Http.DateTime.ASCTIME_DATE_TIME); + zdt = ZonedDateTime.parse(text, DateTime.ASCTIME_DATE_TIME); assertThat(zdt, is(ZDT2)); - assertThat(zdt.format(Http.DateTime.ASCTIME_DATE_TIME), is(text)); + assertThat(zdt.format(DateTime.ASCTIME_DATE_TIME), is(text)); } @Test public void parse() { - assertThat(Http.DateTime.parse("Tue, 3 Jun 2008 11:05:30 GMT"), is(ZDT)); - assertThat(Http.DateTime.parse("Tuesday, 03-Jun-08 11:05:30 GMT"), is(ZDT)); - assertThat(Http.DateTime.parse("Tue Jun 3 11:05:30 2008"), is(ZDT)); + assertThat(DateTime.parse("Tue, 3 Jun 2008 11:05:30 GMT"), is(ZDT)); + assertThat(DateTime.parse("Tuesday, 03-Jun-08 11:05:30 GMT"), is(ZDT)); + assertThat(DateTime.parse("Tue Jun 3 11:05:30 2008"), is(ZDT)); } } diff --git a/http/http/src/test/java/io/helidon/http/ForwardedTest.java b/http/http/src/test/java/io/helidon/http/ForwardedTest.java index 0564e14f04d..f3b13d9ff76 100644 --- a/http/http/src/test/java/io/helidon/http/ForwardedTest.java +++ b/http/http/src/test/java/io/helidon/http/ForwardedTest.java @@ -73,7 +73,7 @@ void testAll() { @Test void testMultiValuesCommaSeparated() { HeadersImpl headers = new HeadersImpl<>(); - headers.add(Http.HeaderNames.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10,by=\"192.0.2.60\""); + headers.add(HeaderNames.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10,by=\"192.0.2.60\""); List forwardedList = Forwarded.create(headers); assertThat(forwardedList, hasSize(2)); @@ -94,7 +94,7 @@ void testMultiValuesCommaSeparated() { @Test void testMultiValues() { HeadersImpl headers = new HeadersImpl<>(); - headers.add(Http.HeaderNames.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10", + headers.add(HeaderNames.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10", "by=\"192.0.2.60\""); List forwardedList = Forwarded.create(headers); @@ -116,7 +116,7 @@ void testMultiValues() { @Test void testMultiValuesAndCommaSeparated() { HeadersImpl headers = new HeadersImpl<>(); - headers.add(Http.HeaderNames.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10", + headers.add(HeaderNames.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10", "by=\"192.0.2.60\",for=\"14.22.11.22\""); List forwardedList = Forwarded.create(headers); diff --git a/http/http/src/test/java/io/helidon/http/HeaderNamesTest.java b/http/http/src/test/java/io/helidon/http/HeaderNamesTest.java index 5f309c8917c..0a454d52ad4 100644 --- a/http/http/src/test/java/io/helidon/http/HeaderNamesTest.java +++ b/http/http/src/test/java/io/helidon/http/HeaderNamesTest.java @@ -34,7 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertAll; class HeaderNamesTest { - private static final Class clazz = Http.HeaderNames.class; + private static final Class clazz = HeaderNames.class; private static final Set constants = Stream.of(clazz.getDeclaredFields()) .filter(it -> Modifier.isStatic(it.getModifiers())) .filter(it -> Modifier.isFinal(it.getModifiers())) @@ -63,11 +63,11 @@ void testAllConstantsAreValid() throws NoSuchFieldException, IllegalAccessExcept // this is to test correct initialization (there may be an issue when the constants // are defined on the interface and implemented by enum outside of it) for (String constant : constants) { - if (!Http.HeaderName.class.equals(clazz.getField(constant).getType())) { + if (!HeaderName.class.equals(clazz.getField(constant).getType())) { continue; } - Http.HeaderName value = (Http.HeaderName) clazz.getField(constant) + HeaderName value = (HeaderName) clazz.getField(constant) .get(null); assertAll( @@ -82,24 +82,24 @@ void testAllConstantsAreValid() throws NoSuchFieldException, IllegalAccessExcept @Test void testEqualsAndHashCodeKnownHeader() { - Http.HeaderName customAccept = Http.HeaderNames.create("ACCEPT"); + HeaderName customAccept = HeaderNames.create("ACCEPT"); - assertThat(customAccept, equalTo(Http.HeaderNames.ACCEPT)); - assertThat(Http.HeaderNames.ACCEPT, equalTo(customAccept)); - assertThat(customAccept.hashCode(), is(Http.HeaderNames.ACCEPT.hashCode())); + assertThat(customAccept, equalTo(HeaderNames.ACCEPT)); + assertThat(HeaderNames.ACCEPT, equalTo(customAccept)); + assertThat(customAccept.hashCode(), is(HeaderNames.ACCEPT.hashCode())); - customAccept = Http.HeaderNames.create("accept", "ACCEPT"); + customAccept = HeaderNames.create("accept", "ACCEPT"); - assertThat(customAccept, equalTo(Http.HeaderNames.ACCEPT)); - assertThat(Http.HeaderNames.ACCEPT, equalTo(customAccept)); - assertThat(customAccept.hashCode(), is(Http.HeaderNames.ACCEPT.hashCode())); + assertThat(customAccept, equalTo(HeaderNames.ACCEPT)); + assertThat(HeaderNames.ACCEPT, equalTo(customAccept)); + assertThat(customAccept.hashCode(), is(HeaderNames.ACCEPT.hashCode())); } @Test void testEqualsAndHashCodeCustomHeader() { - Http.HeaderName custom1 = Http.HeaderNames.create("My-Custom-Header"); - Http.HeaderName custom2 = Http.HeaderNames.create("my-custom-header"); + HeaderName custom1 = HeaderNames.create("My-Custom-Header"); + HeaderName custom2 = HeaderNames.create("my-custom-header"); assertThat(custom1, equalTo(custom2)); @@ -107,8 +107,8 @@ void testEqualsAndHashCodeCustomHeader() { assertThat(custom1.hashCode(), is(custom2.hashCode())); - custom1 = Http.HeaderNames.create("my-custom-header", "My-Custom-Header"); - custom2 = Http.HeaderNames.create("my-custom-header", "my-custom-header"); + custom1 = HeaderNames.create("my-custom-header", "My-Custom-Header"); + custom2 = HeaderNames.create("my-custom-header", "my-custom-header"); assertThat(custom1, equalTo(custom2)); assertThat(custom2, equalTo(custom1)); diff --git a/http/http/src/test/java/io/helidon/http/Http1HeadersParserTest.java b/http/http/src/test/java/io/helidon/http/Http1HeadersParserTest.java index dfb124857db..72a1ab1db8f 100644 --- a/http/http/src/test/java/io/helidon/http/Http1HeadersParserTest.java +++ b/http/http/src/test/java/io/helidon/http/Http1HeadersParserTest.java @@ -62,7 +62,7 @@ void testHeadersWithValidationEnabled(String headerName, String headerValue, boo WritableHeaders headers; if (expectsValid) { headers = getHeaders(headerName, headerValue, true); - String responseHeaderValue = headers.get(Http.HeaderNames.create(headerName)).values(); + String responseHeaderValue = headers.get(HeaderNames.create(headerName)).values(); // returned header values WhiteSpaces are trimmed so need to be tested with trimmed values assertThat(responseHeaderValue, is(headerValue.trim())); } else { @@ -76,7 +76,7 @@ void testHeadersWithValidationEnabled(String headerName, String headerValue, boo void testHeadersWithValidationDisabled(String headerValue) { // retrieve headers without validating WritableHeaders headers = getHeaders(CUSTOM_HEADER_NAME, headerValue, false); - String responseHeaderValue = headers.get(Http.HeaderNames.create(CUSTOM_HEADER_NAME)).values(); + String responseHeaderValue = headers.get(HeaderNames.create(CUSTOM_HEADER_NAME)).values(); // returned header values WhiteSpaces are trimmed so need to be tested with trimmed values assertThat(responseHeaderValue, is(headerValue.trim())); } @@ -116,7 +116,7 @@ private static Stream headers() { private void testHeader(Headers headers, String header, String... values) { - Http.HeaderName headerName = Http.HeaderNames.create(header); + HeaderName headerName = HeaderNames.create(header); assertThat("Headers should contain header: " + headerName.lowerCase(), headers.contains(headerName), is(true)); diff --git a/http/http/src/test/java/io/helidon/http/HttpMethodTest.java b/http/http/src/test/java/io/helidon/http/HttpMethodTest.java index a9c0eeb9063..8a10d952010 100644 --- a/http/http/src/test/java/io/helidon/http/HttpMethodTest.java +++ b/http/http/src/test/java/io/helidon/http/HttpMethodTest.java @@ -30,7 +30,7 @@ import static org.junit.jupiter.api.Assertions.assertAll; class HttpMethodTest { - private static final Class clazz = Http.Method.class; + private static final Class clazz = Method.class; private static final Set constants = Stream.of(clazz.getDeclaredFields()) .filter(it -> Modifier.isStatic(it.getModifiers())) .filter(it -> Modifier.isFinal(it.getModifiers())) @@ -44,7 +44,7 @@ void testAllConstantsAreValid() throws NoSuchFieldException, IllegalAccessExcept // this is to test correct initialization (there may be an issue when the constants // are defined on the interface and implemented by enum outside of it) for (String constant : constants) { - Http.Method value = (Http.Method) clazz.getField(constant) + Method value = (Method) clazz.getField(constant) .get(null); assertAll( diff --git a/http/http/src/test/java/io/helidon/http/HttpPrologueTest.java b/http/http/src/test/java/io/helidon/http/HttpPrologueTest.java index d0c510fcc4b..accaaf7b9c3 100644 --- a/http/http/src/test/java/io/helidon/http/HttpPrologueTest.java +++ b/http/http/src/test/java/io/helidon/http/HttpPrologueTest.java @@ -27,14 +27,14 @@ void testPrologueWithAll() { HttpPrologue prologue = HttpPrologue.create("HTTP/1.1", "HTTP", "1.1", - Http.Method.GET, + Method.GET, "/admin;a=b/list;c=d;e=f?first=second#fragment", true); assertThat(prologue.rawProtocol(), is("HTTP/1.1")); assertThat(prologue.protocol(), is("HTTP")); assertThat(prologue.protocolVersion(), is("1.1")); - assertThat(prologue.method(), is(Http.Method.GET)); + assertThat(prologue.method(), is(Method.GET)); assertThat(prologue.uriPath().rawPathNoParams(), is("/admin/list")); assertThat(prologue.query().rawValue(), is("first=second")); assertThat(prologue.fragment().hasValue(), is(true)); @@ -48,14 +48,14 @@ void testPrologueEncodedPath() { HttpPrologue prologue = HttpPrologue.create("HTTP/1.1", "HTTP", "1.1", - Http.Method.GET, + Method.GET, path, true); assertThat(prologue.rawProtocol(), is("HTTP/1.1")); assertThat(prologue.protocol(), is("HTTP")); assertThat(prologue.protocolVersion(), is("1.1")); - assertThat(prologue.method(), is(Http.Method.GET)); + assertThat(prologue.method(), is(Method.GET)); assertThat(prologue.uriPath().rawPathNoParams(), is("/one/two")); assertThat(prologue.query().rawValue(), is("a=b%26c=d&e=f&e=g&h=x%63%23e%3c")); assertThat(prologue.fragment().hasValue(), is(true)); diff --git a/http/http/src/test/java/io/helidon/http/HttpStatusTest.java b/http/http/src/test/java/io/helidon/http/HttpStatusTest.java index 2e9985d492e..a7fdf7d4c9b 100644 --- a/http/http/src/test/java/io/helidon/http/HttpStatusTest.java +++ b/http/http/src/test/java/io/helidon/http/HttpStatusTest.java @@ -35,7 +35,7 @@ import static org.junit.jupiter.api.Assertions.assertAll; class HttpStatusTest { - private static final Class clazz = Http.Status.class; + private static final Class clazz = Status.class; private static final Set constants = Stream.of(clazz.getDeclaredFields()) .filter(it -> Modifier.isStatic(it.getModifiers())) .filter(it -> Modifier.isFinal(it.getModifiers())) @@ -43,20 +43,20 @@ class HttpStatusTest { .map(Field::getName) .collect(Collectors.toSet()); - Http.Status custom999_1 = Http.Status.create(999); - Http.Status custom999_2 = Http.Status.create(999); + Status custom999_1 = Status.create(999); + Status custom999_2 = Status.create(999); @Test void testSameInstanceForKnownStatus() { - Http.Status ok = Http.Status.create(200); - Http.Status okFromBoth = Http.Status.create(200, Http.Status.OK_200.reasonPhrase()); - Http.Status custom = Http.Status.create(200, "Very-Fine"); + Status ok = Status.create(200); + Status okFromBoth = Status.create(200, Status.OK_200.reasonPhrase()); + Status custom = Status.create(200, "Very-Fine"); - assertThat("Status from code must be the enum instance", ok, sameInstance(Http.Status.OK_200)); + assertThat("Status from code must be the enum instance", ok, sameInstance(Status.OK_200)); assertThat("Status from code an reason phrase that matches must be the enum instance", okFromBoth, - sameInstance(Http.Status.OK_200)); - assertThat("Status from code with custom phrase must differ", custom, not(sameInstance(Http.Status.OK_200))); + sameInstance(Status.OK_200)); + assertThat("Status from code with custom phrase must differ", custom, not(sameInstance(Status.OK_200))); assertThat("Custom reason phrase should be present", custom.reasonPhrase(), is("Very-Fine")); } @@ -71,7 +71,7 @@ void testAllConstantsAreValid() throws NoSuchFieldException, IllegalAccessExcept // this is to test correct initialization (there may be an issue when the constants // are defined on the interface and implemented by enum outside of it) for (String constant : constants) { - Http.Status value = (Http.Status) clazz.getField(constant) + Status value = (Status) clazz.getField(constant) .get(null); assertAll( @@ -83,7 +83,7 @@ void testAllConstantsAreValid() throws NoSuchFieldException, IllegalAccessExcept () -> assertThat(constant, endsWith("_" + value.code())), () -> { // except for teapot - if (value != Http.Status.I_AM_A_TEAPOT_418) { + if (value != Status.I_AM_A_TEAPOT_418) { assertThat(constant, startsWith(value.reasonPhrase() .toUpperCase(Locale.ROOT) diff --git a/http/http/src/test/java/io/helidon/http/HttpTest.java b/http/http/src/test/java/io/helidon/http/HttpTest.java index 7bc8153963c..483b0a1aafb 100644 --- a/http/http/src/test/java/io/helidon/http/HttpTest.java +++ b/http/http/src/test/java/io/helidon/http/HttpTest.java @@ -27,7 +27,6 @@ import org.junit.jupiter.params.provider.MethodSource; import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.sameInstance; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.params.provider.Arguments.arguments; @@ -38,31 +37,31 @@ class HttpTest { @Test void testStatusIsStatus() { - Http.Status rs = Http.Status.create(Http.Status.TEMPORARY_REDIRECT_307.code()); - assertThat(rs, sameInstance(Http.Status.TEMPORARY_REDIRECT_307)); + Status rs = Status.create(Status.TEMPORARY_REDIRECT_307.code()); + assertThat(rs, sameInstance(Status.TEMPORARY_REDIRECT_307)); } @Test void testStatusWithReasonIsStatus() { - Http.Status rs = Http.Status - .create(Http.Status.TEMPORARY_REDIRECT_307.code(), Http.Status.TEMPORARY_REDIRECT_307.reasonPhrase().toUpperCase()); - assertThat(rs, sameInstance(Http.Status.TEMPORARY_REDIRECT_307)); + Status rs = Status + .create(Status.TEMPORARY_REDIRECT_307.code(), Status.TEMPORARY_REDIRECT_307.reasonPhrase().toUpperCase()); + assertThat(rs, sameInstance(Status.TEMPORARY_REDIRECT_307)); } @Test void testResposneStatusCustomReason() { - Http.Status rs = Http.Status - .create(Http.Status.TEMPORARY_REDIRECT_307.code(), "Custom reason phrase"); - assertThat(rs, CoreMatchers.not(Http.Status.TEMPORARY_REDIRECT_307)); + Status rs = Status + .create(Status.TEMPORARY_REDIRECT_307.code(), "Custom reason phrase"); + assertThat(rs, CoreMatchers.not(Status.TEMPORARY_REDIRECT_307)); assertThat(rs.reasonPhrase(), is("Custom reason phrase")); - MatcherAssert.assertThat(rs.code(), CoreMatchers.is(Http.Status.TEMPORARY_REDIRECT_307.code())); - MatcherAssert.assertThat(rs.family(), CoreMatchers.is(Http.Status.TEMPORARY_REDIRECT_307.family())); + MatcherAssert.assertThat(rs.code(), CoreMatchers.is(Status.TEMPORARY_REDIRECT_307.code())); + MatcherAssert.assertThat(rs.family(), CoreMatchers.is(Status.TEMPORARY_REDIRECT_307.family())); } @ParameterizedTest @MethodSource("headers") void testHeaderValidation(String headerName, String headerValues, boolean expectsValid) { - Http.Header header = Http.Headers.create(headerName, headerValues); + Header header = HeaderValues.create(headerName, headerValues); if (expectsValid) { header.validate(); } else { diff --git a/http/http2/src/main/java/io/helidon/http/http2/Http2Headers.java b/http/http2/src/main/java/io/helidon/http/http2/Http2Headers.java index 2846fe648f3..259e9b54569 100644 --- a/http/http2/src/main/java/io/helidon/http/http2/Http2Headers.java +++ b/http/http2/src/main/java/io/helidon/http/http2/Http2Headers.java @@ -26,12 +26,14 @@ import java.util.function.Supplier; import io.helidon.common.buffers.BufferData; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderName; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Method; import io.helidon.http.ServerRequestHeaders; +import io.helidon.http.Status; import io.helidon.http.WritableHeaders; import static java.lang.System.Logger.Level.DEBUG; @@ -61,12 +63,12 @@ public class Http2Headers { /** * Header name of the path pseudo header. */ - public static final HeaderName PATH_NAME = Http.HeaderNames.create(PATH); + public static final HeaderName PATH_NAME = HeaderNames.create(PATH); static final String SCHEME = ":scheme"; /** * Header name of the scheme pseudo header. */ - public static final HeaderName SCHEME_NAME = Http.HeaderNames.create(SCHEME); + public static final HeaderName SCHEME_NAME = HeaderNames.create(SCHEME); static final String STATUS = ":status"; /** * Header name of the status pseudo header. @@ -209,7 +211,7 @@ public static Http2Headers create(WritableHeaders writableHeaders) { * * @return status or null if none defined */ - public Http.Status status() { + public Status status() { return pseudoHeaders.status(); } @@ -227,7 +229,7 @@ public String path() { * * @return method or null if none defined */ - public Http.Method method() { + public Method method() { return pseudoHeaders.method(); } @@ -266,7 +268,7 @@ public Http2Headers path(String path) { * @param method HTTP method of the request * @return updated headers */ - public Http2Headers method(Http.Method method) { + public Http2Headers method(Method method) { this.pseudoHeaders.method(method); return this; } @@ -336,7 +338,7 @@ public void validateRequest() throws Http2Exception { if (pseudoHeaders.hasStatus()) { throw new Http2Exception(Http2ErrorCode.PROTOCOL, ":status in request headers"); } - if (headers.contains(Http.HeaderNames.CONNECTION)) { + if (headers.contains(HeaderNames.CONNECTION)) { throw new Http2Exception(Http2ErrorCode.PROTOCOL, "Connection in request headers"); } if (headers.contains(HeaderNames.TE)) { @@ -368,7 +370,7 @@ public String toString() { * @param status status to use * @return updated headers */ - public Http2Headers status(Http.Status status) { + public Http2Headers status(Status status) { pseudoHeaders.status(status); return this; } @@ -384,20 +386,20 @@ public void write(DynamicTable table, Http2HuffmanEncoder huffman, BufferData gr // first write pseudoheaders if (pseudoHeaders.hasStatus()) { StaticHeader indexed = null; - Http.Status status = pseudoHeaders.status(); - if (status == Http.Status.OK_200) { + Status status = pseudoHeaders.status(); + if (status == Status.OK_200) { indexed = StaticHeader.STATUS_200; - } else if (status == Http.Status.NO_CONTENT_204) { + } else if (status == Status.NO_CONTENT_204) { indexed = StaticHeader.STATUS_204; - } else if (status == Http.Status.PARTIAL_CONTENT_206) { + } else if (status == Status.PARTIAL_CONTENT_206) { indexed = StaticHeader.STATUS_206; - } else if (status == Http.Status.NOT_MODIFIED_304) { + } else if (status == Status.NOT_MODIFIED_304) { indexed = StaticHeader.STATUS_304; - } else if (status == Http.Status.BAD_REQUEST_400) { + } else if (status == Status.BAD_REQUEST_400) { indexed = StaticHeader.STATUS_400; - } else if (status == Http.Status.NOT_FOUND_404) { + } else if (status == Status.NOT_FOUND_404) { indexed = StaticHeader.STATUS_404; - } else if (status == Http.Status.INTERNAL_SERVER_ERROR_500) { + } else if (status == Status.INTERNAL_SERVER_ERROR_500) { indexed = StaticHeader.STATUS_500; } if (indexed == null) { @@ -413,11 +415,11 @@ public void write(DynamicTable table, Http2HuffmanEncoder huffman, BufferData gr } } if (pseudoHeaders.hasMethod()) { - Http.Method method = pseudoHeaders.method(); + Method method = pseudoHeaders.method(); StaticHeader indexed = null; - if (method == Http.Method.GET) { + if (method == Method.GET) { indexed = StaticHeader.METHOD_GET; - } else if (method == Http.Method.POST) { + } else if (method == Method.POST) { indexed = StaticHeader.METHOD_POST; } if (indexed == null) { @@ -527,7 +529,7 @@ record = table.get(approach.number); "Received invalid pseudo-header field (or explicit value instead of indexed)\n" + BufferData.create(name).debugDataHex()); } - headerName = Http.HeaderNames.create(name); + headerName = HeaderNames.create(name); } else { headerName = record.headerName(); } @@ -591,7 +593,7 @@ record = table.get(approach.number); } if (!isPseudoHeader) { - headers.add(Http.Headers.create(headerName, + headers.add(HeaderValues.create(headerName, !approach.addToIndex, approach.neverIndex, value)); @@ -757,52 +759,52 @@ enum StaticHeader implements IndexedHeaderRecord { STATUS_404(13, STATUS_NAME, "404"), STATUS_500(14, STATUS_NAME, "500"), ACCEPT_CHARSET(15, HeaderNames.ACCEPT_CHARSET), - ACCEPT_ENCODING(16, Http.HeaderNames.ACCEPT_ENCODING, "gzip, deflate", false), + ACCEPT_ENCODING(16, HeaderNames.ACCEPT_ENCODING, "gzip, deflate", false), ACCEPT_LANGUAGE(17, HeaderNames.ACCEPT_LANGUAGE), ACCEPT_RANGES(18, HeaderNames.ACCEPT_RANGES), ACCEPT(19, HeaderNames.ACCEPT), ACCESS_CONTROL_ALLOW_ORIGIN(20, HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN), AGE(21, HeaderNames.AGE), - ALLOW(22, Http.HeaderNames.ALLOW), - AUTHORIZATION(23, Http.HeaderNames.AUTHORIZATION), + ALLOW(22, HeaderNames.ALLOW), + AUTHORIZATION(23, HeaderNames.AUTHORIZATION), CACHE_CONTROL(24, HeaderNames.CACHE_CONTROL), - CONTENT_DISPOSITION(25, Http.HeaderNames.CONTENT_DISPOSITION), - CONTENT_ENCODING(26, Http.HeaderNames.CONTENT_ENCODING), - CONTENT_LANGUAGE(27, Http.HeaderNames.CONTENT_LANGUAGE), + CONTENT_DISPOSITION(25, HeaderNames.CONTENT_DISPOSITION), + CONTENT_ENCODING(26, HeaderNames.CONTENT_ENCODING), + CONTENT_LANGUAGE(27, HeaderNames.CONTENT_LANGUAGE), CONTENT_LENGTH(28, HeaderNames.CONTENT_LENGTH), CONTENT_LOCATION(29, HeaderNames.CONTENT_LOCATION), - CONTENT_RANGE(30, Http.HeaderNames.CONTENT_RANGE), - CONTENT_TYPE(31, Http.HeaderNames.CONTENT_TYPE), - COOKIE(32, Http.HeaderNames.COOKIE), + CONTENT_RANGE(30, HeaderNames.CONTENT_RANGE), + CONTENT_TYPE(31, HeaderNames.CONTENT_TYPE), + COOKIE(32, HeaderNames.COOKIE), DATE(33, HeaderNames.DATE), ETAG(34, HeaderNames.ETAG), EXPECT(35, HeaderNames.EXPECT), EXPIRES(36, HeaderNames.EXPIRES), FROM(37, HeaderNames.FROM), - HOST(38, Http.HeaderNames.HOST), - IF_MATCH(39, Http.HeaderNames.IF_MATCH), + HOST(38, HeaderNames.HOST), + IF_MATCH(39, HeaderNames.IF_MATCH), IF_MODIFIED_SINCE(40, HeaderNames.IF_MODIFIED_SINCE), IF_NONE_MATCH(41, HeaderNames.IF_NONE_MATCH), - IF_RANGE(42, Http.HeaderNames.IF_RANGE), + IF_RANGE(42, HeaderNames.IF_RANGE), IF_UNMODIFIED_SINCE(43, HeaderNames.IF_UNMODIFIED_SINCE), - LAST_MODIFIED(44, Http.HeaderNames.LAST_MODIFIED), + LAST_MODIFIED(44, HeaderNames.LAST_MODIFIED), LINK(45, HeaderNames.LINK), LOCATION(46, HeaderNames.LOCATION), - MAX_FORWARDS(47, Http.HeaderNames.MAX_FORWARDS), + MAX_FORWARDS(47, HeaderNames.MAX_FORWARDS), PROXY_AUTHENTICATE(48, HeaderNames.PROXY_AUTHENTICATE), - PROXY_AUTHORIZATION(49, Http.HeaderNames.PROXY_AUTHORIZATION), - RANGE(50, Http.HeaderNames.CONTENT_LOCATION), - REFERER(51, Http.HeaderNames.REFERER), - REFRESH(52, Http.HeaderNames.REFRESH), - RETRY_AFTER(53, Http.HeaderNames.RETRY_AFTER), + PROXY_AUTHORIZATION(49, HeaderNames.PROXY_AUTHORIZATION), + RANGE(50, HeaderNames.CONTENT_LOCATION), + REFERER(51, HeaderNames.REFERER), + REFRESH(52, HeaderNames.REFRESH), + RETRY_AFTER(53, HeaderNames.RETRY_AFTER), SERVER(54, HeaderNames.SERVER), SET_COOKIE(55, HeaderNames.SET_COOKIE), STRICT_TRANSPORT_SECURITY(56, HeaderNames.STRICT_TRANSPORT_SECURITY), - TRANSFER_ENCODING(57, Http.HeaderNames.TRANSFER_ENCODING), - USER_AGENT(58, Http.HeaderNames.USER_AGENT), + TRANSFER_ENCODING(57, HeaderNames.TRANSFER_ENCODING), + USER_AGENT(58, HeaderNames.USER_AGENT), VARY(59, HeaderNames.VARY), VIA(60, HeaderNames.VIA), - WWW_AUTHENTICATE(61, Http.HeaderNames.WWW_AUTHENTICATE); + WWW_AUTHENTICATE(61, HeaderNames.WWW_AUTHENTICATE); /** * Maximal index of the static table of headers. @@ -1292,10 +1294,10 @@ public String value() { private static class PseudoHeaders { private String authority; - private Http.Method method; + private Method method; private String path; private String scheme; - private Http.Status status; + private Status status; private int size; public int size() { @@ -1320,10 +1322,10 @@ PseudoHeaders authority(String authority) { } void method(String method) { - method(Http.Method.create(method)); + method(Method.create(method)); } - PseudoHeaders method(Http.Method method) { + PseudoHeaders method(Method method) { this.method = method; size++; return this; @@ -1342,10 +1344,10 @@ PseudoHeaders scheme(String scheme) { } void status(String status) { - status(Http.Status.create(Integer.parseInt(status))); + status(Status.create(Integer.parseInt(status))); } - PseudoHeaders status(Http.Status status) { + PseudoHeaders status(Status status) { this.status = status; size++; return this; @@ -1363,7 +1365,7 @@ boolean hasMethod() { return method != null; } - Http.Method method() { + Method method() { return method; } @@ -1387,7 +1389,7 @@ boolean hasStatus() { return status != null; } - Http.Status status() { + Status status() { return status; } } diff --git a/http/http2/src/test/java/io/helidon/http/http2/DynamicTableTest.java b/http/http2/src/test/java/io/helidon/http/http2/DynamicTableTest.java index f56a2ac7334..ccca3878fd2 100644 --- a/http/http2/src/test/java/io/helidon/http/http2/DynamicTableTest.java +++ b/http/http2/src/test/java/io/helidon/http/http2/DynamicTableTest.java @@ -16,8 +16,7 @@ package io.helidon.http.http2; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.HeaderNames; import org.junit.jupiter.api.Test; @@ -38,11 +37,11 @@ void testDynamicTable() { assertThat(table.protocolMaxTableSize(), is(80L)); // index 1 - table.add(Http.HeaderNames.create("a"), "b"); + table.add(HeaderNames.create("a"), "b"); assertThat(table.currentTableSize(), is(34)); // 32 + name.length + value.length (on bytes) testRecord(table, Http2Headers.StaticHeader.MAX_INDEX + 1, "a", "b"); // index (now index 1) - table.add(Http.HeaderNames.create("b"), "c"); + table.add(HeaderNames.create("b"), "c"); assertThat(table.currentTableSize(), is(68)); testRecord(table, Http2Headers.StaticHeader.MAX_INDEX + 1, "b", "c"); diff --git a/http/http2/src/test/java/io/helidon/http/http2/Http2HeadersTest.java b/http/http2/src/test/java/io/helidon/http/http2/Http2HeadersTest.java index 883c6b03eb6..1aa703f9337 100644 --- a/http/http2/src/test/java/io/helidon/http/http2/Http2HeadersTest.java +++ b/http/http2/src/test/java/io/helidon/http/http2/Http2HeadersTest.java @@ -19,10 +19,10 @@ import java.util.HexFormat; import io.helidon.common.buffers.BufferData; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Method; import io.helidon.http.WritableHeaders; import io.helidon.http.http2.Http2Headers.DynamicTable; import io.helidon.http.http2.Http2Headers.HeaderRecord; @@ -76,7 +76,7 @@ void testC_2_3() { DynamicTable dynamicTable = DynamicTable.create(Http2Settings.create()); Headers requestHeaders = headers(hexEncoded, dynamicTable).httpHeaders(); - assertThat(requestHeaders.get(Http.HeaderNames.create("password")).value(), is("secret")); + assertThat(requestHeaders.get(HeaderNames.create("password")).value(), is("secret")); assertThat("Dynamic table should be empty", dynamicTable.currentTableSize(), is(0)); } @@ -89,7 +89,7 @@ void testC_2_4() { DynamicTable dynamicTable = DynamicTable.create(Http2Settings.create()); Http2Headers http2Headers = headers(hexEncoded, dynamicTable); - assertThat(http2Headers.method(), is(Http.Method.GET)); + assertThat(http2Headers.method(), is(Method.GET)); assertThat("Dynamic table should be empty", dynamicTable.currentTableSize(), is(0)); } @@ -104,7 +104,7 @@ void testC_3() { Http2Headers http2Headers = headers(hexEncoded, dynamicTable); - assertThat(http2Headers.method(), is(Http.Method.GET)); + assertThat(http2Headers.method(), is(Method.GET)); assertThat(http2Headers.scheme(), is("http")); assertThat(http2Headers.path(), is("/")); assertThat(http2Headers.authority(), is("www.example.com")); @@ -120,17 +120,17 @@ void testC_3() { http2Headers = headers(hexEncoded, dynamicTable); Headers requestHeaders = http2Headers.httpHeaders(); - assertThat(http2Headers.method(), is(Http.Method.GET)); + assertThat(http2Headers.method(), is(Method.GET)); assertThat(http2Headers.scheme(), is("http")); assertThat(http2Headers.path(), is("/")); assertThat(http2Headers.authority(), is("www.example.com")); - assertThat(requestHeaders.get(Http.HeaderNames.create("cache-control")).value(), is("no-cache")); + assertThat(requestHeaders.get(HeaderNames.create("cache-control")).value(), is("no-cache")); assertThat("Dynamic table should not be empty", dynamicTable.currentTableSize(), not(0)); assertThat(dynamicTable.currentTableSize(), is(110)); headerRecord = dynamicTable.get(Http2Headers.StaticHeader.MAX_INDEX + 1); - assertThat(headerRecord.headerName(), is(Http.HeaderNames.CACHE_CONTROL)); + assertThat(headerRecord.headerName(), is(HeaderNames.CACHE_CONTROL)); assertThat(headerRecord.value(), is("no-cache")); headerRecord = dynamicTable.get(Http2Headers.StaticHeader.MAX_INDEX + 2); assertThat(headerRecord.headerName(), is(Http2Headers.AUTHORITY_NAME)); @@ -141,7 +141,7 @@ void testC_3() { http2Headers = headers(hexEncoded, dynamicTable); requestHeaders = http2Headers.httpHeaders(); - assertThat(http2Headers.method(), is(Http.Method.GET)); + assertThat(http2Headers.method(), is(Method.GET)); assertThat(http2Headers.scheme(), is("https")); assertThat(http2Headers.path(), is("/index.html")); assertThat(http2Headers.authority(), is("www.example.com")); @@ -166,7 +166,7 @@ void testC_4_toBytes() { DynamicTable dynamicTable = DynamicTable.create(Http2Settings.create()); WritableHeaders headers = WritableHeaders.create(); Http2Headers http2Headers = Http2Headers.create(headers); - http2Headers.method(Http.Method.GET); + http2Headers.method(Method.GET); http2Headers.scheme("http"); http2Headers.path("/"); http2Headers.authority("www.example.com"); @@ -193,7 +193,7 @@ void testC_4() { DynamicTable dynamicTable = DynamicTable.create(Http2Settings.create()); Http2Headers http2Headers = headers(hexEncoded, dynamicTable); - assertThat(http2Headers.method(), is(Http.Method.GET)); + assertThat(http2Headers.method(), is(Method.GET)); assertThat(http2Headers.scheme(), is("http")); assertThat(http2Headers.path(), is("/")); assertThat(http2Headers.authority(), is("www.example.com")); @@ -210,7 +210,7 @@ void testC_4() { http2Headers = headers(hexEncoded, dynamicTable); Headers requestHeaders = http2Headers.httpHeaders(); - assertThat(http2Headers.method(), is(Http.Method.GET)); + assertThat(http2Headers.method(), is(Method.GET)); assertThat(http2Headers.scheme(), is("http")); assertThat(http2Headers.path(), is("/")); assertThat(http2Headers.authority(), is("www.example.com")); @@ -220,7 +220,7 @@ void testC_4() { assertThat(dynamicTable.currentTableSize(), is(110)); headerRecord = dynamicTable.get(Http2Headers.StaticHeader.MAX_INDEX + 1); - assertThat(headerRecord.headerName(), is(Http.HeaderNames.CACHE_CONTROL)); + assertThat(headerRecord.headerName(), is(HeaderNames.CACHE_CONTROL)); assertThat(headerRecord.value(), is("no-cache")); headerRecord = dynamicTable.get(Http2Headers.StaticHeader.MAX_INDEX + 2); assertThat(headerRecord.headerName(), is(Http2Headers.AUTHORITY_NAME)); @@ -231,7 +231,7 @@ void testC_4() { http2Headers = headers(hexEncoded, dynamicTable); requestHeaders = http2Headers.httpHeaders(); - assertThat(http2Headers.method(), is(Http.Method.GET)); + assertThat(http2Headers.method(), is(Method.GET)); assertThat(http2Headers.scheme(), is("https")); assertThat(http2Headers.path(), is("/index.html")); assertThat(http2Headers.authority(), is("www.example.com")); diff --git a/http/http2/src/test/java/io/helidon/http/http2/MaxFrameSizeSplitTest.java b/http/http2/src/test/java/io/helidon/http/http2/MaxFrameSizeSplitTest.java index 922a3f6addf..77d6fbb980e 100644 --- a/http/http2/src/test/java/io/helidon/http/http2/MaxFrameSizeSplitTest.java +++ b/http/http2/src/test/java/io/helidon/http/http2/MaxFrameSizeSplitTest.java @@ -29,7 +29,6 @@ import org.junit.jupiter.params.provider.MethodSource; import static java.lang.System.Logger.Level.DEBUG; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; diff --git a/http/media/jackson/src/main/java/io/helidon/http/media/jackson/JacksonSupport.java b/http/media/jackson/src/main/java/io/helidon/http/media/jackson/JacksonSupport.java index d448901f3cf..f7c1c2ba331 100644 --- a/http/media/jackson/src/main/java/io/helidon/http/media/jackson/JacksonSupport.java +++ b/http/media/jackson/src/main/java/io/helidon/http/media/jackson/JacksonSupport.java @@ -21,8 +21,8 @@ import io.helidon.common.GenericType; import io.helidon.common.config.Config; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.HeaderNames; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpMediaType; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityReader; @@ -34,7 +34,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; -import static io.helidon.http.Http.Headers.CONTENT_TYPE_JSON; +import static io.helidon.http.HeaderValues.CONTENT_TYPE_JSON; /** * {@link java.util.ServiceLoader} provider implementation for Jackson media support. @@ -179,7 +179,7 @@ public ReaderResponse reader(GenericType type, @Override public WriterResponse writer(GenericType type, WritableHeaders requestHeaders) { - if (requestHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { + if (requestHeaders.contains(HeaderNames.CONTENT_TYPE)) { if (requestHeaders.contains(CONTENT_TYPE_JSON)) { if (objectMapper.canSerialize(type.rawType())) { return new WriterResponse<>(SupportLevel.COMPATIBLE, this::writer); diff --git a/http/media/jackson/src/main/java/io/helidon/http/media/jackson/JacksonWriter.java b/http/media/jackson/src/main/java/io/helidon/http/media/jackson/JacksonWriter.java index 4328bb6210c..4216901162f 100644 --- a/http/media/jackson/src/main/java/io/helidon/http/media/jackson/JacksonWriter.java +++ b/http/media/jackson/src/main/java/io/helidon/http/media/jackson/JacksonWriter.java @@ -27,8 +27,8 @@ import io.helidon.common.GenericType; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpMediaType; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityWriter; @@ -51,7 +51,7 @@ public void write(GenericType type, Headers requestHeaders, WritableHeaders responseHeaders) { - responseHeaders.setIfAbsent(Http.Headers.CONTENT_TYPE_JSON); + responseHeaders.setIfAbsent(HeaderValues.CONTENT_TYPE_JSON); for (HttpMediaType acceptedType : requestHeaders.acceptedTypes()) { if (acceptedType.test(MediaTypes.APPLICATION_JSON)) { @@ -71,7 +71,7 @@ public void write(GenericType type, @Override public void write(GenericType type, T object, OutputStream outputStream, WritableHeaders headers) { - headers.setIfAbsent(Http.Headers.CONTENT_TYPE_JSON); + headers.setIfAbsent(HeaderValues.CONTENT_TYPE_JSON); write(type, object, outputStream); } diff --git a/http/media/jackson/src/test/java/io/helidon/http/media/jackson/JacksonMediaTest.java b/http/media/jackson/src/test/java/io/helidon/http/media/jackson/JacksonMediaTest.java index 7617c93a18e..95d9a4f8dc4 100644 --- a/http/media/jackson/src/test/java/io/helidon/http/media/jackson/JacksonMediaTest.java +++ b/http/media/jackson/src/test/java/io/helidon/http/media/jackson/JacksonMediaTest.java @@ -26,11 +26,11 @@ import io.helidon.common.GenericType; import io.helidon.common.config.Config; -import io.helidon.http.Http; -import io.helidon.http.HttpMediaType; -import io.helidon.http.WritableHeaders; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.testing.http.junit5.HttpHeaderMatcher; +import io.helidon.http.HeaderValues; +import io.helidon.http.HttpMediaType; +import io.helidon.http.WritableHeaders; import io.helidon.http.media.MediaContext; import io.helidon.http.media.MediaSupport; @@ -70,7 +70,7 @@ void testWriteSingle() { res.supplier().get() .write(BOOK_TYPE, new Book("test-title"), os, headers); - assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(HeaderValues.CONTENT_TYPE_JSON)); String result = os.toString(StandardCharsets.UTF_8); assertThat(result, containsString("\"title\"")); assertThat(result, containsString("\"test-title\"")); @@ -97,7 +97,7 @@ void testWriteList() { res.supplier().get() .write(BOOK_LIST_TYPE, books, os, headers); - assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(HeaderValues.CONTENT_TYPE_JSON)); String result = os.toString(StandardCharsets.UTF_8); assertThat(result, containsString("\"title\"")); assertThat(result, containsString("\"first\"")); diff --git a/http/media/jsonb/src/main/java/io/helidon/http/media/jsonb/JsonbSupport.java b/http/media/jsonb/src/main/java/io/helidon/http/media/jsonb/JsonbSupport.java index 81fad1dcd8c..3c025086f8e 100644 --- a/http/media/jsonb/src/main/java/io/helidon/http/media/jsonb/JsonbSupport.java +++ b/http/media/jsonb/src/main/java/io/helidon/http/media/jsonb/JsonbSupport.java @@ -21,8 +21,8 @@ import io.helidon.common.GenericType; import io.helidon.common.config.Config; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.HeaderNames; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpMediaType; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityReader; @@ -33,7 +33,7 @@ import jakarta.json.bind.Jsonb; import jakarta.json.bind.JsonbBuilder; -import static io.helidon.http.Http.Headers.CONTENT_TYPE_JSON; +import static io.helidon.http.HeaderValues.CONTENT_TYPE_JSON; /** * {@link java.util.ServiceLoader} provider implementation for JSON Binding media support. @@ -151,7 +151,7 @@ public WriterResponse writer(GenericType type, WritableHeaders requ if (type.equals(JSON_OBJECT_TYPE)) { return WriterResponse.unsupported(); } - if (requestHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { + if (requestHeaders.contains(HeaderNames.CONTENT_TYPE)) { if (requestHeaders.contains(CONTENT_TYPE_JSON)) { return new WriterResponse<>(SupportLevel.COMPATIBLE, this::writer); } diff --git a/http/media/jsonb/src/main/java/io/helidon/http/media/jsonb/JsonbWriter.java b/http/media/jsonb/src/main/java/io/helidon/http/media/jsonb/JsonbWriter.java index b4e5c9f2ca9..f00a63c8348 100644 --- a/http/media/jsonb/src/main/java/io/helidon/http/media/jsonb/JsonbWriter.java +++ b/http/media/jsonb/src/main/java/io/helidon/http/media/jsonb/JsonbWriter.java @@ -26,8 +26,8 @@ import io.helidon.common.GenericType; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpMediaType; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityWriter; @@ -48,7 +48,7 @@ public void write(GenericType type, Headers requestHeaders, WritableHeaders responseHeaders) { - responseHeaders.setIfAbsent(Http.Headers.CONTENT_TYPE_JSON); + responseHeaders.setIfAbsent(HeaderValues.CONTENT_TYPE_JSON); for (HttpMediaType acceptedType : requestHeaders.acceptedTypes()) { if (acceptedType.test(MediaTypes.APPLICATION_JSON)) { @@ -68,7 +68,7 @@ public void write(GenericType type, @Override public void write(GenericType type, T object, OutputStream outputStream, WritableHeaders headers) { - headers.setIfAbsent(Http.Headers.CONTENT_TYPE_JSON); + headers.setIfAbsent(HeaderValues.CONTENT_TYPE_JSON); write(type, object, outputStream); } diff --git a/http/media/jsonb/src/test/java/io/helidon/http/media/jsonb/JsonbMediaTest.java b/http/media/jsonb/src/test/java/io/helidon/http/media/jsonb/JsonbMediaTest.java index 96465912609..73163f7664b 100644 --- a/http/media/jsonb/src/test/java/io/helidon/http/media/jsonb/JsonbMediaTest.java +++ b/http/media/jsonb/src/test/java/io/helidon/http/media/jsonb/JsonbMediaTest.java @@ -26,11 +26,11 @@ import io.helidon.common.GenericType; import io.helidon.common.config.Config; -import io.helidon.http.Http; -import io.helidon.http.HttpMediaType; -import io.helidon.http.WritableHeaders; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.testing.http.junit5.HttpHeaderMatcher; +import io.helidon.http.HeaderValues; +import io.helidon.http.HttpMediaType; +import io.helidon.http.WritableHeaders; import io.helidon.http.media.MediaContext; import io.helidon.http.media.MediaSupport; @@ -70,7 +70,7 @@ void testWriteSingle() { res.supplier().get() .write(BOOK_TYPE, new Book("test-title"), os, headers); - assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(HeaderValues.CONTENT_TYPE_JSON)); String result = os.toString(StandardCharsets.UTF_8); assertThat(result, containsString("\"title\"")); assertThat(result, containsString("\"test-title\"")); @@ -97,7 +97,7 @@ void testWriteList() { res.supplier().get() .write(BOOK_LIST_TYPE, books, os, headers); - assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(HeaderValues.CONTENT_TYPE_JSON)); String result = os.toString(StandardCharsets.UTF_8); assertThat(result, containsString("\"title\"")); assertThat(result, containsString("\"first\"")); diff --git a/http/media/jsonp/src/main/java/io/helidon/http/media/jsonp/JsonpWriter.java b/http/media/jsonp/src/main/java/io/helidon/http/media/jsonp/JsonpWriter.java index ce9677b4741..b9bb4e72ae3 100644 --- a/http/media/jsonp/src/main/java/io/helidon/http/media/jsonp/JsonpWriter.java +++ b/http/media/jsonp/src/main/java/io/helidon/http/media/jsonp/JsonpWriter.java @@ -26,8 +26,8 @@ import io.helidon.common.GenericType; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpMediaType; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityWriter; @@ -50,7 +50,7 @@ public void write(GenericType type, Headers requestHeaders, WritableHeaders responseHeaders) { - responseHeaders.setIfAbsent(Http.Headers.CONTENT_TYPE_JSON); + responseHeaders.setIfAbsent(HeaderValues.CONTENT_TYPE_JSON); for (HttpMediaType acceptedType : requestHeaders.acceptedTypes()) { if (acceptedType.test(MediaTypes.APPLICATION_JSON)) { @@ -70,7 +70,7 @@ public void write(GenericType type, @Override public void write(GenericType type, T object, OutputStream outputStream, WritableHeaders headers) { - headers.setIfAbsent(Http.Headers.CONTENT_TYPE_JSON); + headers.setIfAbsent(HeaderValues.CONTENT_TYPE_JSON); write(type, object, outputStream); } diff --git a/http/media/jsonp/src/test/java/io/helidon/http/media/jsonp/JsonpMediaTest.java b/http/media/jsonp/src/test/java/io/helidon/http/media/jsonp/JsonpMediaTest.java index 766f616ff33..aacb0bd7cf0 100644 --- a/http/media/jsonp/src/test/java/io/helidon/http/media/jsonp/JsonpMediaTest.java +++ b/http/media/jsonp/src/test/java/io/helidon/http/media/jsonp/JsonpMediaTest.java @@ -24,11 +24,11 @@ import java.util.Map; import io.helidon.common.config.Config; -import io.helidon.http.Http; -import io.helidon.http.HttpMediaType; -import io.helidon.http.WritableHeaders; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.testing.http.junit5.HttpHeaderMatcher; +import io.helidon.http.HeaderValues; +import io.helidon.http.HttpMediaType; +import io.helidon.http.WritableHeaders; import io.helidon.http.media.MediaContext; import io.helidon.http.media.MediaSupport; @@ -74,7 +74,7 @@ void testWriteSingle() { res.supplier().get() .write(JSON_OBJECT_TYPE, createObject("test-title"), os, headers); - assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(HeaderValues.CONTENT_TYPE_JSON)); String result = os.toString(StandardCharsets.UTF_8); assertThat(result, containsString("\"title\"")); assertThat(result, containsString("\"test-title\"")); @@ -101,7 +101,7 @@ void testWriteList() { res.supplier().get() .write(JSON_ARRAY_TYPE, JsonObjects, os, headers); - assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(HeaderValues.CONTENT_TYPE_JSON)); String result = os.toString(StandardCharsets.UTF_8); assertThat(result, containsString("\"title\"")); assertThat(result, containsString("\"first\"")); diff --git a/http/media/media/src/main/java/io/helidon/http/media/FormParamsSupport.java b/http/media/media/src/main/java/io/helidon/http/media/FormParamsSupport.java index 33dd12e1286..4113650d11c 100644 --- a/http/media/media/src/main/java/io/helidon/http/media/FormParamsSupport.java +++ b/http/media/media/src/main/java/io/helidon/http/media/FormParamsSupport.java @@ -35,9 +35,10 @@ import io.helidon.common.media.type.MediaTypes; import io.helidon.common.parameters.Parameters; import io.helidon.common.uri.UriEncoding; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; import io.helidon.http.HttpMediaType; import io.helidon.http.WritableHeaders; @@ -181,7 +182,7 @@ private static class FormParamsWriter implements EntityWriter { private final String separator; private final Function nameEncoder; private final Function valueEncoder; - private final Http.Header contentTypeHeader; + private final Header contentTypeHeader; private FormParamsWriter(String separator, Function nameEncoder, @@ -215,7 +216,7 @@ private void write(Parameters toWrite, WritableHeaders writableHeaders) { Charset charset; - if (writableHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { + if (writableHeaders.contains(HeaderNames.CONTENT_TYPE)) { charset = writableHeaders.contentType() .flatMap(HttpMediaType::charset) .map(Charset::forName) @@ -251,8 +252,8 @@ private void write(Parameters toWrite, } private static class FormParamsUrlWriter extends FormParamsWriter { - private static final Http.Header CONTENT_TYPE_URL_ENCODED = - Http.Headers.createCached(Http.HeaderNames.CONTENT_TYPE, + private static final Header CONTENT_TYPE_URL_ENCODED = + HeaderValues.createCached(HeaderNames.CONTENT_TYPE, HttpMediaType.create(MediaTypes.APPLICATION_FORM_URLENCODED) .withCharset("utf-8") .text()); @@ -266,8 +267,8 @@ private FormParamsUrlWriter() { } private static class FormParamsPlaintextWriter extends FormParamsWriter { - private static final Http.Header CONTENT_TYPE_TEXT = - Http.Headers.createCached(Http.HeaderNames.CONTENT_TYPE, + private static final Header CONTENT_TYPE_TEXT = + HeaderValues.createCached(HeaderNames.CONTENT_TYPE, HttpMediaType.create(MediaTypes.TEXT_PLAIN) .withCharset("utf-8") .text()); diff --git a/http/media/media/src/main/java/io/helidon/http/media/PathSupport.java b/http/media/media/src/main/java/io/helidon/http/media/PathSupport.java index bbc8bd99910..ff4ae2c73a3 100644 --- a/http/media/media/src/main/java/io/helidon/http/media/PathSupport.java +++ b/http/media/media/src/main/java/io/helidon/http/media/PathSupport.java @@ -29,8 +29,8 @@ import io.helidon.common.media.type.MediaType; import io.helidon.common.media.type.MediaTypes; import io.helidon.http.ContentDisposition; +import io.helidon.http.HeaderNames; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.WritableHeaders; /** @@ -106,11 +106,11 @@ private static EntityWriter writer() { } private static void updateHeaders(Path path, WritableHeaders writableHeaders) { - if (!writableHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { + if (!writableHeaders.contains(HeaderNames.CONTENT_TYPE)) { MediaType mediaType = MediaTypes.detectType(path).orElse(MediaTypes.APPLICATION_OCTET_STREAM); writableHeaders.contentType(mediaType); } - if (!writableHeaders.contains(Http.HeaderNames.CONTENT_DISPOSITION)) { + if (!writableHeaders.contains(HeaderNames.CONTENT_DISPOSITION)) { writableHeaders.set(ContentDisposition.builder() .filename(String.valueOf(path.getFileName())) .build()); diff --git a/http/media/media/src/main/java/io/helidon/http/media/StringSupport.java b/http/media/media/src/main/java/io/helidon/http/media/StringSupport.java index 27bf35522ea..2d01729b854 100644 --- a/http/media/media/src/main/java/io/helidon/http/media/StringSupport.java +++ b/http/media/media/src/main/java/io/helidon/http/media/StringSupport.java @@ -27,9 +27,10 @@ import java.util.OptionalLong; import io.helidon.common.GenericType; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; import io.helidon.http.HttpMediaType; import io.helidon.http.HttpMediaTypes; import io.helidon.http.WritableHeaders; @@ -41,7 +42,7 @@ */ @SuppressWarnings({"unchecked", "rawtypes"}) public class StringSupport implements MediaSupport { - private static final Header HEADER_PLAIN_TEXT = Http.Headers.createCached(Http.HeaderNames.CONTENT_TYPE, + private static final Header HEADER_PLAIN_TEXT = HeaderValues.createCached(HeaderNames.CONTENT_TYPE, HttpMediaTypes.PLAINTEXT_UTF_8.text()); private static final EntityReader READER = new StringReader(); private static final EntityWriter WRITER = new StringWriter(); @@ -162,7 +163,7 @@ private void write(String toWrite, OutputStream outputStream, WritableHeaders writableHeaders) { Charset charset; - if (writableHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { + if (writableHeaders.contains(HeaderNames.CONTENT_TYPE)) { charset = writableHeaders.contentType() .flatMap(HttpMediaType::charset) .map(Charset::forName) @@ -185,7 +186,7 @@ private static final class StringInstanceWriter implements InstanceWriter { private StringInstanceWriter(String object, WritableHeaders headers) { Charset charset; - if (headers.contains(Http.HeaderNames.CONTENT_TYPE)) { + if (headers.contains(HeaderNames.CONTENT_TYPE)) { charset = headers.contentType() .flatMap(HttpMediaType::charset) .map(Charset::forName) diff --git a/http/media/multipart/src/main/java/io/helidon/http/media/multipart/MultiPartImpl.java b/http/media/multipart/src/main/java/io/helidon/http/media/multipart/MultiPartImpl.java index 3add1fa2bb3..dccdb9fca9d 100644 --- a/http/media/multipart/src/main/java/io/helidon/http/media/multipart/MultiPartImpl.java +++ b/http/media/multipart/src/main/java/io/helidon/http/media/multipart/MultiPartImpl.java @@ -23,7 +23,7 @@ import java.util.NoSuchElementException; import io.helidon.common.buffers.DataReader; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.HeaderNames; import io.helidon.http.Http1HeadersParser; import io.helidon.http.WritableHeaders; import io.helidon.http.media.MediaContext; diff --git a/http/media/multipart/src/main/java/io/helidon/http/media/multipart/MultiPartWriter.java b/http/media/multipart/src/main/java/io/helidon/http/media/multipart/MultiPartWriter.java index b95ac836a26..d9b58017940 100644 --- a/http/media/multipart/src/main/java/io/helidon/http/media/multipart/MultiPartWriter.java +++ b/http/media/multipart/src/main/java/io/helidon/http/media/multipart/MultiPartWriter.java @@ -23,8 +23,10 @@ import java.nio.charset.StandardCharsets; import io.helidon.common.GenericType; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpMediaType; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityWriter; @@ -32,12 +34,12 @@ class MultiPartWriter implements EntityWriter { private final MediaContext context; - private final Http.Header contentType; + private final Header contentType; private final byte[] boundaryPrefix; MultiPartWriter(MediaContext context, HttpMediaType mediaType, String boundary) { this.context = context; - this.contentType = Http.Headers.create(Http.HeaderNames.CONTENT_TYPE, false, false, mediaType.text()); + this.contentType = HeaderValues.create(HeaderNames.CONTENT_TYPE, false, false, mediaType.text()); this.boundaryPrefix = ("--" + boundary).getBytes(StandardCharsets.UTF_8); } diff --git a/http/media/multipart/src/main/java/io/helidon/http/media/multipart/ReadablePartAbstract.java b/http/media/multipart/src/main/java/io/helidon/http/media/multipart/ReadablePartAbstract.java index 2361a91b8a1..f1e6a1bcc27 100644 --- a/http/media/multipart/src/main/java/io/helidon/http/media/multipart/ReadablePartAbstract.java +++ b/http/media/multipart/src/main/java/io/helidon/http/media/multipart/ReadablePartAbstract.java @@ -19,8 +19,8 @@ import java.util.Optional; import io.helidon.http.ContentDisposition; +import io.helidon.http.HeaderNames; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpMediaType; import io.helidon.http.HttpMediaTypes; import io.helidon.http.media.ReadableEntity; @@ -79,8 +79,8 @@ public boolean hasEntity() { protected abstract void finish(); private void contentDisposition() { - if (headers.contains(Http.HeaderNames.CONTENT_DISPOSITION)) { - this.contentDisposition = ContentDisposition.parse(headers.get(Http.HeaderNames.CONTENT_DISPOSITION).value()); + if (headers.contains(HeaderNames.CONTENT_DISPOSITION)) { + this.contentDisposition = ContentDisposition.parse(headers.get(HeaderNames.CONTENT_DISPOSITION).value()); } else { this.contentDisposition = ContentDisposition.empty(); } diff --git a/http/media/multipart/src/main/java/io/helidon/http/media/multipart/WriteablePartAbstract.java b/http/media/multipart/src/main/java/io/helidon/http/media/multipart/WriteablePartAbstract.java index c7e7166a64f..1f2c7de02af 100644 --- a/http/media/multipart/src/main/java/io/helidon/http/media/multipart/WriteablePartAbstract.java +++ b/http/media/multipart/src/main/java/io/helidon/http/media/multipart/WriteablePartAbstract.java @@ -26,9 +26,10 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; import io.helidon.http.HttpMediaType; import io.helidon.http.WritableHeaders; @@ -69,7 +70,7 @@ public Headers headers() { protected void sendHeaders(OutputStream outputStream, Headers headers) throws IOException { BufferData bufferData = BufferData.growing(128); - for (Http.Header header : headers) { + for (Header header : headers) { header.writeHttp1Header(bufferData); } bufferData.writeTo(outputStream); @@ -78,7 +79,7 @@ protected void sendHeaders(OutputStream outputStream, Headers headers) throws IO } protected void send(OutputStream outputStream, WritableHeaders headers, byte[] bytes) { - headers.set(Http.Headers.create(HeaderNames.CONTENT_LENGTH, true, false, String.valueOf(bytes.length))); + headers.set(HeaderValues.create(HeaderNames.CONTENT_LENGTH, true, false, String.valueOf(bytes.length))); try (outputStream) { sendHeaders(outputStream, headers); @@ -100,7 +101,7 @@ void contentType(WritableHeaders headers) { disposition.add("form-data"); disposition.add("name=\"" + URLEncoder.encode(name(), UTF_8) + "\""); fileName().ifPresent(it -> disposition.add("filename=\"" + URLEncoder.encode(it, UTF_8) + "\"")); - headers.setIfAbsent(Http.Headers.create(HeaderNames.CONTENT_DISPOSITION, String.join("; ", disposition))); + headers.setIfAbsent(HeaderValues.create(HeaderNames.CONTENT_DISPOSITION, String.join("; ", disposition))); } } if (!headers.contains(HeaderNames.CONTENT_TYPE)) { diff --git a/http/sse/src/main/java/io/helidon/http/sse/SseEvent.java b/http/sse/src/main/java/io/helidon/http/sse/SseEvent.java index d5f50e1a17f..add347f4662 100644 --- a/http/sse/src/main/java/io/helidon/http/sse/SseEvent.java +++ b/http/sse/src/main/java/io/helidon/http/sse/SseEvent.java @@ -28,7 +28,7 @@ import io.helidon.common.GenericType; import io.helidon.common.media.type.MediaType; import io.helidon.common.media.type.MediaTypes; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityReader; import io.helidon.http.media.MediaContext; @@ -128,7 +128,7 @@ public T data(Class clazz, MediaType mediaType) { WritableHeaders headers; if (!mediaType.equals(MediaTypes.WILDCARD)) { headers = WritableHeaders.create(); - headers.set(Http.HeaderNames.CONTENT_TYPE, mediaType.text()); + headers.set(HeaderNames.CONTENT_TYPE, mediaType.text()); } else { headers = EMPTY_HEADERS; } diff --git a/http/tests/encoding/deflate/src/test/java/io/helidon/http/tests/integration/encoding/deflate/DeflateEncodingTest.java b/http/tests/encoding/deflate/src/test/java/io/helidon/http/tests/integration/encoding/deflate/DeflateEncodingTest.java index d6ed5512152..d10b82ec673 100644 --- a/http/tests/encoding/deflate/src/test/java/io/helidon/http/tests/integration/encoding/deflate/DeflateEncodingTest.java +++ b/http/tests/encoding/deflate/src/test/java/io/helidon/http/tests/integration/encoding/deflate/DeflateEncodingTest.java @@ -31,15 +31,19 @@ import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; -import io.helidon.http.Http; -import io.helidon.webclient.http2.Http2Client; -import io.helidon.webserver.http2.Http2Route; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.ClientResponseTyped; import io.helidon.webclient.http1.Http1Client; +import io.helidon.webclient.http2.Http2Client; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http1.Http1Route; +import io.helidon.webserver.http2.Http2Route; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -53,7 +57,7 @@ class DeflateEncodingTest { private static final String ENTITY = "Some arbitrary text we want to try to compress"; private static final byte[] DEFLATED_ENTITY; - private static final Http.Header CONTENT_ENCODING_DEFLATE = Http.Headers.create(Http.HeaderNames.CONTENT_ENCODING, "deflate"); + private static final Header CONTENT_ENCODING_DEFLATE = HeaderValues.create(HeaderNames.CONTENT_ENCODING, "deflate"); static { ByteArrayOutputStream baos; @@ -85,22 +89,22 @@ class DeflateEncodingTest { @SetUpRoute static void routing(HttpRouting.Builder builder) { - builder.route(Http1Route.route(Http.Method.PUT, + builder.route(Http1Route.route(Method.PUT, "/http1", (req, res) -> { String entity = req.content().as(String.class); if (!ENTITY.equals(entity)) { - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send("Wrong data"); + res.status(Status.INTERNAL_SERVER_ERROR_500).send("Wrong data"); } else { res.send(entity); } })) - .route(Http2Route.route(Http.Method.PUT, + .route(Http2Route.route(Method.PUT, "/http2", (req, res) -> { String entity = req.content().as(String.class); if (!ENTITY.equals(entity)) { - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send("Wrong data"); + res.status(Status.INTERNAL_SERVER_ERROR_500).send("Wrong data"); } else { res.send(entity); } @@ -139,12 +143,12 @@ void testDeflateMultipleAcceptedEncodingsHttp2Client() { void testIt(io.helidon.webclient.api.HttpClient client, String path, String acceptEncodingValue) { ClientResponseTyped response = client.put(path) - .header(Http.HeaderNames.ACCEPT_ENCODING, acceptEncodingValue) + .header(HeaderNames.ACCEPT_ENCODING, acceptEncodingValue) .header(CONTENT_ENCODING_DEFLATE) .submit(DEFLATED_ENTITY, String.class); Assertions.assertAll( - () -> assertThat(response.status(), is(Http.Status.OK_200)), + () -> assertThat(response.status(), is(Status.OK_200)), () -> assertThat(response.entity(), is(ENTITY)), () -> assertThat(response.headers(), hasHeader(CONTENT_ENCODING_DEFLATE)) ); diff --git a/http/tests/encoding/gzip/src/test/java/io/helidon/http/tests/integration/encoding/gzip/GzipEncodingTest.java b/http/tests/encoding/gzip/src/test/java/io/helidon/http/tests/integration/encoding/gzip/GzipEncodingTest.java index 4b5d1a3957a..990b879cd04 100644 --- a/http/tests/encoding/gzip/src/test/java/io/helidon/http/tests/integration/encoding/gzip/GzipEncodingTest.java +++ b/http/tests/encoding/gzip/src/test/java/io/helidon/http/tests/integration/encoding/gzip/GzipEncodingTest.java @@ -30,15 +30,19 @@ import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; -import io.helidon.http.Http; -import io.helidon.webclient.http2.Http2Client; -import io.helidon.webserver.http2.Http2Route; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.ClientResponseTyped; import io.helidon.webclient.http1.Http1Client; +import io.helidon.webclient.http2.Http2Client; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http1.Http1Route; +import io.helidon.webserver.http2.Http2Route; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -52,7 +56,7 @@ class GzipEncodingTest { private static final String ENTITY = "Some arbitrary text we want to try to compress"; private static final byte[] GZIP_ENTITY; - private static final Http.Header CONTENT_ENCODING_GZIP = Http.Headers.create(Http.HeaderNames.CONTENT_ENCODING, "gzip"); + private static final Header CONTENT_ENCODING_GZIP = HeaderValues.create(HeaderNames.CONTENT_ENCODING, "gzip"); static { ByteArrayOutputStream baos; @@ -84,22 +88,22 @@ class GzipEncodingTest { @SetUpRoute static void routing(HttpRouting.Builder builder) { - builder.route(Http1Route.route(Http.Method.PUT, + builder.route(Http1Route.route(Method.PUT, "/http1", (req, res) -> { String entity = req.content().as(String.class); if (!ENTITY.equals(entity)) { - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send("Wrong data"); + res.status(Status.INTERNAL_SERVER_ERROR_500).send("Wrong data"); } else { res.send(entity); } })) - .route(Http2Route.route(Http.Method.PUT, + .route(Http2Route.route(Method.PUT, "/http2", (req, res) -> { String entity = req.content().as(String.class); if (!ENTITY.equals(entity)) { - res.status(Http.Status.INTERNAL_SERVER_ERROR_500).send("Wrong data"); + res.status(Status.INTERNAL_SERVER_ERROR_500).send("Wrong data"); } else { res.send(entity); } @@ -139,12 +143,12 @@ void testDeflateMultipleAcceptedEncodingsHttp2Client() { void testIt(io.helidon.webclient.api.HttpClient client, String path, String acceptEncodingValue) { ClientResponseTyped response = client.put(path) - .header(Http.HeaderNames.ACCEPT_ENCODING, acceptEncodingValue) + .header(HeaderNames.ACCEPT_ENCODING, acceptEncodingValue) .header(CONTENT_ENCODING_GZIP) .submit(GZIP_ENTITY, String.class); Assertions.assertAll( - () -> assertThat(response.status(), is(Http.Status.OK_200)), + () -> assertThat(response.status(), is(Status.OK_200)), () -> assertThat(response.entity(), is(ENTITY)), () -> assertThat(response.headers(), hasHeader(CONTENT_ENCODING_GZIP)) ); diff --git a/http/tests/media/jsonb/src/test/java/io/helidon/http/tests/integration/media/jsonb/JsonbTest.java b/http/tests/media/jsonb/src/test/java/io/helidon/http/tests/integration/media/jsonb/JsonbTest.java index f21c0674bfd..36fea48c586 100644 --- a/http/tests/media/jsonb/src/test/java/io/helidon/http/tests/integration/media/jsonb/JsonbTest.java +++ b/http/tests/media/jsonb/src/test/java/io/helidon/http/tests/integration/media/jsonb/JsonbTest.java @@ -19,14 +19,15 @@ import java.util.Objects; import java.util.Optional; -import io.helidon.http.Http; -import io.helidon.http.HttpMediaType; import io.helidon.common.media.type.MediaTypes; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.HttpMediaType; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -60,7 +61,7 @@ void testGet() { .request(); assertAll( - () -> assertThat(response.status(), is(Http.Status.OK_200)), + () -> assertThat(response.status(), is(Status.OK_200)), () -> assertThat("Should contain content type application/json", response.headers().contentType(), is(Optional.of(HttpMediaType.create(MediaTypes.APPLICATION_JSON)))), @@ -69,12 +70,12 @@ void testGet() { @Test void testPost() { - Http1ClientResponse response = client.method(Http.Method.POST) + Http1ClientResponse response = client.method(Method.POST) .uri("/jsonb") .submit(MESSAGE); assertAll( - () -> assertThat(response.status(), is(Http.Status.OK_200)), + () -> assertThat(response.status(), is(Status.OK_200)), () -> assertThat("Should contain content type application/json", response.headers().contentType(), is(Optional.of(HttpMediaType.create(MediaTypes.APPLICATION_JSON)))), diff --git a/http/tests/media/jsonp/src/test/java/io/helidon/http/tests/integration/media/jsonp/JsonpTest.java b/http/tests/media/jsonp/src/test/java/io/helidon/http/tests/integration/media/jsonp/JsonpTest.java index 31a6b66525a..0e165409c58 100644 --- a/http/tests/media/jsonp/src/test/java/io/helidon/http/tests/integration/media/jsonp/JsonpTest.java +++ b/http/tests/media/jsonp/src/test/java/io/helidon/http/tests/integration/media/jsonp/JsonpTest.java @@ -19,14 +19,15 @@ import java.util.Map; import java.util.Optional; -import io.helidon.http.Http; -import io.helidon.http.HttpMediaType; import io.helidon.common.media.type.MediaTypes; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.HttpMediaType; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import jakarta.json.Json; import jakarta.json.JsonBuilderFactory; @@ -64,7 +65,7 @@ void testGet() { .request(); assertAll( - () -> assertThat(response.status(), is(Http.Status.OK_200)), + () -> assertThat(response.status(), is(Status.OK_200)), () -> assertThat("Should contain content type application/json", response.headers().contentType(), is(Optional.of(HttpMediaType.create(MediaTypes.APPLICATION_JSON)))), @@ -73,12 +74,12 @@ void testGet() { @Test void testPost() { - Http1ClientResponse response = client.method(Http.Method.POST) + Http1ClientResponse response = client.method(Method.POST) .uri("/jsonp") .submit(MESSAGE); assertAll( - () -> assertThat(response.status(), is(Http.Status.OK_200)), + () -> assertThat(response.status(), is(Status.OK_200)), // todo matcher for headers () -> assertThat("Should contain content type application/json", response.headers().contentType(), diff --git a/http/tests/media/multipart/src/test/java/io/helidon/http/tests/integration/multipart/MultipartTest.java b/http/tests/media/multipart/src/test/java/io/helidon/http/tests/integration/multipart/MultipartTest.java index ebeacd71fab..dce99c95402 100644 --- a/http/tests/media/multipart/src/test/java/io/helidon/http/tests/integration/multipart/MultipartTest.java +++ b/http/tests/media/multipart/src/test/java/io/helidon/http/tests/integration/multipart/MultipartTest.java @@ -24,18 +24,19 @@ import java.util.LinkedList; import java.util.List; -import io.helidon.http.Http; -import io.helidon.http.HttpMediaType; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.HttpMediaType; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.http.media.multipart.MultiPart; import io.helidon.http.media.multipart.ReadablePart; import io.helidon.http.media.multipart.WriteableMultiPart; import io.helidon.http.media.multipart.WriteablePart; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -92,11 +93,11 @@ void testWriteMultipart() { .inputStream(() -> new ByteArrayInputStream(SECOND_PART_CONTENT.getBytes(StandardCharsets.UTF_8)))) .build(); - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .path("/multipart") .submit(multiPart)) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is(FIRST_PART_NAME + ":" + FIRST_PART_CONTENT + "," + SECOND_PART_NAME + ":" + SECOND_PART_CONTENT)); } @@ -106,7 +107,7 @@ void testWriteMultipart() { void testReadMultipart() throws IOException { try (Http1ClientResponse response = client.get("/multipart") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); MultiPart mp = response.as(MultiPart.class); ReadablePart part = mp.next(); diff --git a/http/tests/media/string/src/test/java/io/helidon/http/tests/media/string/StringTest.java b/http/tests/media/string/src/test/java/io/helidon/http/tests/media/string/StringTest.java index 79f304c555d..683ea9f0227 100644 --- a/http/tests/media/string/src/test/java/io/helidon/http/tests/media/string/StringTest.java +++ b/http/tests/media/string/src/test/java/io/helidon/http/tests/media/string/StringTest.java @@ -18,16 +18,19 @@ import java.util.Optional; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; +import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.HttpMediaType; import io.helidon.http.HttpMediaTypes; -import io.helidon.common.media.type.MediaTypes; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -39,7 +42,7 @@ class StringTest { private static final HttpMediaType TEXT_ISO_8859_2 = HttpMediaType.create(MediaTypes.TEXT_PLAIN) .withCharset("ISO-8859-2"); - private static final Header ISO_8859_CONTENT_TYPE = Http.Headers.create(Http.HeaderNames.CONTENT_TYPE, + private static final Header ISO_8859_CONTENT_TYPE = HeaderValues.create(HeaderNames.CONTENT_TYPE, TEXT_ISO_8859_2.text()); private static final String UTF_8_TEXT = "český řízný text"; @@ -64,7 +67,7 @@ void testGetUtf8() { .request(); assertAll( - () -> assertThat(response.status(), is(Http.Status.OK_200)), + () -> assertThat(response.status(), is(Status.OK_200)), () -> assertThat("Should contain content type plain/text; charset=UTF-8", response.headers().contentType(), is(Optional.of(HttpMediaTypes.PLAINTEXT_UTF_8))), @@ -77,7 +80,7 @@ void testGetIso8859_2() { .request(); assertAll( - () -> assertThat(response.status(), is(Http.Status.OK_200)), + () -> assertThat(response.status(), is(Status.OK_200)), () -> assertThat("Should contain content type plain/text; charset=ISO_8859_2", response.headers().contentType(), is(Optional.of(TEXT_ISO_8859_2))), @@ -86,12 +89,12 @@ void testGetIso8859_2() { @Test void testPostUtf8NoContentType() { - Http1ClientResponse response = client.method(Http.Method.POST) + Http1ClientResponse response = client.method(Method.POST) .uri("/request") .submit(UTF_8_TEXT); assertAll( - () -> assertThat(response.status(), is(Http.Status.OK_200)), + () -> assertThat(response.status(), is(Status.OK_200)), () -> assertThat("Should contain content type plain/text; charset=UTF-8", response.headers().contentType(), is(Optional.of(HttpMediaTypes.PLAINTEXT_UTF_8))), diff --git a/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ApiResponse.java b/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ApiResponse.java index 1e95abb76bb..145656413a8 100644 --- a/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ApiResponse.java +++ b/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ApiResponse.java @@ -17,7 +17,7 @@ package io.helidon.integrations.common.rest; import io.helidon.http.Headers; -import io.helidon.http.Http; +import io.helidon.http.Status; /** * A base for responses without an entity. @@ -26,7 +26,7 @@ */ public abstract class ApiResponse extends ApiJsonParser { private final Headers headers; - private final Http.Status status; + private final Status status; private final String requestId; /** @@ -57,7 +57,7 @@ public Headers headers() { * * @return status of the response (only if successful) */ - public Http.Status status() { + public Status status() { return status; } @@ -80,7 +80,7 @@ public String requestId() { public abstract static class Builder, T extends ApiResponse> implements io.helidon.common.Builder { private Headers headers; - private Http.Status status; + private Status status; private String requestId; /** @@ -106,7 +106,7 @@ public B headers(Headers headers) { * @param status HTTP status * @return updated builder */ - public B status(Http.Status status) { + public B status(Status status) { this.status = status; return me(); } @@ -136,7 +136,7 @@ public Headers headers() { * * @return status */ - public Http.Status status() { + public Status status() { return status; } diff --git a/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ApiRestException.java b/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ApiRestException.java index 7e582a306d5..4d51e73ff1a 100644 --- a/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ApiRestException.java +++ b/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ApiRestException.java @@ -20,7 +20,7 @@ import java.util.Optional; import io.helidon.http.Headers; -import io.helidon.http.Http; +import io.helidon.http.Status; /** * Exception when invoking remote REST API caused by wrong response from the API call. @@ -31,7 +31,7 @@ */ public abstract class ApiRestException extends ApiException { private final String requestId; - private final Http.Status status; + private final Status status; private final Headers headers; private final String apiSpecificError; @@ -54,7 +54,7 @@ protected ApiRestException(BaseBuilder builder) { * * @return status */ - public Http.Status status() { + public Status status() { return status; } @@ -94,7 +94,7 @@ public Headers headers() { public abstract static class BaseBuilder> { private String message; private String requestId; - private Http.Status status; + private Status status; private Headers headers; private String apiSpecificError; private Throwable cause; @@ -139,7 +139,7 @@ public B requestId(String requestId) { * @param status returned status * @return updated builder */ - public B status(Http.Status status) { + public B status(Status status) { this.status = status; return me(); } diff --git a/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ResponseBuilder.java b/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ResponseBuilder.java index 194aee05baa..1543b04ee35 100644 --- a/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ResponseBuilder.java +++ b/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/ResponseBuilder.java @@ -18,7 +18,7 @@ import io.helidon.common.Builder; import io.helidon.http.Headers; -import io.helidon.http.Http; +import io.helidon.http.Status; /** * Response builder extracted as an interface, to work around the restriction that we cannot @@ -35,7 +35,7 @@ public interface ResponseBuilder, T, X> exten * @param status HTTP status * @return updated builder */ - B status(Http.Status status); + B status(Status status); /** * Configure the HTTP headers returned by the API call. diff --git a/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/RestApi.java b/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/RestApi.java index 9d31df90c17..118fa26fbbb 100644 --- a/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/RestApi.java +++ b/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/RestApi.java @@ -24,8 +24,7 @@ import io.helidon.config.Config; import io.helidon.faulttolerance.FaultTolerance; import io.helidon.faulttolerance.FtHandler; -import io.helidon.http.Http; -import io.helidon.http.Http.Method; +import io.helidon.http.Method; import io.helidon.http.media.jsonp.JsonpSupport; import io.helidon.integrations.common.rest.ApiOptionalResponse.BuilderBase; import io.helidon.webclient.api.WebClient; @@ -43,10 +42,10 @@ */ public interface RestApi { /** - * Get with an optional response. In case the call returns {@link io.helidon.http.Http.Status#NOT_FOUND_404} + * Get with an optional response. In case the call returns {@link io.helidon.http.Status#NOT_FOUND_404} * this would return an empty optional entity, rather than fail. * This may also be the case for requests that use {@code If-Modified-Since} that return a - * {@link Http.Status#NOT_MODIFIED_304} response code. + * {@link io.helidon.http.Status#NOT_MODIFIED_304} response code. * * @param path path to invoke * @param request request to use @@ -59,7 +58,7 @@ default > T get(String path, ApiRequest request, BuilderBase responseBuilder) { - return invokeOptional(Http.Method.GET, path, request, responseBuilder); + return invokeOptional(Method.GET, path, request, responseBuilder); } /** @@ -75,7 +74,7 @@ default > T get(String path, default > T getEntityStream(String path, ApiRequest request, BuilderBase responseBuilder) { - return invokeEntityResponse(Http.Method.GET, path, request, responseBuilder); + return invokeEntityResponse(Method.GET, path, request, responseBuilder); } /** @@ -92,7 +91,7 @@ default > T getEntityStream(String path, default > T getBytes(String path, ApiRequest request, BuilderBase responseBuilder) { - return invokeBytesResponse(Http.Method.GET, path, request, responseBuilder); + return invokeBytesResponse(Method.GET, path, request, responseBuilder); } /** @@ -108,7 +107,7 @@ default > T getBytes(String path, default T post(String path, ApiRequest request, ApiResponse.Builder responseBuilder) { - return invoke(Http.Method.POST, path, request, responseBuilder); + return invoke(Method.POST, path, request, responseBuilder); } /** @@ -123,7 +122,7 @@ default T post(String path, */ default T put(String path, ApiRequest request, ApiResponse.Builder responseBuilder) { - return invoke(Http.Method.PUT, path, request, responseBuilder); + return invoke(Method.PUT, path, request, responseBuilder); } /** @@ -139,7 +138,7 @@ default T put(String path, ApiRequest request, default T delete(String path, ApiRequest request, ApiResponse.Builder responseBuilder) { - return invoke(Http.Method.DELETE, path, request, responseBuilder); + return invoke(Method.DELETE, path, request, responseBuilder); } /** @@ -188,7 +187,7 @@ T invokeWithResponse(Method method, * @param type of the response * @return future with the response or error */ - T invokeBytesRequest(Http.Method method, + T invokeBytesRequest(Method method, String path, ApiRequest request, InputStream is, @@ -218,7 +217,7 @@ > T invokeEntityResponse(Method method, * Invoke API call that is expected to return bytes. * This method collects all bytes in memory, so it cannot be used for large data. * See - * {@link #invokeEntityResponse(io.helidon.http.Http.Method, String, ApiRequest, BuilderBase)}. + * {@link #invokeEntityResponse(io.helidon.http.Method, String, ApiRequest, BuilderBase)}. *

* The accepted media type must be provided in request, falls back to * {@link io.helidon.common.media.type.MediaTypes#APPLICATION_OCTET_STREAM}. @@ -239,7 +238,7 @@ > T invokeBytesResponse(Method method, /** * Invoke a request that may yield an entity. - * The entity is expected to be missing if {@link Http.Status#NOT_FOUND_404} is returned by the API call (and for some + * The entity is expected to be missing if {@link io.helidon.http.Status#NOT_FOUND_404} is returned by the API call (and for some * other cases, such as not modified). * * @param method HTTP method to invoke diff --git a/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/RestApiBase.java b/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/RestApiBase.java index d256663f6b9..56d58f62355 100644 --- a/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/RestApiBase.java +++ b/integrations/common/rest/src/main/java/io/helidon/integrations/common/rest/RestApiBase.java @@ -31,8 +31,9 @@ import io.helidon.common.media.type.MediaType; import io.helidon.common.media.type.MediaTypes; import io.helidon.faulttolerance.FtHandler; -import io.helidon.http.Http; -import io.helidon.http.Http.Method; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.integrations.common.rest.ApiOptionalResponse.BuilderBase; import io.helidon.webclient.api.HttpClientRequest; import io.helidon.webclient.api.HttpClientResponse; @@ -226,7 +227,7 @@ protected void addQueryParams(HttpClientRequest request, Map> headers) { request.headers(clientHeaders -> { - headers.forEach((key, value) -> clientHeaders.set(Http.HeaderNames.create(key), value)); + headers.forEach((key, value) -> clientHeaders.set(HeaderNames.create(key), value)); }); } @@ -329,15 +330,15 @@ protected boolean isSuccess(String path, ApiRequest request, Method method, String requestId, - Http.Status status) { - if (status == Http.Status.NOT_FOUND_404) { + Status status) { + if (status == Status.NOT_FOUND_404) { return true; } - if (status == Http.Status.NOT_MODIFIED_304) { + if (status == Status.NOT_MODIFIED_304) { return true; } - Http.Status.Family family = Http.Status.Family.of(status.code()); + Status.Family family = Status.Family.of(status.code()); return switch (family) { // we do have not modified handled, we also follow redirects - so this is an error case REDIRECTION, CLIENT_ERROR, SERVER_ERROR -> false; @@ -364,8 +365,8 @@ protected boolean isEntityExpected(String path, ApiRequest request, Method method, String requestId, - Http.Status status) { - Http.Status.Family family = Http.Status.Family.of(status.code()); + Status status) { + Status.Family family = Status.Family.of(status.code()); return switch (family) { // we do have not modified handled, we also follow redirects - so this is an error case REDIRECTION, CLIENT_ERROR, SERVER_ERROR -> false; @@ -420,8 +421,8 @@ protected > T handleOptionalJsonResponse( } /** - * Empty response, may be because of a {@link Http.Status#NOT_FOUND_404}, or - * some other status, such as {@link Http.Status#NOT_MODIFIED_304}. + * Empty response, may be because of a {@link io.helidon.http.Status#NOT_FOUND_404}, or + * some other status, such as {@link io.helidon.http.Status#NOT_MODIFIED_304}. * * @param path requested path * @param request original request @@ -495,8 +496,8 @@ protected T handleJsonResponse( HttpClientResponse response, ApiEntityResponse.Builder responseBuilder) { - Http.Status status = response.status(); - if (Http.Status.Family.of(status.code()) == Http.Status.Family.SUCCESSFUL) { + Status status = response.status(); + if (Status.Family.of(status.code()) == Status.Family.SUCCESSFUL) { LOGGER.finest(() -> requestId + ": " + method + " on path " + path + " returned " + status); try { JsonObject entity = response.entity().as(JsonObject.class); @@ -528,9 +529,9 @@ protected T handleResponse(String path, String requestId, HttpClientResponse response, ApiResponse.Builder responseBuilder) { - Http.Status status = response.status(); + Status status = response.status(); - boolean success = (Http.Status.Family.of(status.code()) == Http.Status.Family.SUCCESSFUL); + boolean success = (Status.Family.of(status.code()) == Status.Family.SUCCESSFUL); if (success) { LOGGER.finest(() -> requestId + ": " + method + " on path " + path + " returned " + status); @@ -965,10 +966,10 @@ private ResponseState responseState(String path, String requestId, HttpClientResponse response) { - Http.Status status = response.status(); - boolean success = (Http.Status.Family.of(status.code()) == Http.Status.Family.SUCCESSFUL) + Status status = response.status(); + boolean success = (Status.Family.of(status.code()) == Status.Family.SUCCESSFUL) || isSuccess(path, request, method, requestId, status); - boolean isEntityExpected = (Http.Status.Family.of(status.code()) == Http.Status.Family.SUCCESSFUL) + boolean isEntityExpected = (Status.Family.of(status.code()) == Status.Family.SUCCESSFUL) || isEntityExpected(path, request, method, requestId, status); return new ResponseState(success, isEntityExpected); } diff --git a/integrations/common/rest/src/test/java/io/helidon/integrations/common/rest/RestApiTest.java b/integrations/common/rest/src/test/java/io/helidon/integrations/common/rest/RestApiTest.java index 3d217dd0931..145812c4fff 100644 --- a/integrations/common/rest/src/test/java/io/helidon/integrations/common/rest/RestApiTest.java +++ b/integrations/common/rest/src/test/java/io/helidon/integrations/common/rest/RestApiTest.java @@ -21,18 +21,18 @@ import java.util.Optional; import java.util.function.Function; -import io.helidon.http.Http; import io.helidon.http.ServerRequestHeaders; +import io.helidon.http.Status; import io.helidon.http.media.MediaContext; import io.helidon.http.media.jsonp.JsonpSupport; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import jakarta.json.Json; import jakarta.json.JsonBuilderFactory; @@ -41,8 +41,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; -import static io.helidon.http.Http.Method.PUT; +import static io.helidon.http.Method.GET; +import static io.helidon.http.Method.PUT; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; @@ -111,7 +111,7 @@ void testGetFound() { var response = restApi.get("/echo", RestRequest.builder(), responseBuilder); assertThat(response.entity(), not(Optional.empty())); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } @Test @@ -121,7 +121,7 @@ void testGetNotFound() { var response = restApi.get("/missing", RestRequest.builder(), responseBuilder); assertThat(response.entity(), is(Optional.empty())); - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } private static class TestApiService implements HttpService { diff --git a/integrations/micrometer/micrometer/src/main/java/io/helidon/integrations/micrometer/MeterRegistryFactory.java b/integrations/micrometer/micrometer/src/main/java/io/helidon/integrations/micrometer/MeterRegistryFactory.java index 411573f0eb3..3ad80af9569 100644 --- a/integrations/micrometer/micrometer/src/main/java/io/helidon/integrations/micrometer/MeterRegistryFactory.java +++ b/integrations/micrometer/micrometer/src/main/java/io/helidon/integrations/micrometer/MeterRegistryFactory.java @@ -29,7 +29,7 @@ import java.util.logging.Logger; import io.helidon.common.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.Handler; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -234,7 +234,7 @@ Handler matchingHandler(ServerRequest serverRequest, .flatMap(Optional::stream) .findFirst() .orElse((req, res) -> res - .status(Http.Status.NOT_ACCEPTABLE_406) + .status(Status.NOT_ACCEPTABLE_406) .send(NO_MATCHING_REGISTRY_ERROR_MESSAGE)); } diff --git a/integrations/micrometer/micrometer/src/main/java/io/helidon/integrations/micrometer/PrometheusHandler.java b/integrations/micrometer/micrometer/src/main/java/io/helidon/integrations/micrometer/PrometheusHandler.java index ba01710eed9..1159e4e3f45 100644 --- a/integrations/micrometer/micrometer/src/main/java/io/helidon/integrations/micrometer/PrometheusHandler.java +++ b/integrations/micrometer/micrometer/src/main/java/io/helidon/integrations/micrometer/PrometheusHandler.java @@ -19,7 +19,8 @@ import java.io.StringWriter; import io.helidon.common.media.type.MediaTypes; -import io.helidon.http.Http; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webserver.http.Handler; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -46,17 +47,17 @@ static PrometheusHandler create(MeterRegistry registry) { public void handle(ServerRequest req, ServerResponse res) throws Exception { res.headers().contentType(MediaTypes.TEXT_PLAIN); - Http.Method method = req.prologue().method(); + Method method = req.prologue().method(); - if (method == Http.Method.GET) { + if (method == Method.GET) { res.send(registry.scrape()); - } else if (method == Http.Method.OPTIONS) { + } else if (method == Method.OPTIONS) { StringWriter writer = new StringWriter(); MicrometerPrometheusRegistrySupport.metadata(writer, registry); res.send(writer.toString()); } else { - res.status(Http.Status.NOT_IMPLEMENTED_501) + res.status(Status.NOT_IMPLEMENTED_501) .send(); } } diff --git a/integrations/micrometer/micrometer/src/test/java/io/helidon/integrations/micrometer/MicrometerEndpointTests.java b/integrations/micrometer/micrometer/src/test/java/io/helidon/integrations/micrometer/MicrometerEndpointTests.java index e4d83d25464..ce17b2755be 100644 --- a/integrations/micrometer/micrometer/src/test/java/io/helidon/integrations/micrometer/MicrometerEndpointTests.java +++ b/integrations/micrometer/micrometer/src/test/java/io/helidon/integrations/micrometer/MicrometerEndpointTests.java @@ -15,20 +15,20 @@ */ package io.helidon.integrations.micrometer; -import static org.hamcrest.Matchers.is; - import java.util.concurrent.ExecutionException; import java.util.function.Supplier; -import io.helidon.http.Http; import io.helidon.config.Config; import io.helidon.config.ConfigSources; +import io.helidon.http.Status; import io.helidon.webclient.api.WebClient; import io.helidon.webserver.WebServer; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; +import static org.hamcrest.Matchers.is; + public class MicrometerEndpointTests { private static Config overallTestConfig = Config.create(ConfigSources.classpath("/micrometerTestData.json")); @@ -78,14 +78,14 @@ private static void runTest(String contextForRequest, Supplier router.addFeature(() -> micrometerFeatureSupplier.get())) .build() .start(); - Http.Status status = WebClient.builder() + Status status = WebClient.builder() .baseUri(String.format("http://localhost:%d%s", webServer.port(), contextForRequest)) .build() .get() // .header(Header.ACCEPT, MediaTypes.TEXT_PLAIN.toString()) .request().status(); - MatcherAssert.assertThat(status, is(Http.Status.OK_200)); + MatcherAssert.assertThat(status, is(Status.OK_200)); } finally { webServer.stop(); } diff --git a/integrations/micrometer/micrometer/src/test/java/io/helidon/integrations/micrometer/MicrometerSimplePrometheusTest.java b/integrations/micrometer/micrometer/src/test/java/io/helidon/integrations/micrometer/MicrometerSimplePrometheusTest.java index e2c7e760a47..9b6a7a39ac2 100644 --- a/integrations/micrometer/micrometer/src/test/java/io/helidon/integrations/micrometer/MicrometerSimplePrometheusTest.java +++ b/integrations/micrometer/micrometer/src/test/java/io/helidon/integrations/micrometer/MicrometerSimplePrometheusTest.java @@ -20,8 +20,9 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import io.helidon.http.Http; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webclient.api.ClientResponseTyped; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; @@ -86,13 +87,13 @@ public void checkViaMediaType() { counter1.increment(3); gauge1.set(4); ClientResponseTyped response = webClient.get() - .header(Http.HeaderNames.ACCEPT, MediaTypes.TEXT_PLAIN.text()) + .header(HeaderNames.ACCEPT, MediaTypes.TEXT_PLAIN.text()) .path("/micrometer") .request(String.class); String promOutput = response.entity(); - assertThat("Unexpected HTTP status, response is: " + promOutput, response.status(), is(Http.Status.OK_200)); + assertThat("Unexpected HTTP status, response is: " + promOutput, response.status(), is(Status.OK_200)); } @Test @@ -101,22 +102,22 @@ public void checkViaQueryParam() { counter1.increment(3); gauge1.set(4); ClientResponseTyped response = webClient.get() - .header(Http.HeaderNames.ACCEPT, MediaTypes.create(MediaTypes.TEXT_PLAIN.type(), "special").toString()) + .header(HeaderNames.ACCEPT, MediaTypes.create(MediaTypes.TEXT_PLAIN.type(), "special").toString()) .path("/micrometer") .queryParam("type", "prometheus") .request(String.class); - assertThat("Unexpected HTTP status", response.status(), is(Http.Status.OK_200)); + assertThat("Unexpected HTTP status", response.status(), is(Status.OK_200)); } @Test public void checkNoMatch() throws ExecutionException, InterruptedException { try(HttpClientResponse response = webClient.get() - .header(Http.HeaderNames.ACCEPT, MediaTypes.create(MediaTypes.TEXT_PLAIN.type(), "special").toString()) + .header(HeaderNames.ACCEPT, MediaTypes.create(MediaTypes.TEXT_PLAIN.type(), "special").toString()) .path("/micrometer") .request()) { - assertThat("Expected failed HTTP status", response.status(), is(Http.Status.NOT_ACCEPTABLE_406)); + assertThat("Expected failed HTTP status", response.status(), is(Status.NOT_ACCEPTABLE_406)); } } diff --git a/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleAuthImpl.java b/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleAuthImpl.java index e0054e9f72d..fba7ab0eca3 100644 --- a/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleAuthImpl.java +++ b/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleAuthImpl.java @@ -16,7 +16,7 @@ package io.helidon.integrations.vault.auths.approle; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.integrations.common.rest.RestApi; import io.helidon.integrations.vault.VaultOptionalResponse; @@ -57,7 +57,7 @@ public VaultOptionalResponse readRoleId(ReadRoleId.Request public GenerateSecretId.Response generateSecretId(GenerateSecretId.Request request) { String apiPath = "/auth/" + path + "/role/" + request.roleName() + "/secret-id"; - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, GenerateSecretId.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, GenerateSecretId.Response.builder()); } @Override @@ -71,7 +71,7 @@ public DestroySecretId.Response destroySecretId(DestroySecretId.Request request) public Login.Response login(Login.Request request) { String apiPath = "/auth/" + path + "/login"; - return restApi.invokeWithResponse(Http.Method.POST, + return restApi.invokeWithResponse(Method.POST, apiPath, request, Login.Response.builder()); diff --git a/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleRestApi.java b/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleRestApi.java index a26fa9a2be3..f5e062445d3 100644 --- a/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleRestApi.java +++ b/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleRestApi.java @@ -20,7 +20,9 @@ import java.time.Instant; import java.util.concurrent.atomic.AtomicReference; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; import io.helidon.integrations.common.rest.ApiRequest; import io.helidon.integrations.vault.VaultTokenBase; import io.helidon.integrations.vault.auths.common.VaultRestApi; @@ -29,7 +31,7 @@ class AppRoleRestApi extends VaultRestApi { private static final System.Logger LOGGER = System.getLogger(AppRoleRestApi.class.getName()); - private static final Http.HeaderName VAULT_TOKEN_HEADER_NAME = Http.HeaderNames.create("X-Vault-Token"); + private static final HeaderName VAULT_TOKEN_HEADER_NAME = HeaderNames.create("X-Vault-Token"); private final AtomicReference currentToken = new AtomicReference<>(); @@ -53,7 +55,7 @@ static Builder appRoleBuilder() { protected HttpClientRequest updateRequestBuilderCommon(HttpClientRequest requestBuilder, String path, ApiRequest request, - Http.Method method, + Method method, String requestId) { VaultTokenBase currentToken = this.currentToken.get(); diff --git a/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleVaultAuth.java b/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleVaultAuth.java index 8a8e724a68b..b3e0e96d181 100644 --- a/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleVaultAuth.java +++ b/integrations/vault/auths/approle/src/main/java/io/helidon/integrations/vault/auths/approle/AppRoleVaultAuth.java @@ -22,7 +22,8 @@ import io.helidon.common.Weight; import io.helidon.common.Weighted; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.integrations.common.rest.RestApi; import io.helidon.integrations.vault.Vault; import io.helidon.integrations.vault.VaultApiException; @@ -35,7 +36,7 @@ @Weight(Weighted.DEFAULT_WEIGHT + 100) public class AppRoleVaultAuth implements VaultAuth { private static final System.Logger LOGGER = System.getLogger(AppRoleVaultAuth.class.getName()); - private static final Http.HeaderName VAULT_NAMESPACE_HEADER_NAME = Http.HeaderNames.create("X-Vault-Namespace"); + private static final HeaderName VAULT_NAMESPACE_HEADER_NAME = HeaderNames.create("X-Vault-Namespace"); private final String appRoleId; private final String secretId; private final String methodPath; diff --git a/integrations/vault/auths/common/src/main/java/io/helidon/integrations/vault/auths/common/NoVaultAuth.java b/integrations/vault/auths/common/src/main/java/io/helidon/integrations/vault/auths/common/NoVaultAuth.java index 74cbdd34508..f996e5fa1f4 100644 --- a/integrations/vault/auths/common/src/main/java/io/helidon/integrations/vault/auths/common/NoVaultAuth.java +++ b/integrations/vault/auths/common/src/main/java/io/helidon/integrations/vault/auths/common/NoVaultAuth.java @@ -20,7 +20,8 @@ import io.helidon.common.Weight; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.integrations.common.rest.RestApi; import io.helidon.integrations.vault.Vault; import io.helidon.integrations.vault.VaultApiException; @@ -31,7 +32,7 @@ */ @Weight(1) public class NoVaultAuth implements VaultAuth { - private static final Http.HeaderName VAULT_NAMESPACE_HEADER_NAME = Http.HeaderNames.create("X-Vault-Namespace"); + private static final HeaderName VAULT_NAMESPACE_HEADER_NAME = HeaderNames.create("X-Vault-Namespace"); /** * Required for service loader. */ diff --git a/integrations/vault/auths/common/src/main/java/io/helidon/integrations/vault/auths/common/VaultRestApi.java b/integrations/vault/auths/common/src/main/java/io/helidon/integrations/vault/auths/common/VaultRestApi.java index 2b855faab00..9351728ee9e 100644 --- a/integrations/vault/auths/common/src/main/java/io/helidon/integrations/vault/auths/common/VaultRestApi.java +++ b/integrations/vault/auths/common/src/main/java/io/helidon/integrations/vault/auths/common/VaultRestApi.java @@ -20,7 +20,7 @@ import java.util.LinkedList; import java.util.List; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.integrations.common.rest.ApiRequest; import io.helidon.integrations.common.rest.ApiRestException; import io.helidon.integrations.common.rest.ResponseBuilder; @@ -57,7 +57,7 @@ public static Builder builder() { @Override protected T emptyResponse(String path, ApiRequest request, - Http.Method method, + Method method, String requestId, HttpClientResponse response, ResponseBuilder responseBuilder) { @@ -89,7 +89,7 @@ protected T emptyResponse(String path, @Override protected ApiRestException readError(String path, ApiRequest request, - Http.Method method, + Method method, String requestId, HttpClientResponse response, JsonObject entity) { diff --git a/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sAuthImpl.java b/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sAuthImpl.java index d5534445b8f..14076cf222a 100644 --- a/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sAuthImpl.java +++ b/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sAuthImpl.java @@ -16,7 +16,7 @@ package io.helidon.integrations.vault.auths.k8s; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.integrations.common.rest.RestApi; class K8sAuthImpl implements K8sAuth { @@ -53,6 +53,6 @@ public ConfigureK8s.Response configure(ConfigureK8s.Request request) { public Login.Response login(Login.Request request) { String apiPath = "/auth/" + path + "/login"; - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, Login.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, Login.Response.builder()); } } diff --git a/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sRestApi.java b/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sRestApi.java index 8d060c0b890..b4cf025f119 100644 --- a/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sRestApi.java +++ b/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sRestApi.java @@ -19,7 +19,9 @@ import java.time.Instant; import java.util.concurrent.atomic.AtomicReference; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; import io.helidon.integrations.common.rest.ApiRequest; import io.helidon.integrations.vault.VaultTokenBase; import io.helidon.integrations.vault.auths.common.VaultRestApi; @@ -27,7 +29,7 @@ class K8sRestApi extends VaultRestApi { - private static final Http.HeaderName VAULT_TOKEN_HEADER_NAME = Http.HeaderNames.create("X-Vault-Token"); + private static final HeaderName VAULT_TOKEN_HEADER_NAME = HeaderNames.create("X-Vault-Token"); private final AtomicReference currentToken = new AtomicReference<>(); private final K8sAuth auth; @@ -50,7 +52,7 @@ static Builder k8sBuilder() { protected HttpClientRequest updateRequestBuilderCommon(HttpClientRequest requestBuilder, String path, ApiRequest request, - Http.Method method, + Method method, String requestId) { VaultTokenBase k8sToken = currentToken.get(); diff --git a/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sVaultAuth.java b/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sVaultAuth.java index e67a6eb7f75..8b860bb5e1d 100644 --- a/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sVaultAuth.java +++ b/integrations/vault/auths/k8s/src/main/java/io/helidon/integrations/vault/auths/k8s/K8sVaultAuth.java @@ -26,7 +26,8 @@ import io.helidon.common.Weight; import io.helidon.common.Weighted; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.integrations.common.rest.RestApi; import io.helidon.integrations.vault.Vault; import io.helidon.integrations.vault.VaultApiException; @@ -39,7 +40,7 @@ @Weight(Weighted.DEFAULT_WEIGHT + 50) public class K8sVaultAuth implements VaultAuth { private static final System.Logger LOGGER = System.getLogger(K8sVaultAuth.class.getName()); - private static final Http.HeaderName VAULT_NAMESPACE_HEADER_NAME = Http.HeaderNames.create("X-Vault-Namespace"); + private static final HeaderName VAULT_NAMESPACE_HEADER_NAME = HeaderNames.create("X-Vault-Namespace"); private final String serviceAccountToken; private final String tokenRole; private final String tokenLocation; diff --git a/integrations/vault/auths/token/src/main/java/io/helidon/integrations/vault/auths/token/TokenAuthImpl.java b/integrations/vault/auths/token/src/main/java/io/helidon/integrations/vault/auths/token/TokenAuthImpl.java index 73825cf0d51..378a92b5b07 100644 --- a/integrations/vault/auths/token/src/main/java/io/helidon/integrations/vault/auths/token/TokenAuthImpl.java +++ b/integrations/vault/auths/token/src/main/java/io/helidon/integrations/vault/auths/token/TokenAuthImpl.java @@ -16,7 +16,7 @@ package io.helidon.integrations.vault.auths.token; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.integrations.common.rest.RestApi; class TokenAuthImpl implements TokenAuth { @@ -32,14 +32,14 @@ class TokenAuthImpl implements TokenAuth { public CreateToken.Response createToken(CreateToken.Request request) { String apiPath = "/auth/" + path + "/create" + request.roleName().map(it -> "/" + it).orElse(""); - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, CreateToken.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, CreateToken.Response.builder()); } @Override public RenewToken.Response renew(RenewToken.Request request) { String apiPath = "/auth/" + path + "/renew"; - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, RenewToken.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, RenewToken.Response.builder()); } @Override diff --git a/integrations/vault/auths/token/src/main/java/io/helidon/integrations/vault/auths/token/TokenVaultAuth.java b/integrations/vault/auths/token/src/main/java/io/helidon/integrations/vault/auths/token/TokenVaultAuth.java index f582fa7eb73..5d1c31a49ae 100644 --- a/integrations/vault/auths/token/src/main/java/io/helidon/integrations/vault/auths/token/TokenVaultAuth.java +++ b/integrations/vault/auths/token/src/main/java/io/helidon/integrations/vault/auths/token/TokenVaultAuth.java @@ -22,7 +22,8 @@ import io.helidon.common.Weight; import io.helidon.common.Weighted; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.integrations.common.rest.RestApi; import io.helidon.integrations.vault.Vault; import io.helidon.integrations.vault.VaultApiException; @@ -37,8 +38,8 @@ @Weight(Weighted.DEFAULT_WEIGHT) public class TokenVaultAuth implements VaultAuth { private static final System.Logger LOGGER = System.getLogger(TokenVaultAuth.class.getName()); - private static final Http.HeaderName VAULT_TOKEN_HEADER_NAME = Http.HeaderNames.create("X-Vault-Token"); - private static final Http.HeaderName VAULT_NAMESPACE_HEADER_NAME = Http.HeaderNames.create("X-Vault-Namespace"); + private static final HeaderName VAULT_TOKEN_HEADER_NAME = HeaderNames.create("X-Vault-Token"); + private static final HeaderName VAULT_NAMESPACE_HEADER_NAME = HeaderNames.create("X-Vault-Namespace"); private final String token; private final String baseNamespace; diff --git a/integrations/vault/secrets/kv2/src/main/java/io/helidon/integrations/vault/secrets/kv2/Kv2SecretsImpl.java b/integrations/vault/secrets/kv2/src/main/java/io/helidon/integrations/vault/secrets/kv2/Kv2SecretsImpl.java index 99b87a26678..3ab53d6043f 100644 --- a/integrations/vault/secrets/kv2/src/main/java/io/helidon/integrations/vault/secrets/kv2/Kv2SecretsImpl.java +++ b/integrations/vault/secrets/kv2/src/main/java/io/helidon/integrations/vault/secrets/kv2/Kv2SecretsImpl.java @@ -18,7 +18,7 @@ import java.util.Optional; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.integrations.common.rest.RestApi; import io.helidon.integrations.vault.ListSecrets; import io.helidon.integrations.vault.Vault; @@ -69,7 +69,7 @@ public UpdateKv2.Response update(UpdateKv2.Request request) { } String apiPath = mount + "/data/" + path; - return restApi.invokeWithResponse(Http.Method.POST, + return restApi.invokeWithResponse(Method.POST, apiPath, request, UpdateKv2.Response.builder()); diff --git a/integrations/vault/secrets/pki/src/main/java/io/helidon/integrations/vault/secrets/pki/PkiSecretsImpl.java b/integrations/vault/secrets/pki/src/main/java/io/helidon/integrations/vault/secrets/pki/PkiSecretsImpl.java index 5b31be84fc6..c7f7bcae880 100644 --- a/integrations/vault/secrets/pki/src/main/java/io/helidon/integrations/vault/secrets/pki/PkiSecretsImpl.java +++ b/integrations/vault/secrets/pki/src/main/java/io/helidon/integrations/vault/secrets/pki/PkiSecretsImpl.java @@ -18,7 +18,7 @@ import java.util.function.Function; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.integrations.common.rest.RestApi; import io.helidon.integrations.vault.ListSecrets; import io.helidon.integrations.vault.Vault; @@ -122,7 +122,7 @@ public CrlGet.Response crl(CrlGet.Request request) { public IssueCertificate.Response issueCertificate(IssueCertificate.Request request) { String apiPath = mount + "/issue/" + request.roleName(); - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, + return restApi.invokeWithResponse(Method.POST, apiPath, request, IssueCertificate.Response.builder() .format(request.format())); } @@ -131,7 +131,7 @@ public IssueCertificate.Response issueCertificate(IssueCertificate.Request reque public SignCsr.Response signCertificateRequest(SignCsr.Request request) { String apiPath = mount + "/sign/" + request.roleName(); - return restApi.invokeWithResponse(Http.Method.POST, + return restApi.invokeWithResponse(Method.POST, apiPath, request, SignCsr.Response.builder() @@ -142,7 +142,7 @@ public SignCsr.Response signCertificateRequest(SignCsr.Request request) { public RevokeCertificate.Response revokeCertificate(RevokeCertificate.Request request) { String apiPath = mount + "/revoke"; - return restApi.invokeWithResponse(Http.Method.POST, + return restApi.invokeWithResponse(Method.POST, apiPath, request, RevokeCertificate.Response.builder()); diff --git a/integrations/vault/secrets/transit/src/main/java/io/helidon/integrations/vault/secrets/transit/TransitSecretsImpl.java b/integrations/vault/secrets/transit/src/main/java/io/helidon/integrations/vault/secrets/transit/TransitSecretsImpl.java index 30a59ba061f..0db43b3bf43 100644 --- a/integrations/vault/secrets/transit/src/main/java/io/helidon/integrations/vault/secrets/transit/TransitSecretsImpl.java +++ b/integrations/vault/secrets/transit/src/main/java/io/helidon/integrations/vault/secrets/transit/TransitSecretsImpl.java @@ -16,7 +16,7 @@ package io.helidon.integrations.vault.secrets.transit; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.integrations.common.rest.RestApi; import io.helidon.integrations.vault.ListSecrets; import io.helidon.integrations.vault.Vault; @@ -69,48 +69,48 @@ public UpdateKeyConfig.Response updateKeyConfig(UpdateKeyConfig.Request request) public Encrypt.Response encrypt(Encrypt.Request request) { String apiPath = "/" + mount + "/encrypt/" + request.encryptionKeyName(); - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, Encrypt.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, Encrypt.Response.builder()); } @Override public EncryptBatch.Response encrypt(EncryptBatch.Request request) { String apiPath = "/" + mount + "/encrypt/" + request.encryptionKeyName(); - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, EncryptBatch.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, EncryptBatch.Response.builder()); } @Override public Decrypt.Response decrypt(Decrypt.Request request) { String apiPath = "/" + mount + "/decrypt/" + request.encryptionKeyName(); - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, Decrypt.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, Decrypt.Response.builder()); } @Override public DecryptBatch.Response decrypt(DecryptBatch.Request request) { String apiPath = "/" + mount + "/decrypt/" + request.encryptionKeyName(); - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, DecryptBatch.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, DecryptBatch.Response.builder()); } @Override public Hmac.Response hmac(Hmac.Request request) { String apiPath = "/" + mount + "/hmac/" + request.hmacKeyName(); - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, Hmac.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, Hmac.Response.builder()); } @Override public Sign.Response sign(Sign.Request request) { String apiPath = "/" + mount + "/sign/" + request.signatureKeyName(); - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, Sign.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, Sign.Response.builder()); } @Override public Verify.Response verify(Verify.Request request) { String apiPath = "/" + mount + "/verify/" + request.digestKeyName(); - return restApi.invokeWithResponse(Http.Method.POST, apiPath, request, Verify.Response.builder()); + return restApi.invokeWithResponse(Method.POST, apiPath, request, Verify.Response.builder()); } } diff --git a/integrations/vault/vault/src/main/java/io/helidon/integrations/vault/Vault.java b/integrations/vault/vault/src/main/java/io/helidon/integrations/vault/Vault.java index c62ea7cc9b8..6410a48c1be 100644 --- a/integrations/vault/vault/src/main/java/io/helidon/integrations/vault/Vault.java +++ b/integrations/vault/vault/src/main/java/io/helidon/integrations/vault/Vault.java @@ -25,7 +25,7 @@ import io.helidon.config.Config; import io.helidon.faulttolerance.FaultTolerance; import io.helidon.faulttolerance.FtHandler; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.integrations.common.rest.RestApi; import io.helidon.integrations.vault.spi.VaultAuth; import io.helidon.webclient.api.WebClientConfig; @@ -41,7 +41,7 @@ public interface Vault { /** * HTTP {@code LIST} method used by several Vault engines. */ - Http.Method LIST = Http.Method.create("LIST"); + Method LIST = Method.create("LIST"); /** * Fluent API builder to construct new instances. diff --git a/integrations/vault/vault/src/main/java/io/helidon/integrations/vault/VaultOptionalResponse.java b/integrations/vault/vault/src/main/java/io/helidon/integrations/vault/VaultOptionalResponse.java index 94c7f238791..797479d157a 100644 --- a/integrations/vault/vault/src/main/java/io/helidon/integrations/vault/VaultOptionalResponse.java +++ b/integrations/vault/vault/src/main/java/io/helidon/integrations/vault/VaultOptionalResponse.java @@ -24,8 +24,8 @@ /** * Response for Vault operations that may contain entity. - * The entity is present for successful requests (returning {@link io.helidon.http.Http.Status#OK_200}; - * entity is not present if the response was {@link io.helidon.http.Http.Status#NOT_FOUND_404}). + * The entity is present for successful requests (returning {@link io.helidon.http.Status#OK_200}; + * entity is not present if the response was {@link io.helidon.http.Status#NOT_FOUND_404}). * * @param type of the response - a subclass of this class */ @@ -57,7 +57,7 @@ public static Builder vaultResponseBuilder() { /** * List of errors (if any) as returned by Vault. - * This list may contain errors when we get a {@link io.helidon.http.Http.Status#NOT_FOUND_404}. + * This list may contain errors when we get a {@link io.helidon.http.Status#NOT_FOUND_404}. * * @return list of errors from Vault */ diff --git a/jersey/connector/src/main/java/io/helidon/jersey/connector/HelidonConnector.java b/jersey/connector/src/main/java/io/helidon/jersey/connector/HelidonConnector.java index 97efacc587a..0f1b710f29d 100644 --- a/jersey/connector/src/main/java/io/helidon/jersey/connector/HelidonConnector.java +++ b/jersey/connector/src/main/java/io/helidon/jersey/connector/HelidonConnector.java @@ -32,7 +32,9 @@ import io.helidon.common.tls.Tls; import io.helidon.common.uri.UriQueryWriteable; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; import io.helidon.http.media.ReadableEntity; import io.helidon.webclient.api.Proxy; import io.helidon.webclient.http1.Http1Client; @@ -108,7 +110,7 @@ private Http1ClientRequest mapRequest(ClientRequest request) { // create WebClient request URI uri = request.getUri(); Http1ClientRequest httpRequest = httpClient - .method(Http.Method.create(request.getMethod())) + .method(Method.create(request.getMethod())) .proxy(requestProxy) .uri(uri); @@ -126,7 +128,7 @@ private Http1ClientRequest mapRequest(ClientRequest request) { // map request headers request.getRequestHeaders().forEach((key, value) -> { String[] values = value.toArray(new String[0]); - httpRequest.header(Http.HeaderNames.create(key), values); + httpRequest.header(HeaderNames.create(key), values); }); // SSL context @@ -184,7 +186,7 @@ public String getReasonPhrase() { }, request); // copy headers - for (Http.Header header : httpResponse.headers()) { + for (Header header : httpResponse.headers()) { for (String v : header.allValues()) { response.getHeaders().add(header.name(), v); } diff --git a/jersey/tests/connector/src/test/java/io/helidon/jersey/connector/JerseyConnectorTest.java b/jersey/tests/connector/src/test/java/io/helidon/jersey/connector/JerseyConnectorTest.java index b4b7efa8029..e072fbca8bf 100644 --- a/jersey/tests/connector/src/test/java/io/helidon/jersey/connector/JerseyConnectorTest.java +++ b/jersey/tests/connector/src/test/java/io/helidon/jersey/connector/JerseyConnectorTest.java @@ -18,7 +18,7 @@ import java.util.Arrays; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.ServerRequest; @@ -70,18 +70,18 @@ private WebTarget target(String uri) { } static void basicGet(ServerRequest request, ServerResponse response) { - response.status(Http.Status.OK_200).send("ok"); + response.status(Status.OK_200).send("ok"); } static void basicPost(ServerRequest request, ServerResponse response) { String entity = request.content().as(String.class); - response.status(Http.Status.OK_200).send(entity + entity); + response.status(Status.OK_200).send(entity + entity); } static void basicGetQuery(ServerRequest request, ServerResponse response) { String first = request.query().get("first"); String second = request.query().get("second"); - response.status(Http.Status.OK_200).send(first + second); + response.status(Status.OK_200).send(first + second); } static void basicHeaders(ServerRequest request, ServerResponse response) { @@ -89,7 +89,7 @@ static void basicHeaders(ServerRequest request, ServerResponse response) { .stream() .filter(h -> h.name().startsWith("X-TEST")) .forEach(response::header); - response.status(Http.Status.OK_200).send("ok"); + response.status(Status.OK_200).send("ok"); } @Test diff --git a/logging/tests/log4j/src/test/java/io/helidon/logging/tests/log4j/Log4jTest.java b/logging/tests/log4j/src/test/java/io/helidon/logging/tests/log4j/Log4jTest.java index 84713a94872..5df77125ba8 100644 --- a/logging/tests/log4j/src/test/java/io/helidon/logging/tests/log4j/Log4jTest.java +++ b/logging/tests/log4j/src/test/java/io/helidon/logging/tests/log4j/Log4jTest.java @@ -16,11 +16,11 @@ package io.helidon.logging.tests.log4j; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Method; import io.helidon.webclient.http1.Http1Client; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -46,7 +46,7 @@ static void routing(HttpRules builder) { //The server should just work @Test void testOk() { - String response = client.method(Http.Method.GET) + String response = client.method(Method.GET) .requestEntity(String.class); LOGGER.log(System.Logger.Level.DEBUG, "Message"); diff --git a/lra/coordinator/client/narayana-client/src/main/java/io/helidon/lra/coordinator/client/narayana/NarayanaClient.java b/lra/coordinator/client/narayana-client/src/main/java/io/helidon/lra/coordinator/client/narayana/NarayanaClient.java index 0afd1701fa2..ae2f0a20fc5 100644 --- a/lra/coordinator/client/narayana-client/src/main/java/io/helidon/lra/coordinator/client/narayana/NarayanaClient.java +++ b/lra/coordinator/client/narayana-client/src/main/java/io/helidon/lra/coordinator/client/narayana/NarayanaClient.java @@ -30,7 +30,10 @@ import io.helidon.common.socket.SocketOptions; import io.helidon.faulttolerance.Retry; import io.helidon.http.ClientRequestHeaders; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.http.media.MediaContext; import io.helidon.lra.coordinator.client.CoordinatorClient; import io.helidon.lra.coordinator.client.CoordinatorConnectionException; @@ -47,8 +50,8 @@ * Narayana LRA coordinator client. */ public class NarayanaClient implements CoordinatorClient { - private static final Http.HeaderName LRA_HTTP_CONTEXT_HEADER = Http.HeaderNames.create(LRA.LRA_HTTP_CONTEXT_HEADER); - private static final Http.HeaderName LRA_HTTP_RECOVERY_HEADER = Http.HeaderNames.create(LRA.LRA_HTTP_RECOVERY_HEADER); + private static final HeaderName LRA_HTTP_CONTEXT_HEADER = HeaderNames.create(LRA.LRA_HTTP_CONTEXT_HEADER); + private static final HeaderName LRA_HTTP_RECOVERY_HEADER = HeaderNames.create(LRA.LRA_HTTP_RECOVERY_HEADER); private static final System.Logger LOGGER = System.getLogger(NarayanaClient.class.getName()); @@ -110,14 +113,14 @@ private URI startInternal(URI parentLRA, String clientID, PropagatedHeaders head .queryParam(QUERY_PARAM_PARENT_LRA, parentLRA == null ? "" : parentLRA.toASCIIString()); try (HttpClientResponse res = req.request()) { - Http.Status status = res.status(); + Status status = res.status(); if (status.code() != 201) { throw connectionError("Unexpected response " + status + " from coordinator " + req.resolvedUri() + ": " + res.as(String.class), null); } //propagate supported headers from coordinator headers.scan(res.headers().toMap()); - URI lraId = res.headers().first(Http.HeaderNames.LOCATION) + URI lraId = res.headers().first(HeaderNames.LOCATION) // TMM doesn't send lraId as LOCATION .or(() -> res.headers().first(LRA_HTTP_CONTEXT_HEADER)) .map(URI::create) @@ -200,9 +203,9 @@ public Optional join(URI lraId, .queryParam(QUERY_PARAM_TIME_LIMIT, String.valueOf(timeLimit)) .headers(h -> { // links are expected either in header - h.add(Http.Headers.createCached(HEADER_LINK, links)); + h.add(HeaderValues.createCached(HEADER_LINK, links)); // header propagation - headers.toMap().forEach((name, value) -> h.set(Http.HeaderNames.create(name), value)); + headers.toMap().forEach((name, value) -> h.set(HeaderNames.create(name), value)); }); try (var res = req.submit(links)) { @@ -333,7 +336,7 @@ private String compensatorLinks(Participant p) { private Consumer copyHeaders(PropagatedHeaders headers) { return wcHeaders -> { - headers.toMap().forEach((key, value) -> wcHeaders.set(Http.HeaderNames.create(key), value)); + headers.toMap().forEach((key, value) -> wcHeaders.set(HeaderNames.create(key), value)); }; } diff --git a/lra/coordinator/server/src/main/java/io/helidon/lra/coordinator/CoordinatorService.java b/lra/coordinator/server/src/main/java/io/helidon/lra/coordinator/CoordinatorService.java index 32612bf779c..32a2f332b38 100644 --- a/lra/coordinator/server/src/main/java/io/helidon/lra/coordinator/CoordinatorService.java +++ b/lra/coordinator/server/src/main/java/io/helidon/lra/coordinator/CoordinatorService.java @@ -32,7 +32,8 @@ import io.helidon.common.LazyValue; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.scheduling.FixedRateInvocation; import io.helidon.scheduling.Scheduling; import io.helidon.scheduling.Task; @@ -50,11 +51,11 @@ import org.eclipse.microprofile.lra.annotation.LRAStatus; import org.eclipse.microprofile.lra.annotation.ws.rs.LRA; -import static io.helidon.http.Http.Status.CREATED_201; -import static io.helidon.http.Http.Status.GONE_410; -import static io.helidon.http.Http.Status.NOT_FOUND_404; -import static io.helidon.http.Http.Status.OK_200; -import static io.helidon.http.Http.Status.PRECONDITION_FAILED_412; +import static io.helidon.http.Status.CREATED_201; +import static io.helidon.http.Status.GONE_410; +import static io.helidon.http.Status.NOT_FOUND_404; +import static io.helidon.http.Status.OK_200; +import static io.helidon.http.Status.PRECONDITION_FAILED_412; /** * LRA coordinator with Narayana like rest api. @@ -72,8 +73,8 @@ public class CoordinatorService implements HttpService { static final String DEFAULT_COORDINATOR_URL = "http://localhost:8070/lra-coordinator"; private static final System.Logger LOGGER = System.getLogger(CoordinatorService.class.getName()); - private static final Http.HeaderName LRA_HTTP_CONTEXT_HEADER = Http.HeaderNames.create(LRA.LRA_HTTP_CONTEXT_HEADER); - private static final Http.HeaderName LRA_HTTP_RECOVERY_HEADER = Http.HeaderNames.create(LRA.LRA_HTTP_RECOVERY_HEADER); + private static final HeaderName LRA_HTTP_CONTEXT_HEADER = HeaderNames.create(LRA.LRA_HTTP_CONTEXT_HEADER); + private static final HeaderName LRA_HTTP_RECOVERY_HEADER = HeaderNames.create(LRA.LRA_HTTP_RECOVERY_HEADER); private static final Set RECOVERABLE_STATUSES = Set.of(LRAStatus.Cancelling, LRAStatus.Closing, LRAStatus.Active); private static final JsonBuilderFactory JSON = Json.createBuilderFactory(Collections.emptyMap()); @@ -228,7 +229,7 @@ private void cancel(ServerRequest req, ServerResponse res) { private void join(ServerRequest req, ServerResponse res) { String lraId = req.path().pathParameters().get("LraId"); - String compensatorLink = req.headers().first(Http.HeaderNames.LINK).orElse(""); + String compensatorLink = req.headers().first(HeaderNames.LINK).orElse(""); Lra lra = lraPersistentRegistry.get(lraId); if (lra == null) { @@ -243,7 +244,7 @@ private void join(ServerRequest req, ServerResponse res) { String recoveryUrl = coordinatorUriWithPath("/" + lraId + "/recovery").toASCIIString(); res.headers().set(LRA_HTTP_RECOVERY_HEADER, recoveryUrl); - res.headers().set(Http.HeaderNames.LOCATION, recoveryUrl); + res.headers().set(HeaderNames.LOCATION, recoveryUrl); res.status(OK_200) .send(recoveryUrl); } diff --git a/lra/coordinator/server/src/main/java/io/helidon/lra/coordinator/Lra.java b/lra/coordinator/server/src/main/java/io/helidon/lra/coordinator/Lra.java index 574a5b17b67..cd37fc9feb5 100644 --- a/lra/coordinator/server/src/main/java/io/helidon/lra/coordinator/Lra.java +++ b/lra/coordinator/server/src/main/java/io/helidon/lra/coordinator/Lra.java @@ -33,7 +33,8 @@ import io.helidon.common.LazyValue; import io.helidon.config.Config; import io.helidon.http.ClientRequestHeaders; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.metrics.api.Counter; import io.helidon.metrics.api.MeterRegistry; import io.helidon.metrics.api.Metrics; @@ -47,10 +48,10 @@ import static org.eclipse.microprofile.lra.annotation.ws.rs.LRA.LRA_HTTP_RECOVERY_HEADER; class Lra { - static final Http.HeaderName LRA_HTTP_CONTEXT_HEADER_NAME = Http.HeaderNames.create(LRA_HTTP_CONTEXT_HEADER); - static final Http.HeaderName LRA_HTTP_ENDED_CONTEXT_HEADER_NAME = Http.HeaderNames.create(LRA_HTTP_ENDED_CONTEXT_HEADER); - static final Http.HeaderName LRA_HTTP_PARENT_CONTEXT_HEADER_NAME = Http.HeaderNames.create(LRA_HTTP_PARENT_CONTEXT_HEADER); - static final Http.HeaderName LRA_HTTP_RECOVERY_HEADER_NAME = Http.HeaderNames.create(LRA_HTTP_RECOVERY_HEADER); + static final HeaderName LRA_HTTP_CONTEXT_HEADER_NAME = HeaderNames.create(LRA_HTTP_CONTEXT_HEADER); + static final HeaderName LRA_HTTP_ENDED_CONTEXT_HEADER_NAME = HeaderNames.create(LRA_HTTP_ENDED_CONTEXT_HEADER); + static final HeaderName LRA_HTTP_PARENT_CONTEXT_HEADER_NAME = HeaderNames.create(LRA_HTTP_PARENT_CONTEXT_HEADER); + static final HeaderName LRA_HTTP_RECOVERY_HEADER_NAME = HeaderNames.create(LRA_HTTP_RECOVERY_HEADER); private static final System.Logger LOGGER = System.getLogger(Lra.class.getName()); diff --git a/lra/coordinator/server/src/test/java/io/helidon/lra/coordinator/CoordinatorTest.java b/lra/coordinator/server/src/test/java/io/helidon/lra/coordinator/CoordinatorTest.java index aeeaabd2a7a..6c8216feea0 100644 --- a/lra/coordinator/server/src/test/java/io/helidon/lra/coordinator/CoordinatorTest.java +++ b/lra/coordinator/server/src/test/java/io/helidon/lra/coordinator/CoordinatorTest.java @@ -22,12 +22,12 @@ import io.helidon.config.Config; import io.helidon.config.ConfigSources; import io.helidon.http.media.jsonp.JsonpSupport; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; -import io.helidon.webserver.testing.junit5.Socket; import io.helidon.webclient.http1.Http1Client; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.webserver.testing.junit5.Socket; import jakarta.json.JsonArray; import jakarta.json.JsonValue; diff --git a/metrics/prometheus/src/test/java/io/helidon/metrics/prometheus/PrometheusSupportTest.java b/metrics/prometheus/src/test/java/io/helidon/metrics/prometheus/PrometheusSupportTest.java index f5097aef876..27586ed82f5 100644 --- a/metrics/prometheus/src/test/java/io/helidon/metrics/prometheus/PrometheusSupportTest.java +++ b/metrics/prometheus/src/test/java/io/helidon/metrics/prometheus/PrometheusSupportTest.java @@ -16,12 +16,13 @@ package io.helidon.metrics.prometheus; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import io.prometheus.client.CollectorRegistry; import io.prometheus.client.Counter; @@ -82,8 +83,8 @@ public void clearRegistry() { @Test public void simpleCall() { try (Http1ClientResponse response = client.get("/metrics").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers().first(Http.HeaderNames.CONTENT_TYPE).orElse(null), + assertThat(response.status(), is(Status.OK_200)); + assertThat(response.headers().first(HeaderNames.CONTENT_TYPE).orElse(null), StringStartsWith.startsWith("text/plain")); String body = response.as(String.class); assertThat(body, containsString("# HELP beta")); @@ -99,7 +100,7 @@ public void simpleCall() { @Test public void doubleCall() { try (Http1ClientResponse response = client.get("/metrics").request()) { - assertThat(response.headers().first(Http.HeaderNames.CONTENT_TYPE).orElse(null), + assertThat(response.headers().first(HeaderNames.CONTENT_TYPE).orElse(null), StringStartsWith.startsWith("text/plain")); String body = response.as(String.class); assertThat(body, containsString("alpha_total{method=\"bar\",} 6.0")); @@ -115,7 +116,7 @@ public void doubleCall() { @Test public void filter() { try (Http1ClientResponse response = client.get("/metrics").queryParam("name[]", "alpha").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String body = response.as(String.class); assertThat(body, not(containsString("# TYPE beta"))); assertThat(body, not(containsString("beta_total 3.0"))); diff --git a/microprofile/cors/src/main/java/io/helidon/microprofile/cors/CorsSupportMp.java b/microprofile/cors/src/main/java/io/helidon/microprofile/cors/CorsSupportMp.java index fd21c0e225f..242b65f378b 100644 --- a/microprofile/cors/src/main/java/io/helidon/microprofile/cors/CorsSupportMp.java +++ b/microprofile/cors/src/main/java/io/helidon/microprofile/cors/CorsSupportMp.java @@ -24,7 +24,8 @@ import io.helidon.cors.CorsResponseAdapter; import io.helidon.cors.CorsSupportBase; import io.helidon.cors.CrossOriginConfig; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import jakarta.ws.rs.container.ContainerRequestContext; import jakarta.ws.rs.container.ContainerResponseContext; @@ -111,7 +112,7 @@ static class RequestAdapterMp implements CorsRequestAdapter firstHeader(Http.HeaderName key) { + public Optional firstHeader(HeaderName key) { return Optional.ofNullable(requestContext.getHeaders().getFirst(key.defaultCase())); } @Override - public boolean headerContainsKey(Http.HeaderName key) { + public boolean headerContainsKey(HeaderName key) { return requestContext.getHeaders().containsKey(key.defaultCase()); } @Override - public List allHeaders(Http.HeaderName key) { + public List allHeaders(HeaderName key) { return requestContext.getHeaders().get(key.defaultCase()); } @@ -172,13 +173,13 @@ static class ResponseAdapterMp implements CorsResponseAdapter { } @Override - public CorsResponseAdapter header(Http.HeaderName key, String value) { + public CorsResponseAdapter header(HeaderName key, String value) { headers.add(key.defaultCase(), value); return this; } @Override - public CorsResponseAdapter header(Http.HeaderName key, Object value) { + public CorsResponseAdapter header(HeaderName key, Object value) { headers.add(key.defaultCase(), value); return this; } diff --git a/microprofile/cors/src/test/java/io/helidon/microprofile/cors/AdapterTest.java b/microprofile/cors/src/test/java/io/helidon/microprofile/cors/AdapterTest.java index 7504af80c6a..e1893b95db2 100644 --- a/microprofile/cors/src/test/java/io/helidon/microprofile/cors/AdapterTest.java +++ b/microprofile/cors/src/test/java/io/helidon/microprofile/cors/AdapterTest.java @@ -20,7 +20,7 @@ import java.util.Map; import java.util.Set; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.microprofile.tests.junit5.AddBean; import jakarta.enterprise.context.ApplicationScoped; @@ -91,7 +91,7 @@ private void testPath(String requestPath, String testId) { .request() .header(TEST_ID_HEADER, testId) .get(); - assertThat("Response status", response.getStatus(), is(Http.Status.OK_200.code())); + assertThat("Response status", response.getStatus(), is(Status.OK_200.code())); assertThat("Adapter path", TestFilter.adapters.get(testId).path(), is(requestPath)); } diff --git a/microprofile/cors/src/test/java/io/helidon/microprofile/cors/CorsDisabledTest.java b/microprofile/cors/src/test/java/io/helidon/microprofile/cors/CorsDisabledTest.java index 4b495685c1d..0fc36372080 100644 --- a/microprofile/cors/src/test/java/io/helidon/microprofile/cors/CorsDisabledTest.java +++ b/microprofile/cors/src/test/java/io/helidon/microprofile/cors/CorsDisabledTest.java @@ -16,7 +16,7 @@ package io.helidon.microprofile.cors; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.microprofile.tests.junit5.AddBean; import io.helidon.microprofile.tests.junit5.AddConfig; import io.helidon.microprofile.tests.junit5.HelidonTest; @@ -28,7 +28,7 @@ import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.ORIGIN; +import static io.helidon.http.HeaderNames.ORIGIN; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasItem; @@ -61,6 +61,6 @@ void testCorsIsDisabled() { assertThat(res.getStatusInfo(), is(Response.Status.OK)); assertThat("Headers from successful response", res.getHeaders().keySet(), - not(hasItem(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()))); + not(hasItem(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()))); } } diff --git a/microprofile/cors/src/test/java/io/helidon/microprofile/cors/CrossOriginTest.java b/microprofile/cors/src/test/java/io/helidon/microprofile/cors/CrossOriginTest.java index fd78f06ee45..5b48e5f484f 100644 --- a/microprofile/cors/src/test/java/io/helidon/microprofile/cors/CrossOriginTest.java +++ b/microprofile/cors/src/test/java/io/helidon/microprofile/cors/CrossOriginTest.java @@ -33,14 +33,14 @@ import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_MAX_AGE; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_REQUEST_HEADERS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD; -import static io.helidon.http.Http.HeaderNames.ORIGIN; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_MAX_AGE; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_REQUEST_HEADERS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD; +import static io.helidon.http.HeaderNames.ORIGIN; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; diff --git a/microprofile/cors/src/test/java/io/helidon/microprofile/cors/ErrorResponseTest.java b/microprofile/cors/src/test/java/io/helidon/microprofile/cors/ErrorResponseTest.java index 348c2d1167d..b2e7f96223d 100644 --- a/microprofile/cors/src/test/java/io/helidon/microprofile/cors/ErrorResponseTest.java +++ b/microprofile/cors/src/test/java/io/helidon/microprofile/cors/ErrorResponseTest.java @@ -16,7 +16,7 @@ package io.helidon.microprofile.cors; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.microprofile.tests.junit5.AddBean; import io.helidon.microprofile.tests.junit5.AddConfig; import io.helidon.microprofile.tests.junit5.HelidonTest; @@ -26,7 +26,7 @@ import jakarta.ws.rs.core.Response; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.ORIGIN; +import static io.helidon.http.HeaderNames.ORIGIN; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -52,11 +52,11 @@ void testErrorResponse() { Response res = target.path("/notfound") .request() .header(ORIGIN.defaultCase(), "http://foo.bar") - .header(Http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD.defaultCase(), "GET") + .header(HeaderNames.ACCESS_CONTROL_REQUEST_METHOD.defaultCase(), "GET") .get(); assertThat("Status from missing endpoint request", res.getStatusInfo(), is(Response.Status.NOT_FOUND)); assertThat("With CORS enabled, headers in 404 response", res.getHeaders().keySet(), - hasItem(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase())); + hasItem(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase())); } } diff --git a/microprofile/jwt-auth/src/main/java/io/helidon/microprofile/jwt/auth/JwtAuthProvider.java b/microprofile/jwt-auth/src/main/java/io/helidon/microprofile/jwt/auth/JwtAuthProvider.java index 5578c15dedc..a7e46d22bd5 100644 --- a/microprofile/jwt-auth/src/main/java/io/helidon/microprofile/jwt/auth/JwtAuthProvider.java +++ b/microprofile/jwt-auth/src/main/java/io/helidon/microprofile/jwt/auth/JwtAuthProvider.java @@ -55,7 +55,7 @@ import io.helidon.common.configurable.Resource; import io.helidon.common.pki.Keys; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.security.AuthenticationResponse; import io.helidon.security.EndpointConfig; import io.helidon.security.Grant; @@ -116,13 +116,13 @@ public class JwtAuthProvider implements AuthenticationProvider, OutboundSecurity /** * Configuration of Cookie property name which contains JWT token. * - * This will be ignored unless {@link #CONFIG_JWT_HEADER} is set to {@link io.helidon.http.Http.HeaderNames#COOKIE}. + * This will be ignored unless {@link #CONFIG_JWT_HEADER} is set to {@link io.helidon.http.HeaderNames#COOKIE}. */ private static final String CONFIG_COOKIE_PROPERTY_NAME = "mp.jwt.token.cookie"; /** * Configuration of the header where the JWT token is set. * - * Default value is {@link io.helidon.http.Http.HeaderNames#AUTHORIZATION}. + * Default value is {@link io.helidon.http.HeaderNames#AUTHORIZATION}. */ private static final String CONFIG_JWT_HEADER = "mp.jwt.token.header"; private static final System.Logger LOGGER = System.getLogger(JwtAuthProvider.class.getName()); @@ -312,7 +312,7 @@ AuthenticationResponse authenticate(ProviderRequest providerRequest, LoginConfig } private Optional findCookie(Map> headers) { - List cookies = headers.get(Http.HeaderNames.COOKIE.defaultCase()); + List cookies = headers.get(HeaderNames.COOKIE.defaultCase()); if ((null == cookies) || cookies.isEmpty()) { return Optional.empty(); } @@ -1151,7 +1151,7 @@ public Builder config(Config config) { * @return updated builder instance */ public Builder jwtHeader(String header) { - if (Http.HeaderNames.COOKIE.defaultCase().equalsIgnoreCase(header)) { + if (HeaderNames.COOKIE.defaultCase().equalsIgnoreCase(header)) { useCookie = true; } else { useCookie = false; diff --git a/microprofile/lra/jax-rs/src/main/java/io/helidon/microprofile/lra/NonJaxRsResource.java b/microprofile/lra/jax-rs/src/main/java/io/helidon/microprofile/lra/NonJaxRsResource.java index 233d2a708b6..d896a2ba539 100644 --- a/microprofile/lra/jax-rs/src/main/java/io/helidon/microprofile/lra/NonJaxRsResource.java +++ b/microprofile/lra/jax-rs/src/main/java/io/helidon/microprofile/lra/NonJaxRsResource.java @@ -24,11 +24,11 @@ import io.helidon.common.Reflected; import io.helidon.common.parameters.Parameters; import io.helidon.config.Config; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.http.HttpPrologue; import io.helidon.http.ServerRequestHeaders; +import io.helidon.http.Status; import io.helidon.lra.coordinator.client.PropagatedHeaders; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -147,12 +147,12 @@ private void handleRequest(ServerRequest req, // to a @Compensate or @Complete method invocation // then it MAY report 410 Gone HTTP status code // or in the case of non-JAX-RS method returning ParticipantStatus null. - () -> res.status(Http.Status.GONE_410).send()); + () -> res.status(Status.GONE_410).send()); } default -> { LOGGER.log(Level.ERROR, "Unexpected non Jax-Rs LRA compensation type " + type + ": " + req.path().absolute().path()); - res.status(Http.Status.NOT_FOUND_404).send(); + res.status(Status.NOT_FOUND_404).send(); } } } @@ -182,7 +182,7 @@ private void sendResult(ServerResponse res, Object result) { } private void sendResponse(ServerResponse res, Response response) { - res.status(Http.Status.create(response.getStatus())); + res.status(Status.create(response.getStatus())); response.getHeaders() .forEach((k, values) -> res.header(HeaderNames.create(k), values.stream() diff --git a/microprofile/lra/jax-rs/src/test/java/io/helidon/microprofile/lra/CoordinatorHeaderPropagationTest.java b/microprofile/lra/jax-rs/src/test/java/io/helidon/microprofile/lra/CoordinatorHeaderPropagationTest.java index b87edb5a505..2f2e54ad99f 100644 --- a/microprofile/lra/jax-rs/src/test/java/io/helidon/microprofile/lra/CoordinatorHeaderPropagationTest.java +++ b/microprofile/lra/jax-rs/src/test/java/io/helidon/microprofile/lra/CoordinatorHeaderPropagationTest.java @@ -30,7 +30,10 @@ import java.util.stream.Stream; import io.helidon.common.context.Contexts; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.lra.coordinator.client.CoordinatorClient; import io.helidon.lra.coordinator.client.PropagatedHeaders; import io.helidon.microprofile.config.ConfigCdiExtension; @@ -105,7 +108,7 @@ class CoordinatorHeaderPropagationTest { private static final String PROPAGATED_HEADER = "xxx-tmm-propagated-header"; private static final String EXTRA_COORDINATOR_PROPAGATED_HEADER = "xBb-tmm-extra-start-header"; private static final String NOT_PROPAGATED_HEADER = "non-propagated-header"; - private static final Http.HeaderName LRA_HTTP_CONTEXT_HEADER_NAME = Http.HeaderNames.create(LRA_HTTP_CONTEXT_HEADER); + private static final HeaderName LRA_HTTP_CONTEXT_HEADER_NAME = HeaderNames.create(LRA_HTTP_CONTEXT_HEADER); private static volatile int port = -1; @@ -143,7 +146,7 @@ HttpService mockCoordinator() { lraMap.put(lraId, new ConcurrentHashMap<>()); - res.status(Http.Status.CREATED_201) + res.status(Status.CREATED_201) .header(LRA_HTTP_CONTEXT_HEADER_NAME, lraId) .header(NOT_PROPAGATED_HEADER, "not this extra one!") .header(EXTRA_COORDINATOR_PROPAGATED_HEADER, "yes extra start header!") @@ -165,14 +168,14 @@ HttpService mockCoordinator() { try (Http1ClientResponse clientResponse = Http1Client.builder() .baseUri(lraMap.get(lraId).get("after").toASCIIString()) .build() - .method(Http.Method.PUT) + .method(Method.PUT) .header(LRA_HTTP_CONTEXT_HEADER_NAME, lraId) .headers(reqHeaders -> { // relay all incoming headers req.headers().forEach(reqHeaders::add); }) .submit(LRAStatus.Closing.name())) { - if (clientResponse.status().family() != Http.Status.Family.SUCCESSFUL) { + if (clientResponse.status().family() != Status.Family.SUCCESSFUL) { res.status(clientResponse.status()); } res.send(); @@ -187,14 +190,14 @@ HttpService mockCoordinator() { try (Http1ClientResponse clientResponse = Http1Client.builder() .baseUri(lraMap.get(lraId).get("complete").toASCIIString()) .build() - .method(Http.Method.PUT) + .method(Method.PUT) .header(LRA_HTTP_CONTEXT_HEADER_NAME, lraId) .headers(reqHeaders -> { // relay all incoming headers req.headers().forEach(reqHeaders::add); }) .request()) { - if (clientResponse.status().family() != Http.Status.Family.SUCCESSFUL) { + if (clientResponse.status().family() != Status.Family.SUCCESSFUL) { res.status(clientResponse.status()); } res.send(); @@ -209,14 +212,14 @@ HttpService mockCoordinator() { try (Http1ClientResponse clientResponse = Http1Client.builder() .baseUri(lraMap.get(lraId).get("compensate").toASCIIString()) .build() - .method(Http.Method.PUT) + .method(Method.PUT) .header(LRA_HTTP_CONTEXT_HEADER_NAME, lraId) .headers(reqHeaders -> { // relay all incoming headers req.headers().forEach(reqHeaders::add); }) .request()) { - if (clientResponse.status().family() != Http.Status.Family.SUCCESSFUL) { + if (clientResponse.status().family() != Status.Family.SUCCESSFUL) { res.status(clientResponse.status()); } res.send(); diff --git a/microprofile/lra/jax-rs/src/test/java/io/helidon/microprofile/lra/ParticipantTest.java b/microprofile/lra/jax-rs/src/test/java/io/helidon/microprofile/lra/ParticipantTest.java index cb167d6f6c7..9eaf4349332 100644 --- a/microprofile/lra/jax-rs/src/test/java/io/helidon/microprofile/lra/ParticipantTest.java +++ b/microprofile/lra/jax-rs/src/test/java/io/helidon/microprofile/lra/ParticipantTest.java @@ -24,7 +24,7 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.lra.coordinator.client.CoordinatorClient; import io.helidon.microprofile.config.ConfigCdiExtension; import io.helidon.microprofile.lra.resources.DontEnd; @@ -102,7 +102,7 @@ HttpService mockCoordinator() { return rules -> rules .post("/start", (req, res) -> { String lraId = URI.create("http://localhost:" + port + "/lra-coordinator/xxx-xxx-001").toASCIIString(); - res.status(Http.Status.CREATED_201) + res.status(Status.CREATED_201) .header(LRA_HTTP_CONTEXT_HEADER, lraId) .send(); }) diff --git a/microprofile/metrics/src/test/java/io/helidon/microprofile/metrics/TestBasicPerformanceIndicators.java b/microprofile/metrics/src/test/java/io/helidon/microprofile/metrics/TestBasicPerformanceIndicators.java index edf9210499f..364dc13833c 100644 --- a/microprofile/metrics/src/test/java/io/helidon/microprofile/metrics/TestBasicPerformanceIndicators.java +++ b/microprofile/metrics/src/test/java/io/helidon/microprofile/metrics/TestBasicPerformanceIndicators.java @@ -15,7 +15,7 @@ */ package io.helidon.microprofile.metrics; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.microprofile.tests.junit5.AddConfig; import io.helidon.microprofile.tests.junit5.HelidonTest; @@ -53,7 +53,7 @@ static void doCheckMetricsVendorURL(WebTarget webTarget) { .accept(MediaType.APPLICATION_JSON_TYPE) .get(); - assertThat("Metrics /metrics/vendor URL HTTP status", response.getStatus(), is(Http.Status.OK_200.code())); + assertThat("Metrics /metrics/vendor URL HTTP status", response.getStatus(), is(Status.OK_200.code())); JsonObject vendorMetrics = response.readEntity(JsonObject.class); diff --git a/microprofile/metrics/src/test/java/io/helidon/microprofile/metrics/TestMetricsOnOwnSocket.java b/microprofile/metrics/src/test/java/io/helidon/microprofile/metrics/TestMetricsOnOwnSocket.java index 5ea345112a3..df28f857b4f 100644 --- a/microprofile/metrics/src/test/java/io/helidon/microprofile/metrics/TestMetricsOnOwnSocket.java +++ b/microprofile/metrics/src/test/java/io/helidon/microprofile/metrics/TestMetricsOnOwnSocket.java @@ -15,7 +15,7 @@ */ package io.helidon.microprofile.metrics; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.microprofile.server.ServerCdiExtension; import io.helidon.microprofile.tests.junit5.AddConfig; import io.helidon.microprofile.tests.junit5.HelidonTest; @@ -89,7 +89,7 @@ void checkMessageFromDefaultRouting() { .request(MediaType.TEXT_PLAIN_TYPE) .get()) { - assertThat("Response code getting greeting", r.getStatus(), is(Http.Status.OK_200.code())); + assertThat("Response code getting greeting", r.getStatus(), is(Status.OK_200.code())); } } @@ -103,7 +103,7 @@ void checkMetricsAfterGet() { private int getRequestsLoadCount(String descr) { try (Response r = metricsInvocation().invoke()) { - assertThat(descr + " metrics sampling response", r.getStatus(), is(Http.Status.OK_200.code())); + assertThat(descr + " metrics sampling response", r.getStatus(), is(Status.OK_200.code())); JsonObject metrics = r.readEntity(JsonObject.class); assertThat("Check for requests.load", metrics.containsKey("requests.load"), is(true)); diff --git a/microprofile/openapi/src/test/java/io/helidon/microprofile/openapi/BasicServerTest.java b/microprofile/openapi/src/test/java/io/helidon/microprofile/openapi/BasicServerTest.java index 85fee1eccd3..86345802f00 100644 --- a/microprofile/openapi/src/test/java/io/helidon/microprofile/openapi/BasicServerTest.java +++ b/microprofile/openapi/src/test/java/io/helidon/microprofile/openapi/BasicServerTest.java @@ -17,7 +17,7 @@ import java.util.Map; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.microprofile.tests.junit5.AddBean; import io.helidon.microprofile.tests.junit5.HelidonTest; import io.helidon.openapi.OpenApiFeature; @@ -52,7 +52,7 @@ private static Map retrieveYaml(WebTarget webTarget) { .request(OpenApiFeature.DEFAULT_RESPONSE_MEDIA_TYPE.text()) .get()) { assertThat("Fetch of OpenAPI document from server status", response.getStatus(), - is(equalTo(Http.Status.OK_200.code()))); + is(equalTo(Status.OK_200.code()))); String yamlText = response.readEntity(String.class); return new Yaml().load(yamlText); } diff --git a/microprofile/server/src/main/java/io/helidon/microprofile/server/JaxRsService.java b/microprofile/server/src/main/java/io/helidon/microprofile/server/JaxRsService.java index 736fb8b6450..851a5de6c9a 100644 --- a/microprofile/server/src/main/java/io/helidon/microprofile/server/JaxRsService.java +++ b/microprofile/server/src/main/java/io/helidon/microprofile/server/JaxRsService.java @@ -35,10 +35,11 @@ import io.helidon.common.context.Context; import io.helidon.common.context.Contexts; import io.helidon.common.uri.UriPath; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.InternalServerException; +import io.helidon.http.Status; import io.helidon.microprofile.server.HelidonHK2InjectionManagerFactory.InjectionManagerWrapper; import io.helidon.webserver.KeyPerformanceIndicatorSupport; import io.helidon.webserver.http.HttpRules; @@ -333,16 +334,16 @@ public OutputStream writeResponseStatusAndHeaders(long contentLengthParam, String name = entry.getKey(); List values = entry.getValue(); if (values.size() == 1) { - res.header(Http.Headers.create(HeaderNames.create(name), values.get(0))); + res.header(HeaderValues.create(HeaderNames.create(name), values.get(0))); } else { - res.header(Http.Headers.create(entry.getKey(), entry.getValue())); + res.header(HeaderValues.create(entry.getKey(), entry.getValue())); } } Response.StatusType statusInfo = containerResponse.getStatusInfo(); - res.status(Http.Status.create(statusInfo.getStatusCode(), statusInfo.getReasonPhrase())); + res.status(Status.create(statusInfo.getStatusCode(), statusInfo.getReasonPhrase())); if (contentLength > 0) { - res.header(Http.Headers.create(HeaderNames.CONTENT_LENGTH, String.valueOf(contentLength))); + res.header(HeaderValues.create(HeaderNames.CONTENT_LENGTH, String.valueOf(contentLength))); } this.outputStream = new NoFlushOutputStream(res.outputStream()); return outputStream; diff --git a/microprofile/server/src/main/java/io/helidon/microprofile/server/ServerCdiExtension.java b/microprofile/server/src/main/java/io/helidon/microprofile/server/ServerCdiExtension.java index eff1d827033..e220691799b 100644 --- a/microprofile/server/src/main/java/io/helidon/microprofile/server/ServerCdiExtension.java +++ b/microprofile/server/src/main/java/io/helidon/microprofile/server/ServerCdiExtension.java @@ -37,7 +37,8 @@ import io.helidon.common.context.Contexts; import io.helidon.config.Config; import io.helidon.config.mp.Prioritized; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.microprofile.cdi.RuntimeStart; import io.helidon.webserver.KeyPerformanceIndicatorSupport; import io.helidon.webserver.ListenerConfig; @@ -481,8 +482,8 @@ private void registerDefaultRedirect() { Optional.ofNullable(basePath) .or(() -> config.get("server.base-path").asString().asOptional()) .ifPresent(basePath -> routingBuilder.any("/", (req, res) -> { - res.status(Http.Status.MOVED_PERMANENTLY_301); - res.headers().set(Http.HeaderNames.LOCATION, basePath); + res.status(Status.MOVED_PERMANENTLY_301); + res.headers().set(HeaderNames.LOCATION, basePath); res.send(); })); STARTUP_LOGGER.log(Level.TRACE, "Builders ready"); diff --git a/microprofile/server/src/test/java/io/helidon/microprofile/server/ProducedRouteTest.java b/microprofile/server/src/test/java/io/helidon/microprofile/server/ProducedRouteTest.java index d0e29496b70..dcc493986ce 100644 --- a/microprofile/server/src/test/java/io/helidon/microprofile/server/ProducedRouteTest.java +++ b/microprofile/server/src/test/java/io/helidon/microprofile/server/ProducedRouteTest.java @@ -20,8 +20,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.microprofile.tests.junit5.AddBean; import io.helidon.microprofile.tests.junit5.AddConfig; import io.helidon.microprofile.tests.junit5.AddExtension; @@ -66,13 +66,13 @@ public class ProducedRouteTest { static final String UNFILTERED_PATH = "/unfiltered"; static final String COOL_HEADER = "Cool-Header"; - static final HeaderName COOL_HEADER_NAME = Http.HeaderNames.create(COOL_HEADER); + static final HeaderName COOL_HEADER_NAME = HeaderNames.create(COOL_HEADER); static final String COOL_VALUE = "cool value"; static final String COOLER_HEADER = "Cooler-Header"; - static final HeaderName COOLER_HEADER_NAME = Http.HeaderNames.create(COOLER_HEADER); + static final HeaderName COOLER_HEADER_NAME = HeaderNames.create(COOLER_HEADER); static final String COOLER_VALUE = "cooler value"; static final String COOLEST_HEADER = "Coolest-Header"; - static final HeaderName COOLEST_HEADER_NAME = Http.HeaderNames.create(COOLEST_HEADER); + static final HeaderName COOLEST_HEADER_NAME = HeaderNames.create(COOLEST_HEADER); static final String COOLEST_VALUE = "coolest value"; @Test diff --git a/microprofile/tests/server/src/test/resources/application.yaml b/microprofile/tests/server/src/test/resources/application.yaml index 3620ad340a9..197d7d04253 100644 --- a/microprofile/tests/server/src/test/resources/application.yaml +++ b/microprofile/tests/server/src/test/resources/application.yaml @@ -14,6 +14,8 @@ # limitations under the License. # +server: + port: 0 mp.initializer: allow: true no-warn: true \ No newline at end of file diff --git a/microprofile/websocket/src/main/java/io/helidon/microprofile/tyrus/TyrusConnection.java b/microprofile/websocket/src/main/java/io/helidon/microprofile/tyrus/TyrusConnection.java index f754ca29b4a..0482f286b19 100644 --- a/microprofile/websocket/src/main/java/io/helidon/microprofile/tyrus/TyrusConnection.java +++ b/microprofile/websocket/src/main/java/io/helidon/microprofile/tyrus/TyrusConnection.java @@ -25,7 +25,7 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.buffers.DataReader; -import io.helidon.http.Http; +import io.helidon.http.DateTime; import io.helidon.webserver.ConnectionContext; import io.helidon.webserver.spi.ServerConnection; import io.helidon.websocket.WsCloseCodes; @@ -62,7 +62,7 @@ class TyrusConnection implements ServerConnection, WsSession { this.ctx = ctx; this.upgradeInfo = upgradeInfo; this.listener = new TyrusListener(); - this.lastRequestTimestamp = Http.DateTime.timestamp(); + this.lastRequestTimestamp = DateTime.timestamp(); } @Override @@ -77,9 +77,9 @@ public void handle(Semaphore requestSemaphore) { readingNetwork = true; BufferData buffer = dataReader.readBuffer(); readingNetwork = false; - lastRequestTimestamp = Http.DateTime.timestamp(); + lastRequestTimestamp = DateTime.timestamp(); listener.onMessage(this, buffer, true); - lastRequestTimestamp = Http.DateTime.timestamp(); + lastRequestTimestamp = DateTime.timestamp(); } catch (Exception e) { listener.onError(this, e); listener.onClose(this, WsCloseCodes.UNEXPECTED_CONDITION, e.getMessage()); @@ -132,7 +132,7 @@ public Optional subProtocol() { @Override public Duration idleTime() { - return Duration.between(lastRequestTimestamp, Http.DateTime.timestamp()); + return Duration.between(lastRequestTimestamp, DateTime.timestamp()); } @Override diff --git a/microprofile/websocket/src/main/java/io/helidon/microprofile/tyrus/TyrusUpgrader.java b/microprofile/websocket/src/main/java/io/helidon/microprofile/tyrus/TyrusUpgrader.java index c053214ec16..13c73d8192a 100644 --- a/microprofile/websocket/src/main/java/io/helidon/microprofile/tyrus/TyrusUpgrader.java +++ b/microprofile/websocket/src/main/java/io/helidon/microprofile/tyrus/TyrusUpgrader.java @@ -33,7 +33,8 @@ import io.helidon.common.buffers.DataWriter; import io.helidon.common.uri.UriQuery; import io.helidon.http.DirectHandler; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.HttpPrologue; import io.helidon.http.RequestException; import io.helidon.http.WritableHeaders; @@ -123,8 +124,8 @@ public ServerConnection upgrade(ConnectionContext ctx, HttpPrologue prologue, Wr // Validate origin if (!anyOrigin()) { - if (headers.contains(Http.HeaderNames.ORIGIN)) { - String origin = headers.get(Http.HeaderNames.ORIGIN).value(); + if (headers.contains(HeaderNames.ORIGIN)) { + String origin = headers.get(HeaderNames.ORIGIN).value(); if (!origins().contains(origin)) { throw RequestException.builder() .message("Invalid Origin") @@ -229,8 +230,8 @@ WebSocketEngine.UpgradeInfo protocolHandshake(WritableHeaders headers, UriQue // Map Tyrus response headers back to Helidon upgradeResponse.getHeaders() .forEach((key, value) -> headers.add( - Http.Headers.create( - Http.HeaderNames.create(key, key.toLowerCase(Locale.ROOT)), + HeaderValues.create( + HeaderNames.create(key, key.toLowerCase(Locale.ROOT)), value))); return upgradeInfo; } diff --git a/openapi/src/main/java/io/helidon/openapi/OpenApiFeature.java b/openapi/src/main/java/io/helidon/openapi/OpenApiFeature.java index 5db9141130e..4a776b0a5cd 100644 --- a/openapi/src/main/java/io/helidon/openapi/OpenApiFeature.java +++ b/openapi/src/main/java/io/helidon/openapi/OpenApiFeature.java @@ -38,9 +38,10 @@ import io.helidon.common.media.type.MediaTypes; import io.helidon.config.Config; import io.helidon.config.metadata.ConfiguredOption; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.http.HttpMediaType; import io.helidon.http.ServerRequestHeaders; +import io.helidon.http.Status; import io.helidon.http.WritableHeaders; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; @@ -319,11 +320,11 @@ && uiSupportsMediaType(requestedMediaType.get())) { MediaType resultMediaType = requestedMediaType.get(); final String openAPIDocument = prepareDocument(resultMediaType); - resp.status(Http.Status.OK_200); + resp.status(Status.OK_200); resp.headers().contentType(resultMediaType); resp.send(openAPIDocument); } catch (Exception ex) { - resp.status(Http.Status.INTERNAL_SERVER_ERROR_500); + resp.status(Status.INTERNAL_SERVER_ERROR_500); resp.send("Error serializing OpenAPI document; " + ex.getMessage()); logger().log(System.Logger.Level.ERROR, "Error serializing OpenAPI document", ex); } @@ -391,7 +392,7 @@ private Optional chooseResponseMediaType(ServerRequest req) { ServerRequestHeaders headersToCheck = req.headers(); if (headersToCheck.acceptedTypes().isEmpty()) { WritableHeaders writableHeaders = WritableHeaders.create(headersToCheck); - writableHeaders.add(Http.HeaderNames.ACCEPT, DEFAULT_RESPONSE_MEDIA_TYPE.toString()); + writableHeaders.add(HeaderNames.ACCEPT, DEFAULT_RESPONSE_MEDIA_TYPE.toString()); headersToCheck = ServerRequestHeaders.create(writableHeaders); } return headersToCheck diff --git a/openapi/src/main/java/io/helidon/openapi/OpenApiUiBase.java b/openapi/src/main/java/io/helidon/openapi/OpenApiUiBase.java index a4533b61022..637f8b56bf7 100644 --- a/openapi/src/main/java/io/helidon/openapi/OpenApiUiBase.java +++ b/openapi/src/main/java/io/helidon/openapi/OpenApiUiBase.java @@ -28,8 +28,9 @@ import io.helidon.common.media.type.MediaType; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.uri.UriQuery; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.http.HttpMediaType; +import io.helidon.http.Status; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -139,11 +140,11 @@ protected Map options() { protected boolean sendStaticText(ServerRequest request, ServerResponse response, HttpMediaType mediaType) { try { response - .header(Http.HeaderNames.CONTENT_TYPE, mediaType.toString()) + .header(HeaderNames.CONTENT_TYPE, mediaType.toString()) .send(prepareDocument(request.query(), mediaType)); } catch (IOException e) { LOGGER.log(System.Logger.Level.WARNING, "Error formatting OpenAPI output as " + mediaType, e); - response.status(Http.Status.INTERNAL_SERVER_ERROR_500) + response.status(Status.INTERNAL_SERVER_ERROR_500) .send("Error formatting OpenAPI output. See server log."); } return true; diff --git a/openapi/src/test/java/io/helidon/openapi/TestUtil.java b/openapi/src/test/java/io/helidon/openapi/TestUtil.java index 9216eb0156a..c9d7965cfd7 100644 --- a/openapi/src/test/java/io/helidon/openapi/TestUtil.java +++ b/openapi/src/test/java/io/helidon/openapi/TestUtil.java @@ -28,12 +28,12 @@ import java.util.logging.Level; import java.util.logging.Logger; -import io.helidon.http.Http; -import io.helidon.http.HttpMediaType; import io.helidon.common.media.type.MediaType; import io.helidon.common.media.type.MediaTypes; import io.helidon.config.Config; import io.helidon.config.ConfigSources; +import io.helidon.http.HttpMediaType; +import io.helidon.http.Status; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.HttpRouting; @@ -261,7 +261,7 @@ public static HttpMediaType validateResponseMediaType( HttpURLConnection cnx, MediaType expectedMediaType) throws Exception { assertThat("Unexpected response code", cnx.getResponseCode(), - is(Http.Status.OK_200.code())); + is(Status.OK_200.code())); HttpMediaType expectedMT = expectedMediaType != null ? HttpMediaType.create(expectedMediaType) : HttpMediaType.create(OpenApiFeature.DEFAULT_RESPONSE_MEDIA_TYPE); diff --git a/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsMtRoleMapperProvider.java b/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsMtRoleMapperProvider.java index c9925f2891c..dd152a6e163 100644 --- a/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsMtRoleMapperProvider.java +++ b/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsMtRoleMapperProvider.java @@ -29,7 +29,7 @@ import io.helidon.config.Config; import io.helidon.config.metadata.Configured; import io.helidon.config.metadata.ConfiguredOption; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.security.AuthenticationResponse; import io.helidon.security.Grant; import io.helidon.security.ProviderRequest; @@ -257,7 +257,7 @@ protected List getGrantsFromServer(String idcsTenantId, .post() .uri(multitenantEndpoints.assertEndpoint(idcsTenantId)) .headers(it -> { - it.add(Http.HeaderNames.AUTHORIZATION, "Bearer " + appToken); + it.add(HeaderNames.AUTHORIZATION, "Bearer " + appToken); }); return processRoleRequest(post, requestBuilder.build(), subjectName); diff --git a/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsRoleMapperProvider.java b/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsRoleMapperProvider.java index f4fc9467090..1f06513315e 100644 --- a/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsRoleMapperProvider.java +++ b/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsRoleMapperProvider.java @@ -26,7 +26,7 @@ import io.helidon.config.Config; import io.helidon.config.metadata.Configured; import io.helidon.config.metadata.ConfiguredOption; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.security.AuthenticationResponse; import io.helidon.security.Grant; import io.helidon.security.ProviderRequest; @@ -196,7 +196,7 @@ private List obtainGrantsFromServer(String subjectName, String .post() .uri(asserterUri) .headers(it -> { - it.add(Http.HeaderNames.AUTHORIZATION, "Bearer " + appToken); + it.add(HeaderNames.AUTHORIZATION, "Bearer " + appToken); }); return processRoleRequest(request, requestBuilder.build(), subjectName); diff --git a/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsRoleMapperProviderBase.java b/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsRoleMapperProviderBase.java index 58687d7ac90..fc2347a8eab 100644 --- a/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsRoleMapperProviderBase.java +++ b/security/providers/idcs-mapper/src/main/java/io/helidon/security/providers/idcs/mapper/IdcsRoleMapperProviderBase.java @@ -34,7 +34,8 @@ import io.helidon.config.Config; import io.helidon.config.metadata.Configured; import io.helidon.config.metadata.ConfiguredOption; -import io.helidon.http.Http; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.security.AuthenticationResponse; import io.helidon.security.Grant; import io.helidon.security.ProviderRequest; @@ -173,7 +174,7 @@ protected Subject buildSubject(Subject originalSubject, List gr protected List processRoleRequest(HttpClientRequest request, Object entity, String subjectName) { try (HttpClientResponse response = request.submit(entity)) { - if (response.status().family() == Http.Status.Family.SUCCESSFUL) { + if (response.status().family() == Status.Family.SUCCESSFUL) { try { JsonObject jsonObject = response.as(JsonObject.class); return processServerResponse(jsonObject, subjectName); @@ -189,7 +190,7 @@ protected List processRoleRequest(HttpClientRequest request, Ob message = response.as(String.class); LOGGER.log(Level.WARNING, "Cannot read groups for user \"" + subjectName + "\". " + "Response code: " + response.status() - + (response.status() == Http.Status.UNAUTHORIZED_401 ? ", make sure your IDCS client has role " + + (response.status() == Status.UNAUTHORIZED_401 ? ", make sure your IDCS client has role " + "\"Authenticator Client\" added on the client configuration page" : "") + ", error entity: " + message); } catch (Exception e) { @@ -450,10 +451,10 @@ private AppTokenData fromServer(RoleMapTracing tracing) { HttpClientRequest request = webClient.post() .uri(tokenEndpointUri) - .header(Http.Headers.ACCEPT_JSON); + .header(HeaderValues.ACCEPT_JSON); try (HttpClientResponse response = request.submit(params)) { - if (response.status().family() == Http.Status.Family.SUCCESSFUL) { + if (response.status().family() == Status.Family.SUCCESSFUL) { try { JsonObject jsonObject = response.as(JsonObject.class); String accessToken = jsonObject.getString(ACCESS_TOKEN_KEY); diff --git a/security/providers/oidc-common/src/main/java/io/helidon/security/providers/oidc/common/IdcsSupport.java b/security/providers/oidc-common/src/main/java/io/helidon/security/providers/oidc/common/IdcsSupport.java index e2954a662f3..576f8e278d9 100644 --- a/security/providers/oidc-common/src/main/java/io/helidon/security/providers/oidc/common/IdcsSupport.java +++ b/security/providers/oidc-common/src/main/java/io/helidon/security/providers/oidc/common/IdcsSupport.java @@ -20,7 +20,9 @@ import java.time.Duration; import io.helidon.common.parameters.Parameters; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.security.SecurityException; import io.helidon.security.jwt.jwk.JwkKeys; import io.helidon.webclient.api.HttpClientResponse; @@ -50,10 +52,10 @@ static JwkKeys signJwk(WebClient appWebClient, try (HttpClientResponse response = appWebClient.post() .uri(tokenEndpointUri) - .header(Http.Headers.ACCEPT_JSON) + .header(HeaderValues.ACCEPT_JSON) .submit(form)) { - if (response.status().family() == Http.Status.Family.SUCCESSFUL) { + if (response.status().family() == Status.Family.SUCCESSFUL) { JsonObject json = response.as(JsonObject.class); String accessToken = json.getString("access_token"); @@ -61,7 +63,7 @@ static JwkKeys signJwk(WebClient appWebClient, // get the jwk from server JsonObject jwkJson = generalClient.get() .uri(signJwkUri) - .header(Http.HeaderNames.AUTHORIZATION, "Bearer " + accessToken) + .header(HeaderNames.AUTHORIZATION, "Bearer " + accessToken) .requestEntity(JsonObject.class); return JwkKeys.create(jwkJson); diff --git a/security/providers/oidc-common/src/test/java/io/helidon/security/providers/oidc/common/OidcConfigFromBuilderTest.java b/security/providers/oidc-common/src/test/java/io/helidon/security/providers/oidc/common/OidcConfigFromBuilderTest.java index 4d2e97177d9..fdefb53ae39 100644 --- a/security/providers/oidc-common/src/test/java/io/helidon/security/providers/oidc/common/OidcConfigFromBuilderTest.java +++ b/security/providers/oidc-common/src/test/java/io/helidon/security/providers/oidc/common/OidcConfigFromBuilderTest.java @@ -16,9 +16,14 @@ package io.helidon.security.providers.oidc.common; -import io.helidon.http.Http; +import java.net.URI; +import java.time.Duration; +import java.util.Arrays; +import java.util.Map; + import io.helidon.config.Config; import io.helidon.config.ConfigSources; +import io.helidon.http.Status; import io.helidon.webserver.WebServer; import org.junit.jupiter.api.Test; @@ -44,11 +49,6 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertAll; -import java.net.URI; -import java.time.Duration; -import java.util.Arrays; -import java.util.Map; - /** * Unit test for {@link OidcConfig}. */ @@ -136,11 +136,11 @@ void testRequestUrisWithProxy() { String reqUri = req.requestedUri().toUri().toASCIIString(); if (!relativeUris[0] && !reqUri.startsWith("http://localhost")) { // Simulate a failed Identity response if relativeURIs=false but the request URI is relative - res.status(Http.Status.INTERNAL_SERVER_ERROR_500); + res.status(Status.INTERNAL_SERVER_ERROR_500); res.send("URI must be absolute"); } else if (relativeUris[0] && reqUri.startsWith("http://localhost")) { // Simulate a failed Identity response if relativeURIs=true but the request URI is absolute - res.status(Http.Status.INTERNAL_SERVER_ERROR_500); + res.status(Status.INTERNAL_SERVER_ERROR_500); res.send("URI must be relative"); } else { // Simulate a successful Identity response diff --git a/security/providers/oidc/src/main/java/io/helidon/security/providers/oidc/OidcFeature.java b/security/providers/oidc/src/main/java/io/helidon/security/providers/oidc/OidcFeature.java index 480a5e081ea..ce8da550c06 100644 --- a/security/providers/oidc/src/main/java/io/helidon/security/providers/oidc/OidcFeature.java +++ b/security/providers/oidc/src/main/java/io/helidon/security/providers/oidc/OidcFeature.java @@ -39,9 +39,11 @@ import io.helidon.common.parameters.Parameters; import io.helidon.config.Config; import io.helidon.cors.CrossOriginConfig; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.ServerRequestHeaders; import io.helidon.http.ServerResponseHeaders; +import io.helidon.http.Status; import io.helidon.security.Security; import io.helidon.security.SecurityException; import io.helidon.security.providers.oidc.common.OidcConfig; @@ -62,7 +64,7 @@ import jakarta.json.JsonObject; -import static io.helidon.http.Http.HeaderNames.HOST; +import static io.helidon.http.HeaderNames.HOST; import static io.helidon.security.providers.oidc.common.spi.TenantConfigFinder.DEFAULT_TENANT_ID; /** @@ -298,7 +300,7 @@ private void logoutWithTenant(ServerRequest req, ServerResponse res, Tenant tena if (idTokenCookie.isEmpty()) { LOGGER.log(Level.TRACE, "Logout request invoked without ID Token cookie"); - res.status(Http.Status.FORBIDDEN_403) + res.status(Status.FORBIDDEN_403) .send(); return; } @@ -320,8 +322,8 @@ private void logoutWithTenant(ServerRequest req, ServerResponse res, Tenant tena headers.addCookie(idTokenCookieHandler.removeCookie().build()); headers.addCookie(tenantCookieHandler.removeCookie().build()); - res.status(Http.Status.TEMPORARY_REDIRECT_307) - .header(Http.HeaderNames.LOCATION, sb.toString()) + res.status(Status.TEMPORARY_REDIRECT_307) + .header(HeaderNames.LOCATION, sb.toString()) .send(); } catch (Exception e) { sendError(res, e); @@ -380,12 +382,12 @@ private void processCodeWithTenant(String code, ServerRequest req, ServerRespons HttpClientRequest post = webClient.post() .uri(tenant.tokenEndpointUri()) - .header(Http.Headers.ACCEPT_JSON); + .header(HeaderValues.ACCEPT_JSON); OidcUtil.updateRequest(OidcConfig.RequestType.CODE_TO_TOKEN, tenantConfig, form); try (HttpClientResponse response = post.submit(form.build())) { - if (response.status().family() == Http.Status.Family.SUCCESSFUL) { + if (response.status().family() == Status.Family.SUCCESSFUL) { try { JsonObject jsonObject = response.as(JsonObject.class); processJsonResponse(req, res, jsonObject, tenantName); @@ -453,7 +455,7 @@ private String processJsonResponse(ServerRequest req, //redirect to "state" String state = req.query().first(STATE_PARAM_NAME).orElse(DEFAULT_REDIRECT); - res.status(Http.Status.TEMPORARY_REDIRECT_307); + res.status(Status.TEMPORARY_REDIRECT_307); if (oidcConfig.useParam()) { state += (state.contains("?") ? "&" : "?") + oidcConfig.paramName() + "=" + tokenValue; if (!DEFAULT_TENANT_ID.equals(tenantName)) { @@ -462,7 +464,7 @@ private String processJsonResponse(ServerRequest req, } state = increaseRedirectCounter(state); - res.headers().add(Http.HeaderNames.LOCATION, state); + res.headers().add(HeaderNames.LOCATION, state); if (oidcConfig.useCookie()) { try { @@ -498,11 +500,11 @@ private void sendError(ServerResponse response, Throwable t) { if (LOGGER.isLoggable(Level.TRACE)) { LOGGER.log(Level.TRACE, "Failed to process OIDC request", t); } - response.status(Http.Status.INTERNAL_SERVER_ERROR_500) + response.status(Status.INTERNAL_SERVER_ERROR_500) .send(); } - private Optional processError(ServerResponse serverResponse, Http.Status status, String entity) { + private Optional processError(ServerResponse serverResponse, Status status, String entity) { LOGGER.log(Level.DEBUG, "Invalid token or failed request when connecting to OIDC Token Endpoint. Response: " + entity + ", response status: " + status); @@ -521,7 +523,7 @@ private Optional processError(ServerResponse res, Throwable t, String me // this must always be the same, so clients cannot guess what kind of problem they are facing // if they try to provide wrong data private void sendErrorResponse(ServerResponse serverResponse) { - serverResponse.status(Http.Status.UNAUTHORIZED_401); + serverResponse.status(Status.UNAUTHORIZED_401); serverResponse.send("Not a valid authorization code2"); } @@ -557,7 +559,7 @@ private void processError(ServerRequest req, ServerResponse res) { + " Error description: " + errorDescription); - res.status(Http.Status.BAD_REQUEST_400); + res.status(Status.BAD_REQUEST_400); res.send("{\"error\": \"" + error + "\", \"error_description\": \"" + errorDescription + "\"}"); } diff --git a/security/providers/oidc/src/main/java/io/helidon/security/providers/oidc/TenantAuthenticationHandler.java b/security/providers/oidc/src/main/java/io/helidon/security/providers/oidc/TenantAuthenticationHandler.java index 32749b6de55..f499878c4ad 100644 --- a/security/providers/oidc/src/main/java/io/helidon/security/providers/oidc/TenantAuthenticationHandler.java +++ b/security/providers/oidc/src/main/java/io/helidon/security/providers/oidc/TenantAuthenticationHandler.java @@ -34,8 +34,9 @@ import io.helidon.common.Errors; import io.helidon.common.parameters.Parameters; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.security.AuthenticationResponse; import io.helidon.security.EndpointConfig; import io.helidon.security.Grant; @@ -118,13 +119,13 @@ class TenantAuthenticationHandler { HttpClientRequest post = tenant.appWebClient() .post() .uri(tenant.introspectUri()) - .header(Http.Headers.ACCEPT_JSON) + .header(HeaderValues.ACCEPT_JSON) .headers(it -> it.add(HeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate")); OidcUtil.updateRequest(OidcConfig.RequestType.INTROSPECT_JWT, tenantConfig, form); try (HttpClientResponse response = post.submit(form.build())) { - if (response.status().family() == Http.Status.Family.SUCCESSFUL) { + if (response.status().family() == Status.Family.SUCCESSFUL) { try { JsonObject jsonObject = response.as(JsonObject.class); if (!jsonObject.getBoolean("active")) { @@ -211,7 +212,7 @@ AuthenticationResponse authenticate(String tenantId, ProviderRequest providerReq LOGGER.log(System.Logger.Level.DEBUG, "Invalid token in cookie", e); } return errorResponse(providerRequest, - Http.Status.UNAUTHORIZED_401, + Status.UNAUTHORIZED_401, null, "Invalid token", tenantId); @@ -229,7 +230,7 @@ AuthenticationResponse authenticate(String tenantId, ProviderRequest providerReq } else { LOGGER.log(System.Logger.Level.DEBUG, () -> "Missing token, could not find in either of: " + missingLocations); return errorResponse(providerRequest, - Http.Status.UNAUTHORIZED_401, + Status.UNAUTHORIZED_401, null, "Missing token, could not find in either of: " + missingLocations, @@ -265,7 +266,7 @@ private Set expectedScopes(ProviderRequest request) { } private AuthenticationResponse errorResponse(ProviderRequest providerRequest, - Http.Status status, + Status status, String code, String description, String tenantId) { @@ -319,7 +320,7 @@ private AuthenticationResponse errorResponse(ProviderRequest providerRequest, return AuthenticationResponse .builder() .status(SecurityResponse.SecurityStatus.FAILURE_FINISH) - .statusCode(Http.Status.TEMPORARY_REDIRECT_307.code()) + .statusCode(Status.TEMPORARY_REDIRECT_307.code()) .description("Redirecting to identity server: " + description) .responseHeader("Location", authorizationEndpoint + queryString) .build(); @@ -354,7 +355,7 @@ private AuthenticationResponse failOrAbstain(String message) { } } - private AuthenticationResponse errorResponseNoRedirect(String code, String description, Http.Status status) { + private AuthenticationResponse errorResponseNoRedirect(String code, String description, Status status) { if (optional) { return AuthenticationResponse.builder() .status(SecurityResponse.SecurityStatus.ABSTAIN) @@ -364,7 +365,7 @@ private AuthenticationResponse errorResponseNoRedirect(String code, String descr if (null == code) { return AuthenticationResponse.builder() .status(SecurityResponse.SecurityStatus.FAILURE) - .statusCode(Http.Status.UNAUTHORIZED_401.code()) + .statusCode(Status.UNAUTHORIZED_401.code()) .responseHeader(HeaderNames.WWW_AUTHENTICATE.defaultCase(), "Bearer realm=\"" + tenantConfig.realm() + "\"") .description(description) @@ -466,7 +467,7 @@ private AuthenticationResponse processValidationResult(ProviderRequest providerR return AuthenticationResponse.success(subject); } else { return errorResponse(providerRequest, - Http.Status.FORBIDDEN_403, + Status.FORBIDDEN_403, "insufficient_scope", "Scopes " + missingScopes + " are missing", tenantId); @@ -478,7 +479,7 @@ private AuthenticationResponse processValidationResult(ProviderRequest providerR validationErrors.log(LOGGER); } return errorResponse(providerRequest, - Http.Status.UNAUTHORIZED_401, + Status.UNAUTHORIZED_401, "invalid_token", "Token not valid", tenantId); diff --git a/tests/apps/bookstore/bookstore-se/src/main/java/io/helidon/tests/apps/bookstore/se/BookService.java b/tests/apps/bookstore/bookstore-se/src/main/java/io/helidon/tests/apps/bookstore/se/BookService.java index 75dc5ca748f..607e4bee11d 100644 --- a/tests/apps/bookstore/bookstore-se/src/main/java/io/helidon/tests/apps/bookstore/se/BookService.java +++ b/tests/apps/bookstore/bookstore-se/src/main/java/io/helidon/tests/apps/bookstore/se/BookService.java @@ -19,7 +19,7 @@ import java.util.Collection; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.tests.apps.bookstore.common.Book; import io.helidon.tests.apps.bookstore.common.BookMapper; import io.helidon.tests.apps.bookstore.common.BookStore; @@ -93,10 +93,10 @@ private void postBook(ServerRequest request, ServerResponse response) { private void addBook(Book book, ServerResponse response) { if (BOOK_STORE.contains(book.getIsbn())) { - response.status(Http.Status.CONFLICT_409).send(); + response.status(Status.CONFLICT_409).send(); } else { BOOK_STORE.store(book); - response.status(Http.Status.OK_200).send(); + response.status(Status.OK_200).send(); } } @@ -105,7 +105,7 @@ private void getBook(ServerRequest request, ServerResponse response) { Book book = BOOK_STORE.find(isbn); if (book == null) { - response.status(Http.Status.NOT_FOUND_404).send(); + response.status(Status.NOT_FOUND_404).send(); return; } @@ -141,9 +141,9 @@ private void putBook(ServerRequest request, ServerResponse response) { private void updateBook(Book book, ServerResponse response) { if (BOOK_STORE.contains(book.getIsbn())) { BOOK_STORE.store(book); - response.status(Http.Status.OK_200).send(); + response.status(Status.OK_200).send(); } else { - response.status(Http.Status.NOT_FOUND_404).send(); + response.status(Status.NOT_FOUND_404).send(); } } @@ -153,7 +153,7 @@ private void deleteBook(ServerRequest request, ServerResponse response) { BOOK_STORE.remove(isbn); response.send(); } else { - response.status(Http.Status.NOT_FOUND_404).send(); + response.status(Status.NOT_FOUND_404).send(); } } } diff --git a/tests/functional/bookstore/src/test/java/io/helidon/tests/bookstore/MainTest.java b/tests/functional/bookstore/src/test/java/io/helidon/tests/bookstore/MainTest.java index 34fb2384203..a4ba3ecdb21 100644 --- a/tests/functional/bookstore/src/test/java/io/helidon/tests/bookstore/MainTest.java +++ b/tests/functional/bookstore/src/test/java/io/helidon/tests/bookstore/MainTest.java @@ -31,8 +31,9 @@ import java.util.Objects; import java.util.Queue; -import io.helidon.http.Http; import io.helidon.common.media.type.MediaTypes; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.WebClient; @@ -293,7 +294,7 @@ private void runJsonFunctionalTest(String edition, String jsonLibrary) throws Ex HttpClientResponse response = webClient .post("/books") .submit(json); - assertThat("HTTP response POST", response.status(), is(Http.Status.OK_200)); + assertThat("HTTP response POST", response.status(), is(Status.OK_200)); JsonObject book = webClient .get("/books/123456") @@ -303,12 +304,12 @@ private void runJsonFunctionalTest(String edition, String jsonLibrary) throws Ex response = webClient.get() .path("/books/0000") .request(); - assertThat("HTTP response GET bad ISBN", response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat("HTTP response GET bad ISBN", response.status(), is(Status.NOT_FOUND_404)); response = webClient.delete() .path("/books/123456") .request(); - assertThat("HTTP response DELETE", response.status(), is(Http.Status.OK_200)); + assertThat("HTTP response DELETE", response.status(), is(Status.OK_200)); bookArray = webClient.get() .path("/books") @@ -352,7 +353,7 @@ private void runMetricsAndHealthTest(String edition, String jsonLibrary, boolean String payload = webClient.get() .path("/metrics") - .header(Http.HeaderNames.ACCEPT, MediaTypes.WILDCARD.text()) + .header(HeaderNames.ACCEPT, MediaTypes.WILDCARD.text()) .requestEntity(String.class); assertThat("Making sure we got Prometheus format", payload, anyOf(startsWith("# TYPE"), startsWith("# HELP"))); @@ -362,7 +363,7 @@ private void runMetricsAndHealthTest(String edition, String jsonLibrary, boolean if (!Objects.equals(jsonLibrary, "jackson")) { jsonObject = webClient.get() .path("/metrics") - .header(Http.HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) + .header(HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) .requestEntity(JsonObject.class); String scopeTagName = edition.equals("se") ? "scope" : "mp_scope"; assertThat("Checking request count", @@ -371,7 +372,7 @@ private void runMetricsAndHealthTest(String edition, String jsonLibrary, boolean jsonObject = webClient.get() .path("/health") - .header(Http.HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) + .header(HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) .requestEntity(JsonObject.class); assertThat("Checking health status", jsonObject.getString("status"), is("UP")); if (edition.equals("mp")) { @@ -394,9 +395,9 @@ void routing(String edition) throws Exception { HttpClientResponse response = webClient.get() .path("/badurl") - .header(Http.HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) + .header(HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) .request(); - assertThat("Checking encode URL response", response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat("Checking encode URL response", response.status(), is(Status.NOT_FOUND_404)); } finally { application.stop(); } diff --git a/tests/functional/request-scope/src/main/java/io/helidon/tests/functional/requestscope/TenantContext.java b/tests/functional/request-scope/src/main/java/io/helidon/tests/functional/requestscope/TenantContext.java index 46e2cdf785f..ade90555a6e 100644 --- a/tests/functional/request-scope/src/main/java/io/helidon/tests/functional/requestscope/TenantContext.java +++ b/tests/functional/request-scope/src/main/java/io/helidon/tests/functional/requestscope/TenantContext.java @@ -15,7 +15,8 @@ */ package io.helidon.tests.functional.requestscope; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.webserver.http.ServerRequest; import jakarta.annotation.PostConstruct; @@ -24,7 +25,7 @@ @RequestScoped public class TenantContext { - private static final Http.HeaderName TENANT_ID = Http.HeaderNames.create("x-tenant-id"); + private static final HeaderName TENANT_ID = HeaderNames.create("x-tenant-id"); @Context private ServerRequest request; diff --git a/tests/integration/gh-5792/src/main/java/io/helidon/tests/integration/yamlparsing/GreetClientHttp.java b/tests/integration/gh-5792/src/main/java/io/helidon/tests/integration/yamlparsing/GreetClientHttp.java index 7d80eee3021..92811597bfe 100644 --- a/tests/integration/gh-5792/src/main/java/io/helidon/tests/integration/yamlparsing/GreetClientHttp.java +++ b/tests/integration/gh-5792/src/main/java/io/helidon/tests/integration/yamlparsing/GreetClientHttp.java @@ -15,7 +15,7 @@ */ package io.helidon.tests.integration.yamlparsing; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webclient.api.WebClient; /** @@ -35,7 +35,7 @@ public static void main(String[] args) { .baseUri("http://localhost:8080/greet") .build(); - String response = client.method(Http.Method.GET) + String response = client.method(Method.GET) .requestEntity(String.class); System.out.println(response); diff --git a/tests/integration/gh-5792/src/main/java/io/helidon/tests/integration/yamlparsing/GreetService.java b/tests/integration/gh-5792/src/main/java/io/helidon/tests/integration/yamlparsing/GreetService.java index 1f763d9eeaf..b5a9acaf120 100644 --- a/tests/integration/gh-5792/src/main/java/io/helidon/tests/integration/yamlparsing/GreetService.java +++ b/tests/integration/gh-5792/src/main/java/io/helidon/tests/integration/yamlparsing/GreetService.java @@ -18,7 +18,7 @@ import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -106,13 +106,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** diff --git a/tests/integration/gh-5792/src/test/java/io/helidon/tests/integration/yamlparsing/AbstractMainTest.java b/tests/integration/gh-5792/src/test/java/io/helidon/tests/integration/yamlparsing/AbstractMainTest.java index 66ffc3e2f1e..ca154f3ba42 100644 --- a/tests/integration/gh-5792/src/test/java/io/helidon/tests/integration/yamlparsing/AbstractMainTest.java +++ b/tests/integration/gh-5792/src/test/java/io/helidon/tests/integration/yamlparsing/AbstractMainTest.java @@ -15,15 +15,14 @@ */ package io.helidon.tests.integration.yamlparsing; - -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.SetUpRoute; -import org.junit.jupiter.api.Test; import jakarta.json.JsonObject; +import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; @@ -44,7 +43,7 @@ static void routing(HttpRouting.Builder builder) { @Test void testRootRoute() { try (Http1ClientResponse response = client.get("/greet").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("message"), is("Hello World!")); } @@ -53,7 +52,7 @@ void testRootRoute() { @Test void testOpenApi() { try (Http1ClientResponse response = client.get("/openapi").request()) { - assertThat("/openapi status", response.status(), is(Http.Status.OK_200)); + assertThat("/openapi status", response.status(), is(Status.OK_200)); assertThat("/openapi content", response.as(String.class), containsString("title: Swagger Petstore")); } } diff --git a/tests/integration/mp-gh-3246/src/test/java/io/helidon/tests/integration/gh3246/Gh3246Test.java b/tests/integration/mp-gh-3246/src/test/java/io/helidon/tests/integration/gh3246/Gh3246Test.java index e58ac1d6b95..c1211b4d558 100644 --- a/tests/integration/mp-gh-3246/src/test/java/io/helidon/tests/integration/gh3246/Gh3246Test.java +++ b/tests/integration/mp-gh-3246/src/test/java/io/helidon/tests/integration/gh3246/Gh3246Test.java @@ -19,7 +19,7 @@ import java.time.Instant; import io.helidon.common.configurable.Resource; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.microprofile.tests.junit5.AddBean; import io.helidon.microprofile.tests.junit5.HelidonTest; import io.helidon.security.jwt.Jwt; @@ -86,7 +86,7 @@ void testSecuredCallout() { String response = webTarget.path("/test/secured") .queryParam("port", port) .request() - .header(Http.HeaderNames.AUTHORIZATION.defaultCase(), "Bearer " + tokenContent) + .header(HeaderNames.AUTHORIZATION.defaultCase(), "Bearer " + tokenContent) .get(String.class); assertThat(response, is("hello")); diff --git a/tests/integration/mp-security-client/src/test/java/io/helidon/tests/integration/mp/security/client/MpSecurityClientTest.java b/tests/integration/mp-security-client/src/test/java/io/helidon/tests/integration/mp/security/client/MpSecurityClientTest.java index 9fbbbedd3bd..e5dea673205 100644 --- a/tests/integration/mp-security-client/src/test/java/io/helidon/tests/integration/mp/security/client/MpSecurityClientTest.java +++ b/tests/integration/mp-security-client/src/test/java/io/helidon/tests/integration/mp/security/client/MpSecurityClientTest.java @@ -22,7 +22,7 @@ import java.nio.charset.StandardCharsets; import java.util.Base64; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.microprofile.server.Server; import jakarta.json.Json; @@ -58,7 +58,7 @@ void testNotAuthenticated() throws Exception { con.connect(); - assertThat("Response code should be unauthorized", con.getResponseCode(), is(Http.Status.UNAUTHORIZED_401.code())); + assertThat("Response code should be unauthorized", con.getResponseCode(), is(Status.UNAUTHORIZED_401.code())); con.disconnect(); } @@ -70,7 +70,7 @@ void testAdmin() throws Exception { con.setRequestProperty("Authorization", buildBasic("jack", "password")); con.connect(); - assertThat("Response code should be 200", con.getResponseCode(), is(Http.Status.OK_200.code())); + assertThat("Response code should be 200", con.getResponseCode(), is(Status.OK_200.code())); JsonObject jsonObject; try(InputStream inputStream = con.getInputStream()) { @@ -98,7 +98,7 @@ void testUser() throws Exception { con.setRequestProperty("Authorization", buildBasic("john", "password")); con.connect(); - assertThat("Response code should be 200", con.getResponseCode(), is(Http.Status.OK_200.code())); + assertThat("Response code should be 200", con.getResponseCode(), is(Status.OK_200.code())); JsonObject jsonObject; try(InputStream inputStream = con.getInputStream()) { diff --git a/tests/integration/mp-ws-services/src/test/java/io/helidon/tests/integration/mp/ws/services/MpServicesTest.java b/tests/integration/mp-ws-services/src/test/java/io/helidon/tests/integration/mp/ws/services/MpServicesTest.java index 3889f866fbb..79062ed684b 100644 --- a/tests/integration/mp-ws-services/src/test/java/io/helidon/tests/integration/mp/ws/services/MpServicesTest.java +++ b/tests/integration/mp-ws-services/src/test/java/io/helidon/tests/integration/mp/ws/services/MpServicesTest.java @@ -23,7 +23,7 @@ import java.net.URL; import java.nio.charset.StandardCharsets; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.microprofile.server.Server; import org.junit.jupiter.api.AfterAll; @@ -81,7 +81,7 @@ private void test(int port, String path, String expected) throws IOException { assertThat("Should be a successful request (http://localhost:" + port + path + ")", con.getResponseCode(), - is(Http.Status.OK_200.code())); + is(Status.OK_200.code())); InputStream inputStream = con.getInputStream(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); diff --git a/tests/integration/native-image/mp-1/src/main/java/io/helidon/tests/integration/nativeimage/mp1/Mp1Main.java b/tests/integration/native-image/mp-1/src/main/java/io/helidon/tests/integration/nativeimage/mp1/Mp1Main.java index 4215afd4a0e..a03943c1697 100644 --- a/tests/integration/native-image/mp-1/src/main/java/io/helidon/tests/integration/nativeimage/mp1/Mp1Main.java +++ b/tests/integration/native-image/mp-1/src/main/java/io/helidon/tests/integration/nativeimage/mp1/Mp1Main.java @@ -55,9 +55,9 @@ import jakarta.ws.rs.core.Response; import org.eclipse.microprofile.faulttolerance.exceptions.TimeoutException; -import static io.helidon.http.Http.Status.FORBIDDEN_403; -import static io.helidon.http.Http.Status.OK_200; -import static io.helidon.http.Http.Status.UNAUTHORIZED_401; +import static io.helidon.http.Status.FORBIDDEN_403; +import static io.helidon.http.Status.OK_200; +import static io.helidon.http.Status.UNAUTHORIZED_401; /** * Main class of this integration test. diff --git a/tests/integration/native-image/mp-2/src/main/java/io/helidon/tests/integration/nativeimage/mp2/Mp2Main.java b/tests/integration/native-image/mp-2/src/main/java/io/helidon/tests/integration/nativeimage/mp2/Mp2Main.java index 36342329b3f..e4f2df6ed91 100644 --- a/tests/integration/native-image/mp-2/src/main/java/io/helidon/tests/integration/nativeimage/mp2/Mp2Main.java +++ b/tests/integration/native-image/mp-2/src/main/java/io/helidon/tests/integration/nativeimage/mp2/Mp2Main.java @@ -15,16 +15,16 @@ */ package io.helidon.tests.integration.nativeimage.mp2; +import io.helidon.common.Errors; +import io.helidon.microprofile.cdi.Main; + import jakarta.ws.rs.client.Client; import jakarta.ws.rs.client.ClientBuilder; import jakarta.ws.rs.client.Entity; import jakarta.ws.rs.client.WebTarget; import jakarta.ws.rs.core.Response; -import io.helidon.common.Errors; -import io.helidon.microprofile.cdi.Main; - -import static io.helidon.http.Http.Status.OK_200; +import static io.helidon.http.Status.OK_200; /** * Main class of this integration test. diff --git a/tests/integration/native-image/se-1/src/main/java/io/helidon/tests/integration/nativeimage/se1/GreetService.java b/tests/integration/native-image/se-1/src/main/java/io/helidon/tests/integration/nativeimage/se1/GreetService.java index fffe043a53c..043128e7fbf 100644 --- a/tests/integration/native-image/se-1/src/main/java/io/helidon/tests/integration/nativeimage/se1/GreetService.java +++ b/tests/integration/native-image/se-1/src/main/java/io/helidon/tests/integration/nativeimage/se1/GreetService.java @@ -21,7 +21,7 @@ import java.util.function.Consumer; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -120,13 +120,13 @@ private void updateGreetingHandler(ServerRequest request, JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } } diff --git a/tests/integration/native-image/se-1/src/main/java/io/helidon/tests/integration/nativeimage/se1/WebClientService.java b/tests/integration/native-image/se-1/src/main/java/io/helidon/tests/integration/nativeimage/se1/WebClientService.java index b98b201620c..06b2484c00e 100644 --- a/tests/integration/native-image/se-1/src/main/java/io/helidon/tests/integration/nativeimage/se1/WebClientService.java +++ b/tests/integration/native-image/se-1/src/main/java/io/helidon/tests/integration/nativeimage/se1/WebClientService.java @@ -23,10 +23,11 @@ import java.util.Objects; import java.util.function.Predicate; -import io.helidon.http.Http; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.reactive.Single; import io.helidon.config.Config; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.WebClient; import io.helidon.webserver.http.HttpRules; @@ -48,7 +49,7 @@ public WebClientService(Config config, MockZipkinService zipkinService) { this.context = "http://localhost:" + config.get("port").asInt().orElse(7076); client = WebClient.builder() .baseUri(context) - .addHeader(Http.HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) + .addHeader(HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) .config(config.get("client")) .build(); } @@ -63,13 +64,13 @@ public void routing(HttpRules rules) { private void redirect(ServerRequest request, ServerResponse response) { - response.headers().add(Http.HeaderNames.LOCATION, context + "/wc/endpoint"); - response.status(Http.Status.MOVED_PERMANENTLY_301).send(); + response.headers().add(HeaderNames.LOCATION, context + "/wc/endpoint"); + response.status(Status.MOVED_PERMANENTLY_301).send(); } private void redirectInfinite(ServerRequest serverRequest, ServerResponse response) { - response.headers().add(Http.HeaderNames.LOCATION, context + "/wc/redirect/infinite"); - response.status(Http.Status.MOVED_PERMANENTLY_301).send(); + response.headers().add(HeaderNames.LOCATION, context + "/wc/redirect/infinite"); + response.status(Status.MOVED_PERMANENTLY_301).send(); } private void getEndpoint(final ServerRequest request, final ServerResponse response) { @@ -85,7 +86,7 @@ private void getTest(final ServerRequest request, final ServerResponse response) response.send("ALL TESTS PASSED!\n"); } catch (Exception e) { - response.status(Http.Status.INTERNAL_SERVER_ERROR_500); + response.status(Status.INTERNAL_SERVER_ERROR_500); StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); response.send("Failed to process request: " + writer); @@ -115,7 +116,7 @@ public void testFollowRedirect() { .path("/wc/redirect") .followRedirects(false) .request()) { - assertEquals(response.status(), Http.Status.MOVED_PERMANENTLY_301); + assertEquals(response.status(), Status.MOVED_PERMANENTLY_301); } } diff --git a/tests/integration/security/gh2297/src/test/java/io/helidon/tests/integration/security/gh2297/ProtectedMetricsTest.java b/tests/integration/security/gh2297/src/test/java/io/helidon/tests/integration/security/gh2297/ProtectedMetricsTest.java index 6e72c6d4bbd..0a633129d8f 100644 --- a/tests/integration/security/gh2297/src/test/java/io/helidon/tests/integration/security/gh2297/ProtectedMetricsTest.java +++ b/tests/integration/security/gh2297/src/test/java/io/helidon/tests/integration/security/gh2297/ProtectedMetricsTest.java @@ -18,7 +18,7 @@ import java.util.Base64; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.microprofile.server.Server; import jakarta.ws.rs.client.Client; @@ -81,7 +81,7 @@ void testMetricsEndpointNoUser() { Response response = metricTarget.request() .get(); - assertThat(response.getStatus(), is(Http.Status.UNAUTHORIZED_401.code())); + assertThat(response.getStatus(), is(Status.UNAUTHORIZED_401.code())); } // TODO metrics @@ -91,7 +91,7 @@ void testMetricEndpointSuccess() { .header("Authorization", basic("success")) .get(); - assertThat(response.getStatus(), is(Http.Status.OK_200.code())); + assertThat(response.getStatus(), is(Status.OK_200.code())); } @Test @@ -100,7 +100,7 @@ void testMetricEndpointForbidden() { .header("Authorization", basic("fail")) .get(); - assertThat(response.getStatus(), is(Http.Status.FORBIDDEN_403.code())); + assertThat(response.getStatus(), is(Status.FORBIDDEN_403.code())); } private String basic(String user) { diff --git a/tests/integration/security/path-params/src/test/java/io/helidon/tests/integration/security/pathparams/AdminTest.java b/tests/integration/security/path-params/src/test/java/io/helidon/tests/integration/security/pathparams/AdminTest.java index 2fc1b73cf7d..480be4216c5 100644 --- a/tests/integration/security/path-params/src/test/java/io/helidon/tests/integration/security/pathparams/AdminTest.java +++ b/tests/integration/security/path-params/src/test/java/io/helidon/tests/integration/security/pathparams/AdminTest.java @@ -19,7 +19,7 @@ import java.util.Base64; import java.util.function.Function; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.microprofile.server.Server; import jakarta.ws.rs.client.Client; @@ -71,39 +71,39 @@ void testGreetResource() { @Test void testAdminResource1() { Response response = target.apply("/admin").request().get(); - assertThat(response.getStatus(), is(Http.Status.UNAUTHORIZED_401.code())); + assertThat(response.getStatus(), is(Status.UNAUTHORIZED_401.code())); } @Test void testAdminResource2() { Response response = target.apply("/admin;a=b").request().get(); - assertThat(response.getStatus(), is(Http.Status.UNAUTHORIZED_401.code())); + assertThat(response.getStatus(), is(Status.UNAUTHORIZED_401.code())); } @Test void testAdminResource3() { Response response = target.apply("/admin;a=b;c=d").request().get(); - assertThat(response.getStatus(), is(Http.Status.UNAUTHORIZED_401.code())); + assertThat(response.getStatus(), is(Status.UNAUTHORIZED_401.code())); } @Test void testAdminResource4() { Response response = target.apply("/admin;").request().get(); - assertThat(response.getStatus(), is(Http.Status.UNAUTHORIZED_401.code())); + assertThat(response.getStatus(), is(Status.UNAUTHORIZED_401.code())); } @Test @Disabled void testAdminResource5() { Response response = target.apply("/admin/;").request().get(); - assertThat(response.getStatus(), is(Http.Status.UNAUTHORIZED_401.code())); + assertThat(response.getStatus(), is(Status.UNAUTHORIZED_401.code())); } @Test @Disabled void testAdminResource6() { Response response = target.apply("/admin/;/").request().get(); - assertThat(response.getStatus(), is(Http.Status.UNAUTHORIZED_401.code())); + assertThat(response.getStatus(), is(Status.UNAUTHORIZED_401.code())); } @Test @@ -111,7 +111,7 @@ void testAdminResourceBasicAuth1() { Response response = target.apply("/admin").request() .header("Authorization", basic("success")) .get(); - assertThat(response.getStatus(), is(Http.Status.OK_200.code())); + assertThat(response.getStatus(), is(Status.OK_200.code())); } @Test @@ -119,7 +119,7 @@ void testAdminResourceBasicAuth2() { Response response = target.apply("/admin;a=b").request() .header("Authorization", basic("success")) .get(); - assertThat(response.getStatus(), is(Http.Status.OK_200.code())); + assertThat(response.getStatus(), is(Status.OK_200.code())); } private String basic(String user) { diff --git a/tests/integration/vault/src/test/java/io/helidon/examples/integrations/vault/hcp/VaultTest.java b/tests/integration/vault/src/test/java/io/helidon/examples/integrations/vault/hcp/VaultTest.java index 26dda3f5b30..2628a5cb76d 100644 --- a/tests/integration/vault/src/test/java/io/helidon/examples/integrations/vault/hcp/VaultTest.java +++ b/tests/integration/vault/src/test/java/io/helidon/examples/integrations/vault/hcp/VaultTest.java @@ -25,7 +25,7 @@ import java.util.Optional; import io.helidon.common.Base64Value; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.integrations.common.rest.ApiResponse; import io.helidon.integrations.vault.Secret; import io.helidon.integrations.vault.Vault; @@ -149,7 +149,7 @@ void testKv1() { assertThat("Enable kv1 engine, got response status: " + enableResponse.status(), enableResponse.status().family(), - is(Http.Status.Family.SUCCESSFUL)); + is(Status.Family.SUCCESSFUL)); Kv1Secrets secrets = tokenVault.secrets(Kv1Secrets.ENGINE); String secretPath = "first/secret"; @@ -158,7 +158,7 @@ void testKv1() { CreateKv1.Response createResponse = secrets.create(secretPath, Map.of("key", "secretValue")); assertThat("Create secret, got response status: " + createResponse.status(), createResponse.status().family(), - is(Http.Status.Family.SUCCESSFUL)); + is(Status.Family.SUCCESSFUL)); // get secret Optional maybeSecret = secrets.get(secretPath); @@ -171,7 +171,7 @@ void testKv1() { DeleteKv1.Response deleteResponse = secrets.delete(secretPath); assertThat("Delete secret, got response status: " + deleteResponse.status(), deleteResponse.status().family(), - is(Http.Status.Family.SUCCESSFUL)); + is(Status.Family.SUCCESSFUL)); List secretList = secrets.list(); assertThat(secretList, is(List.of())); @@ -185,7 +185,7 @@ void testKv1() { assertThat("Disable kv1 engine, got response status: " + disableResponse.status(), disableResponse.status().family(), - is(Http.Status.Family.SUCCESSFUL)); + is(Status.Family.SUCCESSFUL)); } @Test @@ -198,7 +198,7 @@ void testKv2() { CreateKv2.Response createResponse = secrets.create(secretPath, Map.of("key", "secretValue")); assertThat("Create secret, got response status: " + createResponse.status(), createResponse.status().family(), - is(Http.Status.Family.SUCCESSFUL)); + is(Status.Family.SUCCESSFUL)); // get secret Optional maybeSecret = secrets.get(secretPath); @@ -218,7 +218,7 @@ void testKv2() { DeleteKv2.Response deleteResponse = secrets.delete(secretPath, 1); assertThat("Delete secret, got response status: " + deleteResponse.status(), deleteResponse.status().family(), - is(Http.Status.Family.SUCCESSFUL)); + is(Status.Family.SUCCESSFUL)); maybeSecret = secrets.get(secretPath); @@ -235,7 +235,7 @@ void testCubbyhole() { CreateCubbyhole.Response createResponse = secrets.create(secretPath, Map.of("key", "secretValue")); assertThat("Create secret, got response status: " + createResponse.status(), createResponse.status().family(), - is(Http.Status.Family.SUCCESSFUL)); + is(Status.Family.SUCCESSFUL)); // get secret Optional maybeSecret = secrets.get(secretPath); @@ -248,7 +248,7 @@ void testCubbyhole() { DeleteCubbyhole.Response deleteResponse = secrets.delete(secretPath); assertThat("Delete secret, got response status: " + deleteResponse.status(), deleteResponse.status().family(), - is(Http.Status.Family.SUCCESSFUL)); + is(Status.Family.SUCCESSFUL)); List secretList = secrets.list(); assertThat(secretList, is(List.of())); @@ -509,6 +509,6 @@ private void transitBatch(TransitSecrets secrets) { private void assertSuccess(String action, ApiResponse response) { assertThat(action + ", got response status: " + response.status(), response.status().family(), - is(Http.Status.Family.SUCCESSFUL)); + is(Status.Family.SUCCESSFUL)); } } diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/ClientRequest.java b/webclient/api/src/main/java/io/helidon/webclient/api/ClientRequest.java index 236a498bd8c..49bf7cbae8a 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/ClientRequest.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/ClientRequest.java @@ -30,10 +30,13 @@ import io.helidon.common.uri.UriFragment; import io.helidon.common.uri.UriInfo; import io.helidon.http.ClientRequestHeaders; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpException; import io.helidon.http.HttpMediaType; +import io.helidon.http.Status; /** * Request can be reused within a single thread, but it remembers all explicitly configured headers and URI. @@ -100,7 +103,7 @@ default T path(String uri) { * @param header header to set * @return updated request */ - T header(Http.Header header); + T header(Header header); /** * Set an HTTP header. @@ -109,8 +112,8 @@ default T path(String uri) { * @param values header values * @return updated request */ - default T header(Http.HeaderName name, String... values) { - return header(Http.Headers.create(name, true, false, values)); + default T header(HeaderName name, String... values) { + return header(HeaderValues.create(name, true, false, values)); } /** @@ -120,8 +123,8 @@ default T header(Http.HeaderName name, String... values) { * @param values header values * @return updated request */ - default T header(Http.HeaderName name, List values) { - return header(Http.Headers.create(name, values)); + default T header(HeaderName name, List values) { + return header(HeaderValues.create(name, values)); } /** @@ -276,10 +279,10 @@ default ClientResponseTyped request(Class type) { */ default E requestEntity(Class type) throws HttpException { ClientResponseTyped typedResponse = request(type); - if (typedResponse.status().family() == Http.Status.Family.SUCCESSFUL) { + if (typedResponse.status().family() == Status.Family.SUCCESSFUL) { return typedResponse.entity(); } - if (typedResponse.status() == Http.Status.BAD_REQUEST_400) { + if (typedResponse.status() == Status.BAD_REQUEST_400) { throw new IllegalArgumentException("Failed to read entity, received bad request"); } throw new IllegalStateException(typedResponse.status() + ": Failed to read entity, as response status is not success"); diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/ClientRequestBase.java b/webclient/api/src/main/java/io/helidon/webclient/api/ClientRequestBase.java index d39b466bf84..d109fc7f631 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/ClientRequestBase.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/ClientRequestBase.java @@ -38,8 +38,11 @@ import io.helidon.common.uri.UriEncoding; import io.helidon.common.uri.UriFragment; import io.helidon.http.ClientRequestHeaders; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.http.media.MediaContext; import io.helidon.webclient.spi.WebClientService; @@ -54,8 +57,8 @@ public abstract class ClientRequestBase, R extends Ht /** * Helidon user agent request header. */ - public static final Http.Header USER_AGENT_HEADER = Http.Headers.create(Http.HeaderNames.USER_AGENT, - "Helidon " + Version.VERSION); + public static final Header USER_AGENT_HEADER = HeaderValues.create(HeaderNames.USER_AGENT, + "Helidon " + Version.VERSION); private static final Map COUNTERS = new ConcurrentHashMap<>(); private static final Set SUPPORTED_SCHEMES = Set.of("https", "http"); @@ -63,7 +66,7 @@ public abstract class ClientRequestBase, R extends Ht private final HttpClientConfig clientConfig; private final WebClientCookieManager cookieManager; private final String protocolId; - private final Http.Method method; + private final Method method; private final ClientUri clientUri; private final Map properties; private final ClientRequestHeaders headers; @@ -84,7 +87,7 @@ public abstract class ClientRequestBase, R extends Ht protected ClientRequestBase(HttpClientConfig clientConfig, WebClientCookieManager cookieManager, String protocolId, - Http.Method method, + Method method, ClientUri clientUri, Map properties) { this.clientConfig = clientConfig; @@ -156,14 +159,14 @@ public ClientRequestHeaders headers() { } @Override - public T header(Http.Header header) { + public T header(Header header) { this.headers.set(header); return identity(); } @Override public T headers(Headers headers) { - for (Http.Header header : headers) { + for (Header header : headers) { this.headers.add(header); } return identity(); @@ -276,7 +279,7 @@ public final R outputStream(OutputStreamHandler outputStreamConsumer) { * @return HTTP method */ @Override - public Http.Method method() { + public Method method() { return method; } @@ -467,8 +470,8 @@ private String resolvePathParams(String path) { } private void rejectHeadWithEntity() { - if (this.method.equals(Http.Method.HEAD)) { - throw new IllegalArgumentException("Payload in method '" + Http.Method.HEAD + "' has no defined semantics"); + if (this.method.equals(Method.HEAD)) { + throw new IllegalArgumentException("Payload in method '" + Method.HEAD + "' has no defined semantics"); } } diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/ClientResponseBase.java b/webclient/api/src/main/java/io/helidon/webclient/api/ClientResponseBase.java index 373fb46dc8f..3591c1ceecf 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/ClientResponseBase.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/ClientResponseBase.java @@ -17,7 +17,7 @@ package io.helidon.webclient.api; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; +import io.helidon.http.Status; /** * Http client response base. @@ -28,7 +28,7 @@ interface ClientResponseBase { * * @return status */ - Http.Status status(); + Status status(); /** * Response headers. diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/ClientResponseTypedImpl.java b/webclient/api/src/main/java/io/helidon/webclient/api/ClientResponseTypedImpl.java index 57b08ce0271..435fbf7ca25 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/ClientResponseTypedImpl.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/ClientResponseTypedImpl.java @@ -17,7 +17,7 @@ package io.helidon.webclient.api; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; +import io.helidon.http.Status; class ClientResponseTypedImpl implements ClientResponseTyped { private final HttpClientResponse response; @@ -42,7 +42,7 @@ class ClientResponseTypedImpl implements ClientResponseTyped { } @Override - public Http.Status status() { + public Status status() { return response.status(); } diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/FullClientRequest.java b/webclient/api/src/main/java/io/helidon/webclient/api/FullClientRequest.java index 350f4a2e468..806ea34318f 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/FullClientRequest.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/FullClientRequest.java @@ -21,7 +21,7 @@ import java.util.Optional; import io.helidon.common.tls.Tls; -import io.helidon.http.Http; +import io.helidon.http.Method; /** * Client request with getters for all configurable options, used for integration with HTTP version implementations. @@ -41,7 +41,7 @@ public interface FullClientRequest> extends ClientReq * * @return method */ - Http.Method method(); + Method method(); /** * URI of this request. diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/HttpClient.java b/webclient/api/src/main/java/io/helidon/webclient/api/HttpClient.java index 288112defbc..a08aaa2c6fd 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/HttpClient.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/HttpClient.java @@ -16,7 +16,7 @@ package io.helidon.webclient.api; -import io.helidon.http.Http; +import io.helidon.http.Method; /** * HTTP client. @@ -30,7 +30,7 @@ public interface HttpClient> { * @param method HTTP method * @return a new request (not thread safe) */ - REQ method(Http.Method method); + REQ method(Method method); /** * Shortcut for get method with a path. @@ -39,7 +39,7 @@ public interface HttpClient> { * @return a new request (not thread safe) */ default REQ get(String uri) { - return (REQ) method(Http.Method.GET).uri(uri); + return (REQ) method(Method.GET).uri(uri); } /** @@ -48,7 +48,7 @@ default REQ get(String uri) { * @return a new request (not thread safe) */ default REQ get() { - return method(Http.Method.GET); + return method(Method.GET); } /** @@ -58,7 +58,7 @@ default REQ get() { * @return a new request (not thread safe) */ default REQ post(String uri) { - return (REQ) method(Http.Method.POST).uri(uri); + return (REQ) method(Method.POST).uri(uri); } /** @@ -67,7 +67,7 @@ default REQ post(String uri) { * @return a new request (not thread safe) */ default REQ post() { - return method(Http.Method.POST); + return method(Method.POST); } /** @@ -77,7 +77,7 @@ default REQ post() { * @return a new request (not thread safe) */ default REQ put(String uri) { - return (REQ) method(Http.Method.PUT).uri(uri); + return (REQ) method(Method.PUT).uri(uri); } /** @@ -86,7 +86,7 @@ default REQ put(String uri) { * @return a new request (not thread safe) */ default REQ put() { - return method(Http.Method.PUT); + return method(Method.PUT); } /** @@ -96,7 +96,7 @@ default REQ put() { * @return a new request (not thread safe) */ default REQ delete(String uri) { - return (REQ) method(Http.Method.DELETE).uri(uri); + return (REQ) method(Method.DELETE).uri(uri); } /** @@ -105,7 +105,7 @@ default REQ delete(String uri) { * @return a new request (not thread safe) */ default REQ delete() { - return method(Http.Method.DELETE); + return method(Method.DELETE); } /** @@ -115,7 +115,7 @@ default REQ delete() { * @return a new request (not thread safe) */ default REQ head(String uri) { - return (REQ) method(Http.Method.HEAD).uri(uri); + return (REQ) method(Method.HEAD).uri(uri); } /** @@ -124,7 +124,7 @@ default REQ head(String uri) { * @return a new request (not thread safe) */ default REQ head() { - return method(Http.Method.HEAD); + return method(Method.HEAD); } /** @@ -134,7 +134,7 @@ default REQ head() { * @return a new request (not thread safe) */ default REQ options(String uri) { - return (REQ) method(Http.Method.OPTIONS).uri(uri); + return (REQ) method(Method.OPTIONS).uri(uri); } /** @@ -143,7 +143,7 @@ default REQ options(String uri) { * @return a new request (not thread safe) */ default REQ options() { - return method(Http.Method.OPTIONS); + return method(Method.OPTIONS); } /** @@ -153,7 +153,7 @@ default REQ options() { * @return a new request (not thread safe) */ default REQ trace(String uri) { - return (REQ) method(Http.Method.TRACE).uri(uri); + return (REQ) method(Method.TRACE).uri(uri); } /** @@ -162,7 +162,7 @@ default REQ trace(String uri) { * @return a new request (not thread safe) */ default REQ trace() { - return method(Http.Method.TRACE); + return method(Method.TRACE); } /** @@ -172,7 +172,7 @@ default REQ trace() { * @return a new request (not thread safe) */ default REQ patch(String uri) { - return (REQ) method(Http.Method.PATCH).uri(uri); + return (REQ) method(Method.PATCH).uri(uri); } /** @@ -181,6 +181,6 @@ default REQ patch(String uri) { * @return a new request (not thread safe) */ default REQ patch() { - return method(Http.Method.PATCH); + return method(Method.PATCH); } } diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientConfigBlueprint.java b/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientConfigBlueprint.java index d785b524160..434c64e6bbe 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientConfigBlueprint.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientConfigBlueprint.java @@ -32,7 +32,7 @@ import io.helidon.config.metadata.Configured; import io.helidon.config.metadata.ConfiguredOption; import io.helidon.http.ClientRequestHeaders; -import io.helidon.http.Http; +import io.helidon.http.Header; import io.helidon.http.WritableHeaders; import io.helidon.http.encoding.ContentEncodingContext; import io.helidon.http.media.MediaContext; @@ -114,7 +114,7 @@ interface HttpClientConfigBlueprint extends HttpConfigBaseBlueprint { * @return default headers */ @Option.Singular - Set headers(); + Set

headers(); /** * Default headers as a headers object. Creates a new instance for each call, so the returned value diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientConfigSupport.java b/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientConfigSupport.java index 97ed8cd579c..6f8598fc832 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientConfigSupport.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientConfigSupport.java @@ -24,7 +24,8 @@ import io.helidon.common.LazyValue; import io.helidon.common.socket.SocketOptions; import io.helidon.common.tls.Tls; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderValues; import io.helidon.http.encoding.ContentEncodingContext; import io.helidon.http.media.MediaContext; import io.helidon.webclient.spi.DnsResolver; @@ -72,8 +73,8 @@ static void baseUri(HttpClientConfig.BuilderBase builder, String baseUri) * @param value value of the header */ @Prototype.BuilderMethod - static void addHeader(HttpClientConfig.BuilderBase builder, Http.HeaderName name, String value) { - builder.addHeader(Http.Headers.create(name, value)); + static void addHeader(HttpClientConfig.BuilderBase builder, HeaderName name, String value) { + builder.addHeader(HeaderValues.create(name, value)); } /** @@ -84,8 +85,8 @@ static void addHeader(HttpClientConfig.BuilderBase builder, Http.HeaderNam * @param value value of the header */ @Prototype.BuilderMethod - static void addHeader(HttpClientConfig.BuilderBase builder, Http.HeaderName name, int value) { - builder.addHeader(Http.Headers.create(name, value)); + static void addHeader(HttpClientConfig.BuilderBase builder, HeaderName name, int value) { + builder.addHeader(HeaderValues.create(name, value)); } /** @@ -96,54 +97,54 @@ static void addHeader(HttpClientConfig.BuilderBase builder, Http.HeaderNam * @param value value of the header */ @Prototype.BuilderMethod - static void addHeader(HttpClientConfig.BuilderBase builder, Http.HeaderName name, long value) { - builder.addHeader(Http.Headers.create(name, value)); + static void addHeader(HttpClientConfig.BuilderBase builder, HeaderName name, long value) { + builder.addHeader(HeaderValues.create(name, value)); } /** * Add default header value. This method is not optimal and should only be used when the header name is really - * obtained from a string, in other cases, use an alternative with {@link io.helidon.http.Http.HeaderName} - * or {@link io.helidon.http.Http.Header}. + * obtained from a string, in other cases, use an alternative with {@link io.helidon.http.HeaderName} + * or {@link io.helidon.http.Header}. * * @param builder builder to update * @param name name of the header * @param value value of the header - * @see #addHeader(io.helidon.http.Http.Header) + * @see #addHeader(io.helidon.http.Header) */ @Prototype.BuilderMethod static void addHeader(HttpClientConfig.BuilderBase builder, String name, String value) { - builder.addHeader(Http.Headers.create(name, value)); + builder.addHeader(HeaderValues.create(name, value)); } /** * Add default header value. This method is not optimal and should only be used when the header name is really - * obtained from a string, in other cases, use an alternative with {@link io.helidon.http.Http.HeaderName} - * or {@link io.helidon.http.Http.Header}. + * obtained from a string, in other cases, use an alternative with {@link io.helidon.http.HeaderName} + * or {@link io.helidon.http.Header}. * * @param builder builder to update * @param name name of the header * @param value value of the header - * @see #addHeader(io.helidon.http.Http.Header) + * @see #addHeader(io.helidon.http.Header) */ @Prototype.BuilderMethod static void addHeader(HttpClientConfig.BuilderBase builder, String name, int value) { - builder.addHeader(Http.Headers.create(name, value)); + builder.addHeader(HeaderValues.create(name, value)); } /** * Add default header value. This method is not optimal and should only be used when the header name is really - * obtained from a string, in other cases, use an alternative with {@link io.helidon.http.Http.HeaderName} - * or {@link io.helidon.http.Http.Header}. + * obtained from a string, in other cases, use an alternative with {@link io.helidon.http.HeaderName} + * or {@link io.helidon.http.Header}. * * @param builder builder to update * @param name name of the header * @param value value of the header - * @see #addHeader(io.helidon.http.Http.Header) + * @see #addHeader(io.helidon.http.Header) */ @Prototype.BuilderMethod static void addHeader(HttpClientConfig.BuilderBase builder, String name, long value) { - builder.addHeader(Http.Headers.create(name, value)); + builder.addHeader(HeaderValues.create(name, value)); } } diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientRequest.java b/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientRequest.java index d3882188af7..36ba87c3cf3 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientRequest.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/HttpClientRequest.java @@ -23,7 +23,7 @@ import io.helidon.common.configurable.LruCache; import io.helidon.common.socket.HelidonSocket; import io.helidon.common.tls.Tls; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webclient.spi.HttpClientSpi; /** @@ -44,7 +44,7 @@ public class HttpClientRequest extends ClientRequestBase protocolsToClients, List protocols, diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/LoomClient.java b/webclient/api/src/main/java/io/helidon/webclient/api/LoomClient.java index b83dbb30d82..86a6ffd3e29 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/LoomClient.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/LoomClient.java @@ -27,7 +27,7 @@ import io.helidon.common.HelidonServiceLoader; import io.helidon.common.LazyValue; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.inject.configdriven.api.ConfigDriven; import io.helidon.webclient.spi.ClientProtocolProvider; import io.helidon.webclient.spi.HttpClientSpi; @@ -133,7 +133,7 @@ public WebClientCookieManager cookieManager() { } @Override - public HttpClientRequest method(Http.Method method) { + public HttpClientRequest method(Method method) { ClientUri clientUri = prototype().baseUri() .map(ClientUri::create) // create from base config .orElseGet(ClientUri::create); // create as empty diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/Proxy.java b/webclient/api/src/main/java/io/helidon/webclient/api/Proxy.java index a178a803e3f..31fb60fab3c 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/Proxy.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/Proxy.java @@ -45,8 +45,11 @@ import io.helidon.common.tls.Tls; import io.helidon.config.metadata.Configured; import io.helidon.config.metadata.ConfiguredOption; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; /** * A definition of a proxy server to use for outgoing requests. @@ -54,8 +57,8 @@ public class Proxy { private static final System.Logger LOGGER = System.getLogger(Proxy.class.getName()); private static final Tls NO_TLS = Tls.builder().enabled(false).build(); - private static final Http.Header PROXY_CONNECTION = - Http.Headers.create("Proxy-Connection", "keep-alive"); + private static final Header PROXY_CONNECTION = + HeaderValues.create("Proxy-Connection", "keep-alive"); /** * No proxy instance. @@ -85,7 +88,7 @@ public class Proxy { private final Optional username; private final Optional password; private final ProxySelector systemProxySelector; - private final Optional proxyAuthHeader; + private final Optional
proxyAuthHeader; private Proxy(Proxy.Builder builder) { this.host = builder.host(); @@ -112,7 +115,7 @@ private Proxy(Proxy.Builder builder) { // Making the password char[] to String looks not correct, but it is done in the same way in HttpBasicAuthProvider String b64 = Base64.getEncoder().encodeToString((username.get() + ":" + new String(pass)) .getBytes(StandardCharsets.UTF_8)); - this.proxyAuthHeader = Optional.of(Http.Headers.create(HeaderNames.PROXY_AUTHORIZATION, "Basic " + b64)); + this.proxyAuthHeader = Optional.of(HeaderValues.create(HeaderNames.PROXY_AUTHORIZATION, "Basic " + b64)); } else { this.proxyAuthHeader = Optional.empty(); } @@ -464,7 +467,7 @@ private static Socket connectToProxy(WebClient webClient, }) .connect(); - HttpClientRequest request = webClient.method(Http.Method.CONNECT) + HttpClientRequest request = webClient.method(Method.CONNECT) .followRedirects(false) // do not follow redirects for proxy connect itself .connection(connection) .uri("http://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort()) @@ -472,13 +475,13 @@ private static Socket connectToProxy(WebClient webClient, .header(HeaderNames.HOST, targetAddress.getHostName() + ":" + targetAddress.getPort()) .accept(MediaTypes.WILDCARD); if (clientConfig.keepAlive()) { - request.header(Http.Headers.CONNECTION_KEEP_ALIVE) + request.header(HeaderValues.CONNECTION_KEEP_ALIVE) .header(PROXY_CONNECTION); } proxy.proxyAuthHeader.ifPresent(request::header); // we cannot close the response, as that would close the connection HttpClientResponse response = request.request(); - if (response.status().family() != Http.Status.Family.SUCCESSFUL) { + if (response.status().family() != Status.Family.SUCCESSFUL) { response.close(); throw new IllegalStateException("Proxy sent wrong HTTP response code: " + response.status()); } diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/ServiceRequestImpl.java b/webclient/api/src/main/java/io/helidon/webclient/api/ServiceRequestImpl.java index c9b0fd4d965..88251566b91 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/ServiceRequestImpl.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/ServiceRequestImpl.java @@ -22,13 +22,13 @@ import io.helidon.common.context.Context; import io.helidon.http.ClientRequestHeaders; -import io.helidon.http.Http; +import io.helidon.http.Method; class ServiceRequestImpl implements WebClientServiceRequest { private final Map properties; private final String protocolId; private final ClientUri uri; - private final Http.Method method; + private final Method method; private final ClientRequestHeaders headers; private final Context context; private final CompletionStage whenComplete; @@ -37,7 +37,7 @@ class ServiceRequestImpl implements WebClientServiceRequest { private String requestId; ServiceRequestImpl(ClientUri uri, - Http.Method method, + Method method, String protocolId, ClientRequestHeaders headers, Context context, @@ -62,7 +62,7 @@ public ClientUri uri() { } @Override - public Http.Method method() { + public Method method() { return method; } diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/WebClientCookieManager.java b/webclient/api/src/main/java/io/helidon/webclient/api/WebClientCookieManager.java index 6681449d9f8..ccbb45ef9ff 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/WebClientCookieManager.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/WebClientCookieManager.java @@ -28,7 +28,7 @@ import io.helidon.builder.api.RuntimeType; import io.helidon.http.ClientRequestHeaders; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; /** * Helidon WebClient cookie manager. @@ -36,9 +36,9 @@ @RuntimeType.PrototypedBy(WebClientCookieManagerConfig.class) public class WebClientCookieManager extends CookieManager implements RuntimeType.Api { - private static final String COOKIE = Http.HeaderNames.COOKIE.defaultCase(); - private static final String SET_COOKIE = Http.HeaderNames.SET_COOKIE.defaultCase(); - private static final String SET_COOKIE2 = Http.HeaderNames.SET_COOKIE2.defaultCase(); + private static final String COOKIE = HeaderNames.COOKIE.defaultCase(); + private static final String SET_COOKIE = HeaderNames.SET_COOKIE.defaultCase(); + private static final String SET_COOKIE2 = HeaderNames.SET_COOKIE2.defaultCase(); private final boolean acceptCookies; private final List defaultCookies; @@ -117,10 +117,10 @@ public void request(ClientUri uri, ClientRequestHeaders requestHeaders) { List cookies = cookieMap.get(COOKIE); cookies.addAll(defaultCookies); if (!cookies.isEmpty()) { - requestHeaders.add(Http.HeaderNames.COOKIE, cookies.toArray(new String[0])); + requestHeaders.add(HeaderNames.COOKIE, cookies.toArray(new String[0])); } } else if (!defaultCookies.isEmpty()) { - requestHeaders.add(Http.HeaderNames.COOKIE, defaultCookies.toArray(new String[0])); + requestHeaders.add(HeaderNames.COOKIE, defaultCookies.toArray(new String[0])); } } catch (IOException e) { throw new UncheckedIOException(e); @@ -140,14 +140,14 @@ public void response(ClientUri uri, ClientResponseHeaders headers) { if (acceptCookies) { Map> cookies = null; - if (headers.contains(Http.HeaderNames.SET_COOKIE)) { + if (headers.contains(HeaderNames.SET_COOKIE)) { cookies = new HashMap<>(); - cookies.put(SET_COOKIE, headers.get(Http.HeaderNames.SET_COOKIE).allValues()); + cookies.put(SET_COOKIE, headers.get(HeaderNames.SET_COOKIE).allValues()); } - if (headers.contains(Http.HeaderNames.SET_COOKIE2)) { + if (headers.contains(HeaderNames.SET_COOKIE2)) { cookies = cookies == null ? new HashMap<>() : cookies; - cookies.put(SET_COOKIE2, headers.get(Http.HeaderNames.SET_COOKIE2).allValues()); + cookies.put(SET_COOKIE2, headers.get(HeaderNames.SET_COOKIE2).allValues()); } if (cookies != null) { diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/WebClientServiceRequest.java b/webclient/api/src/main/java/io/helidon/webclient/api/WebClientServiceRequest.java index 3635bebc9b1..c36b52cb320 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/WebClientServiceRequest.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/WebClientServiceRequest.java @@ -21,7 +21,7 @@ import io.helidon.common.context.Context; import io.helidon.http.ClientRequestHeaders; -import io.helidon.http.Http; +import io.helidon.http.Method; /** * Request to SPI {@link io.helidon.webclient.spi.WebClientService} that supports modification of the outgoing request. @@ -35,12 +35,12 @@ public interface WebClientServiceRequest { ClientUri uri(); /** - * Returns an HTTP request method. See also {@link io.helidon.http.Http.Method HTTP standard methods} utility class. + * Returns an HTTP request method. See also {@link io.helidon.http.Method HTTP standard methods} utility class. * * @return an HTTP method - * @see io.helidon.http.Http.Method + * @see io.helidon.http.Method */ - Http.Method method(); + Method method(); /** * Returns an HTTP protocol ID, mapped to a specific version. This is the same ID that is used for ALPN diff --git a/webclient/api/src/main/java/io/helidon/webclient/api/WebClientServiceResponseBlueprint.java b/webclient/api/src/main/java/io/helidon/webclient/api/WebClientServiceResponseBlueprint.java index e1647b187c0..02561e4328a 100644 --- a/webclient/api/src/main/java/io/helidon/webclient/api/WebClientServiceResponseBlueprint.java +++ b/webclient/api/src/main/java/io/helidon/webclient/api/WebClientServiceResponseBlueprint.java @@ -22,7 +22,7 @@ import io.helidon.builder.api.Prototype; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; +import io.helidon.http.Status; /** * Response which is created upon receiving of server response. @@ -42,7 +42,7 @@ interface WebClientServiceResponseBlueprint { * * @return response status */ - Http.Status status(); + Status status(); /** * Input stream to get data of the entity. This allows decorating the entity (such as decryption). diff --git a/webclient/api/src/test/java/io/helidon/webclient/api/HttpClientTest.java b/webclient/api/src/test/java/io/helidon/webclient/api/HttpClientTest.java index a6f2d429d9e..0f0e20461f6 100644 --- a/webclient/api/src/test/java/io/helidon/webclient/api/HttpClientTest.java +++ b/webclient/api/src/test/java/io/helidon/webclient/api/HttpClientTest.java @@ -21,11 +21,12 @@ import java.util.Map; import java.util.function.Consumer; +import io.helidon.common.tls.Tls; +import io.helidon.common.uri.UriFragment; import io.helidon.http.ClientRequestHeaders; +import io.helidon.http.Header; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.common.uri.UriFragment; -import io.helidon.common.tls.Tls; +import io.helidon.http.Method; import org.junit.jupiter.api.Test; @@ -37,16 +38,16 @@ class HttpClientTest { // Validate that the Http Shortcut methods are using their corresponding HTTP Method @Test void testHttpMethodShortcuts() { - Map map = Map.of(Http.Method.GET, new FakeHttpClient().get(), - Http.Method.POST, new FakeHttpClient().post(), - Http.Method.PUT, new FakeHttpClient().put(), - Http.Method.DELETE, new FakeHttpClient().delete(), - Http.Method.HEAD, new FakeHttpClient().head(), - Http.Method.OPTIONS, new FakeHttpClient().options(), - Http.Method.TRACE, new FakeHttpClient().trace(), - Http.Method.PATCH, new FakeHttpClient().patch()); - - for (Map.Entry entry : map.entrySet()) { + Map map = Map.of(Method.GET, new FakeHttpClient().get(), + Method.POST, new FakeHttpClient().post(), + Method.PUT, new FakeHttpClient().put(), + Method.DELETE, new FakeHttpClient().delete(), + Method.HEAD, new FakeHttpClient().head(), + Method.OPTIONS, new FakeHttpClient().options(), + Method.TRACE, new FakeHttpClient().trace(), + Method.PATCH, new FakeHttpClient().patch()); + + for (Map.Entry entry : map.entrySet()) { assertThat(entry.getValue().getMethod(), is(entry.getKey())); } } @@ -55,20 +56,20 @@ Http.Method.TRACE, new FakeHttpClient().trace(), @Test void testHttpMethodShortcutsWithUri() { String baseURI = "http://localhost:1234"; - Map map = Map.of( + Map map = Map.of( // use the method name as the path of the URL passed as argument to the http method shortcut // ex. http://localhost:1234/GET - Http.Method.GET, new FakeHttpClient().get(baseURI + "/" + Http.Method.GET.text()), - Http.Method.POST, new FakeHttpClient().post(baseURI + "/" + Http.Method.POST.text()), - Http.Method.PUT, new FakeHttpClient().put(baseURI + "/" + Http.Method.PUT.text()), - Http.Method.DELETE, new FakeHttpClient().delete(baseURI + "/" + Http.Method.DELETE.text()), - Http.Method.HEAD, new FakeHttpClient().head(baseURI + "/" + Http.Method.HEAD.text()), - Http.Method.OPTIONS, new FakeHttpClient().options(baseURI + "/" + Http.Method.OPTIONS.text()), - Http.Method.TRACE, new FakeHttpClient().trace(baseURI + "/" + Http.Method.TRACE.text()), - Http.Method.PATCH, new FakeHttpClient().patch(baseURI + "/" + Http.Method.PATCH.text()) + Method.GET, new FakeHttpClient().get(baseURI + "/" + Method.GET.text()), + Method.POST, new FakeHttpClient().post(baseURI + "/" + Method.POST.text()), + Method.PUT, new FakeHttpClient().put(baseURI + "/" + Method.PUT.text()), + Method.DELETE, new FakeHttpClient().delete(baseURI + "/" + Method.DELETE.text()), + Method.HEAD, new FakeHttpClient().head(baseURI + "/" + Method.HEAD.text()), + Method.OPTIONS, new FakeHttpClient().options(baseURI + "/" + Method.OPTIONS.text()), + Method.TRACE, new FakeHttpClient().trace(baseURI + "/" + Method.TRACE.text()), + Method.PATCH, new FakeHttpClient().patch(baseURI + "/" + Method.PATCH.text()) ); - for (Map.Entry entry : map.entrySet()) { + for (Map.Entry entry : map.entrySet()) { assertThat(entry.getValue().getMethod(), is(entry.getKey())); // validate that the URL path is the method name as passed on to the shortcut method during map init above assertThat(entry.getValue().getUri().getPath(), is("/" + entry.getKey().text())); @@ -77,20 +78,20 @@ Http.Method.PATCH, new FakeHttpClient().patch(baseURI + "/" + Http.Method.PATCH. static class FakeHttpClient implements HttpClient { @Override - public FakeHttpClientRequest method(Http.Method method) { + public FakeHttpClientRequest method(Method method) { return new FakeHttpClientRequest(method); } } static class FakeHttpClientRequest implements ClientRequest { - private final Http.Method method; + private final Method method; private URI uri; - FakeHttpClientRequest(Http.Method method) { + FakeHttpClientRequest(Method method) { this.method = method; } - public Http.Method getMethod() { + public Method getMethod() { return this.method; } @@ -140,7 +141,7 @@ public FakeHttpClientRequest maxRedirects(int maxRedirects) { } @Override - public FakeHttpClientRequest header(Http.Header header) { + public FakeHttpClientRequest header(Header header) { return this; } diff --git a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallChainBase.java b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallChainBase.java index 0296b8fa12f..4236cb7b6e6 100644 --- a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallChainBase.java +++ b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallChainBase.java @@ -32,11 +32,13 @@ import io.helidon.common.tls.Tls; import io.helidon.http.ClientRequestHeaders; import io.helidon.http.ClientResponseHeaders; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; -import io.helidon.http.Http.Method; import io.helidon.http.Http1HeadersParser; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.http.WritableHeaders; import io.helidon.http.encoding.ContentDecoder; import io.helidon.http.encoding.ContentEncodingContext; @@ -83,7 +85,7 @@ abstract class Http1CallChainBase implements WebClientService.Chain { } static void writeHeaders(Headers headers, BufferData bufferData, boolean validate) { - for (Http.Header header : headers) { + for (Header header : headers) { if (validate) { header.validate(); } @@ -97,7 +99,7 @@ static WebClientServiceResponse createServiceResponse(HttpClientConfig clientCon WebClientServiceRequest serviceRequest, ClientConnection connection, DataReader reader, - Http.Status responseStatus, + Status responseStatus, ClientResponseHeaders responseHeaders, CompletableFuture whenComplete) { WebClientServiceResponse.Builder builder = WebClientServiceResponse.builder(); @@ -138,7 +140,7 @@ public WebClientServiceResponse proceed(WebClientServiceRequest serviceRequest) writeBuffer.clear(); prologue(writeBuffer, serviceRequest, uri); - headers.setIfAbsent(Http.Headers.create(Http.HeaderNames.HOST, uri.authority())); + headers.setIfAbsent(HeaderValues.create(HeaderNames.HOST, uri.authority())); return doProceed(effectiveConnection, serviceRequest, headers, writer, reader, writeBuffer); } @@ -155,7 +157,7 @@ void prologue(BufferData nonEntityData, WebClientServiceRequest request, ClientU // When CONNECT, the first line contains the remote host:port, in the same way as the HOST header. nonEntityData.writeAscii(request.method().text() + " " - + request.headers().get(Http.HeaderNames.HOST).value() + + request.headers().get(HeaderNames.HOST).value() + " HTTP/1.1\r\n"); } else { // When proxy is set, ensure that the request uses absolute URI because of Section 5.1.2 Request-URI in @@ -207,7 +209,7 @@ CompletableFuture whenComplete() { protected WebClientServiceResponse readResponse(WebClientServiceRequest serviceRequest, ClientConnection connection, DataReader reader) { - Http.Status responseStatus; + Status responseStatus; try { responseStatus = Http1StatusParser.readStatus(reader, protocolConfig.maxStatusLineLength()); } catch (UncheckedIOException e) { @@ -243,7 +245,7 @@ private static InputStream inputStream(HttpClientConfig clientConfig, ContentDecoder decoder; - if (encodingSupport.contentDecodingEnabled() && responseHeaders.contains(Http.HeaderNames.CONTENT_ENCODING)) { + if (encodingSupport.contentDecodingEnabled() && responseHeaders.contains(HeaderNames.CONTENT_ENCODING)) { String contentEncoding = responseHeaders.get(HeaderNames.CONTENT_ENCODING).value(); if (encodingSupport.contentDecodingSupported(contentEncoding)) { decoder = encodingSupport.decoder(contentEncoding); @@ -258,7 +260,7 @@ private static InputStream inputStream(HttpClientConfig clientConfig, if (responseHeaders.contains(HeaderNames.CONTENT_LENGTH)) { long length = responseHeaders.contentLength().getAsLong(); return decoder.apply(new ContentLengthInputStream(helidonSocket, reader, whenComplete, response, length)); - } else if (responseHeaders.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED)) { + } else if (responseHeaders.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED)) { return new ChunkedInputStream(helidonSocket, reader, whenComplete, response); } else { // we assume the rest of the connection is entity (valid for HTTP/1.0, HTTP CONNECT method etc. @@ -266,16 +268,16 @@ private static InputStream inputStream(HttpClientConfig clientConfig, } } - private static boolean mayHaveEntity(Http.Status responseStatus, ClientResponseHeaders responseHeaders) { - if (responseHeaders.contains(Http.Headers.CONTENT_LENGTH_ZERO)) { + private static boolean mayHaveEntity(Status responseStatus, ClientResponseHeaders responseHeaders) { + if (responseHeaders.contains(HeaderValues.CONTENT_LENGTH_ZERO)) { return false; } - if (responseStatus == Http.Status.NO_CONTENT_204) { + if (responseStatus == Status.NO_CONTENT_204) { return false; } if (( responseHeaders.contains(HeaderNames.UPGRADE) - && !responseHeaders.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED))) { + && !responseHeaders.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED))) { // this is an upgrade response and there is no entity return false; } diff --git a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallEntityChain.java b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallEntityChain.java index 5284c48d33d..853c79194bc 100644 --- a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallEntityChain.java +++ b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallEntityChain.java @@ -22,7 +22,8 @@ import io.helidon.common.buffers.DataReader; import io.helidon.common.buffers.DataWriter; import io.helidon.http.ClientRequestHeaders; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.webclient.api.ClientConnection; import io.helidon.webclient.api.WebClientServiceRequest; import io.helidon.webclient.api.WebClientServiceResponse; @@ -51,7 +52,7 @@ public WebClientServiceResponse doProceed(ClientConnection connection, DataReader reader, BufferData writeBuffer) { - headers.set(Http.Headers.create(Http.HeaderNames.CONTENT_LENGTH, entity.length)); + headers.set(HeaderValues.create(HeaderNames.CONTENT_LENGTH, entity.length)); writeHeaders(headers, writeBuffer, protocolConfig().validateRequestHeaders()); // we have completed writing the headers diff --git a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallOutputStreamChain.java b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallOutputStreamChain.java index 57661ef6920..db7205b878a 100644 --- a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallOutputStreamChain.java +++ b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1CallOutputStreamChain.java @@ -31,9 +31,12 @@ import io.helidon.common.uri.UriInfo; import io.helidon.http.ClientRequestHeaders; import io.helidon.http.ClientResponseHeaders; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.Http1HeadersParser; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.http.WritableHeaders; import io.helidon.webclient.api.ClientConnection; import io.helidon.webclient.api.ClientRequest; @@ -99,10 +102,10 @@ WebClientServiceResponse doProceed(ClientConnection connection, throw new IllegalStateException("Output stream was not closed in handler"); } - Http.Status responseStatus; + Status responseStatus; try { responseStatus = Http1StatusParser.readStatus(reader, http1Client.protocolConfig().maxStatusLineLength()); - if (responseStatus == Http.Status.CONTINUE_100) { + if (responseStatus == Status.CONTINUE_100) { // skip the next empty end of line readHeaders(reader); responseStatus = Http1StatusParser.readStatus(reader, http1Client.protocolConfig().maxStatusLineLength()); @@ -124,7 +127,7 @@ WebClientServiceResponse doProceed(ClientConnection connection, if (originalRequest().followRedirects() && RedirectionProcessor.redirectionStatusCode(responseStatus)) { checkRedirectHeaders(responseHeaders); - URI newUri = URI.create(responseHeaders.get(Http.HeaderNames.LOCATION).value()); + URI newUri = URI.create(responseHeaders.get(HeaderNames.LOCATION).value()); ClientUri redirectUri = ClientUri.create(newUri); if (newUri.getHost() == null) { UriInfo resolvedUri = cos.lastRequest.resolvedUri(); @@ -133,7 +136,7 @@ WebClientServiceResponse doProceed(ClientConnection connection, redirectUri.port(resolvedUri.port()); } Http1ClientRequestImpl request = new Http1ClientRequestImpl(cos.lastRequest, - Http.Method.GET, + Method.GET, redirectUri, cos.lastRequest.properties()); Http1ClientResponseImpl clientResponse = RedirectionProcessor.invokeWithFollowRedirects(request, @@ -158,8 +161,8 @@ WebClientServiceResponse doProceed(ClientConnection connection, } private static void checkRedirectHeaders(Headers headerValues) { - if (!headerValues.contains(Http.HeaderNames.LOCATION)) { - throw new IllegalStateException("There is no " + Http.HeaderNames.LOCATION + " header present in the" + if (!headerValues.contains(HeaderNames.LOCATION)) { + throw new IllegalStateException("There is no " + HeaderNames.LOCATION + " header present in the" + " response! " + "It is not clear where to redirect."); } @@ -212,7 +215,7 @@ private ClientConnectionOutputStream(ClientConnection connection, this.clientConfig = clientConfig; this.protocolConfig = protocolConfig; this.contentLength = headers.contentLength().orElse(-1); - this.chunked = contentLength == -1 || headers.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED); + this.chunked = contentLength == -1 || headers.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED); this.request = request; this.originalRequest = originalRequest; this.lastRequest = originalRequest; @@ -275,9 +278,9 @@ public void close() throws IOException { } writer.write(terminating); } else { - headers.remove(Http.HeaderNames.TRANSFER_ENCODING); + headers.remove(HeaderNames.TRANSFER_ENCODING); if (noData) { - headers.set(Http.Headers.CONTENT_LENGTH_ZERO); + headers.set(HeaderValues.CONTENT_LENGTH_ZERO); contentLength = 0; } if (noData || firstPacket != null) { @@ -350,20 +353,20 @@ private void writeContent(BufferData buffer) throws IOException { private void sendPrologueAndHeader() { boolean expects100Continue = clientConfig.sendExpectContinue() && !noData; if (expects100Continue) { - headers.add(Http.Headers.EXPECT_100); + headers.add(HeaderValues.EXPECT_100); } if (chunked) { // Add chunked encoding, if there is no other transfer-encoding headers - if (!headers.contains(Http.HeaderNames.TRANSFER_ENCODING)) { - headers.set(Http.Headers.TRANSFER_ENCODING_CHUNKED); + if (!headers.contains(HeaderNames.TRANSFER_ENCODING)) { + headers.set(HeaderValues.TRANSFER_ENCODING_CHUNKED); } else { // Add chunked encoding, if it's not part of existing transfer-encoding headers - if (!headers.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED)) { - headers.add(Http.Headers.TRANSFER_ENCODING_CHUNKED); + if (!headers.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED)) { + headers.add(HeaderValues.TRANSFER_ENCODING_CHUNKED); } } - headers.remove(Http.HeaderNames.CONTENT_LENGTH); + headers.remove(HeaderNames.CONTENT_LENGTH); } if (LOGGER.isLoggable(System.Logger.Level.TRACE)) { @@ -381,7 +384,7 @@ private void sendPrologueAndHeader() { whenSent.complete(request); if (expects100Continue) { - Http.Status responseStatus; + Status responseStatus; try { connection.readTimeout(originalRequest.readContinueTimeout()); @@ -394,17 +397,17 @@ private void sendPrologueAndHeader() { } finally { connection.readTimeout(originalRequest.readTimeout()); } - if (responseStatus == Http.Status.CONTINUE_100) { + if (responseStatus == Status.CONTINUE_100) { // there is the status and (usually) empty headers. We ignore such headers Http1HeadersParser.readHeaders(reader, protocolConfig.maxHeaderSize(), protocolConfig.validateResponseHeaders()); } if (responseStatus == null) { - responseStatus = Http.Status.CONTINUE_100; + responseStatus = Status.CONTINUE_100; } - if (responseStatus != Http.Status.CONTINUE_100) { + if (responseStatus != Status.CONTINUE_100) { WritableHeaders responseHeaders = Http1HeadersParser.readHeaders(reader, protocolConfig.maxHeaderSize(), protocolConfig.validateResponseHeaders()); @@ -433,17 +436,17 @@ private void sendPrologueAndHeader() { } } - private void redirect(Http.Status lastStatus, WritableHeaders headerValues) { - String redirectedUri = headerValues.get(Http.HeaderNames.LOCATION).value(); + private void redirect(Status lastStatus, WritableHeaders headerValues) { + String redirectedUri = headerValues.get(HeaderNames.LOCATION).value(); ClientUri lastUri = originalRequest.uri(); - Http.Method method; + Method method; boolean sendEntity; - if (lastStatus == Http.Status.TEMPORARY_REDIRECT_307 - || lastStatus == Http.Status.PERMANENT_REDIRECT_308) { + if (lastStatus == Status.TEMPORARY_REDIRECT_307 + || lastStatus == Status.PERMANENT_REDIRECT_308) { method = originalRequest.method(); sendEntity = true; } else { - method = Http.Method.GET; + method = Method.GET; sendEntity = false; } for (int i = 0; i < clientConfig.maxRedirects(); i++) { @@ -463,8 +466,8 @@ private void redirect(Http.Status lastStatus, WritableHeaders headerValues) { Http1ClientResponseImpl response; if (sendEntity) { response = (Http1ClientResponseImpl) clientRequest - .header(Http.Headers.EXPECT_100) - .header(Http.Headers.TRANSFER_ENCODING_CHUNKED) + .header(HeaderValues.EXPECT_100) + .header(HeaderValues.TRANSFER_ENCODING_CHUNKED) .readTimeout(originalRequest.readContinueTimeout()) .request(); response.connection().readTimeout(originalRequest.readTimeout()); @@ -481,12 +484,12 @@ private void redirect(Http.Status lastStatus, WritableHeaders headerValues) { if (RedirectionProcessor.redirectionStatusCode(response.status())) { try (response) { checkRedirectHeaders(response.headers()); - if (response.status() != Http.Status.TEMPORARY_REDIRECT_307 - && response.status() != Http.Status.PERMANENT_REDIRECT_308) { - method = Http.Method.GET; + if (response.status() != Status.TEMPORARY_REDIRECT_307 + && response.status() != Status.PERMANENT_REDIRECT_308) { + method = Method.GET; sendEntity = false; } - redirectedUri = response.headers().get(Http.HeaderNames.LOCATION).value(); + redirectedUri = response.headers().get(HeaderNames.LOCATION).value(); } } else { if (!sendEntity) { diff --git a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientImpl.java b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientImpl.java index f925f02bf77..101b3980945 100644 --- a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientImpl.java +++ b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientImpl.java @@ -16,7 +16,7 @@ package io.helidon.webclient.http1; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webclient.api.ClientRequest; import io.helidon.webclient.api.ClientUri; import io.helidon.webclient.api.FullClientRequest; @@ -41,7 +41,7 @@ class Http1ClientImpl implements Http1Client, HttpClientSpi { } @Override - public Http1ClientRequest method(Http.Method method) { + public Http1ClientRequest method(Method method) { ClientUri clientUri = clientConfig.baseUri() .map(ClientUri::create) // create from base config .orElseGet(ClientUri::create); // create as empty diff --git a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientRequestImpl.java b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientRequestImpl.java index 017bba3ba2d..7c995aa35c1 100644 --- a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientRequestImpl.java +++ b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientRequestImpl.java @@ -22,7 +22,10 @@ import io.helidon.common.GenericType; import io.helidon.common.buffers.BufferData; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.http.media.EntityWriter; import io.helidon.http.media.InstanceWriter; import io.helidon.http.media.MediaContext; @@ -36,7 +39,7 @@ class Http1ClientRequestImpl extends ClientRequestBase properties) { super(http1Client.clientConfig(), @@ -49,7 +52,7 @@ class Http1ClientRequestImpl extends ClientRequestBase properties) { this(request.http1Client, @@ -125,10 +128,10 @@ public Http1ClientResponse doOutputStream(OutputStreamHandler streamHandler) { @Override public UpgradeResponse upgrade(String protocol) { - if (!headers().contains(Http.HeaderNames.UPGRADE)) { - headers().set(Http.HeaderNames.UPGRADE, protocol); + if (!headers().contains(HeaderNames.UPGRADE)) { + headers().set(HeaderNames.UPGRADE, protocol); } - Http.Header requestedUpgrade = headers().get(Http.HeaderNames.UPGRADE); + Header requestedUpgrade = headers().get(HeaderNames.UPGRADE); Http1ClientResponseImpl response; if (followRedirects()) { @@ -137,7 +140,7 @@ public UpgradeResponse upgrade(String protocol) { response = invokeRequestWithEntity(BufferData.EMPTY_BYTES); } - if (response.status() == Http.Status.SWITCHING_PROTOCOLS_101) { + if (response.status() == Status.SWITCHING_PROTOCOLS_101) { // yep, this is the response we want if (response.headers().contains(requestedUpgrade)) { if (LOGGER.isLoggable(System.Logger.Level.TRACE)) { diff --git a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientResponseImpl.java b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientResponseImpl.java index 021b25b50a6..a9d22d96192 100644 --- a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientResponseImpl.java +++ b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ClientResponseImpl.java @@ -28,10 +28,10 @@ import io.helidon.common.media.type.ParserMode; import io.helidon.http.ClientRequestHeaders; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; -import io.helidon.http.Http.Headers; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Http1HeadersParser; +import io.helidon.http.Status; import io.helidon.http.WritableHeaders; import io.helidon.http.media.MediaContext; import io.helidon.http.media.ReadableEntity; @@ -52,7 +52,7 @@ class Http1ClientResponseImpl implements Http1ClientResponse { private final AtomicBoolean closed = new AtomicBoolean(); - private final Http.Status responseStatus; + private final Status responseStatus; private final ClientRequestHeaders requestHeaders; private final ClientResponseHeaders responseHeaders; private final InputStream inputStream; @@ -70,7 +70,7 @@ class Http1ClientResponseImpl implements Http1ClientResponse { private WritableHeaders trailers; Http1ClientResponseImpl(HttpClientConfig clientConfig, - Http.Status responseStatus, + Status responseStatus, ClientRequestHeaders requestHeaders, ClientResponseHeaders responseHeaders, ClientConnection connection, @@ -91,10 +91,10 @@ class Http1ClientResponseImpl implements Http1ClientResponse { if (responseHeaders.contains(HeaderNames.CONTENT_LENGTH)) { this.entityLength = Long.parseLong(responseHeaders.get(HeaderNames.CONTENT_LENGTH).value()); - } else if (responseHeaders.contains(Headers.TRANSFER_ENCODING_CHUNKED)) { + } else if (responseHeaders.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED)) { this.entityLength = -1; } - if (responseHeaders.contains(Http.HeaderNames.TRAILER)) { + if (responseHeaders.contains(HeaderNames.TRAILER)) { this.hasTrailers = true; this.trailerNames = responseHeaders.get(HeaderNames.TRAILER).allValues(true); } else { @@ -104,7 +104,7 @@ class Http1ClientResponseImpl implements Http1ClientResponse { } @Override - public Http.Status status() { + public Status status() { return responseStatus; } @@ -122,7 +122,7 @@ public ReadableEntity entity() { public void close() { if (closed.compareAndSet(false, true)) { try { - if (headers().contains(Http.Headers.CONNECTION_CLOSE)) { + if (headers().contains(HeaderValues.CONNECTION_CLOSE)) { connection.closeResource(); } else { if (entityFullyRead || entityLength == 0) { diff --git a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ConnectionCache.java b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ConnectionCache.java index fe44b5f84c1..74eb18af7e7 100644 --- a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ConnectionCache.java +++ b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1ConnectionCache.java @@ -25,7 +25,7 @@ import io.helidon.common.tls.Tls; import io.helidon.http.ClientRequestHeaders; -import io.helidon.http.Http; +import io.helidon.http.HeaderValues; import io.helidon.http.WritableHeaders; import io.helidon.webclient.api.ClientConnection; import io.helidon.webclient.api.ClientUri; @@ -72,17 +72,17 @@ ClientConnection connection(Http1ClientImpl http1Client, } private boolean handleKeepAlive(boolean defaultKeepAlive, WritableHeaders headers) { - if (headers.contains(Http.Headers.CONNECTION_CLOSE)) { + if (headers.contains(HeaderValues.CONNECTION_CLOSE)) { return false; } if (defaultKeepAlive) { - headers.setIfAbsent(Http.Headers.CONNECTION_KEEP_ALIVE); + headers.setIfAbsent(HeaderValues.CONNECTION_KEEP_ALIVE); return true; } - if (headers.contains(Http.Headers.CONNECTION_KEEP_ALIVE)) { + if (headers.contains(HeaderValues.CONNECTION_KEEP_ALIVE)) { return true; } - headers.set(Http.Headers.CONNECTION_CLOSE); + headers.set(HeaderValues.CONNECTION_CLOSE); return false; } diff --git a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1StatusParser.java b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1StatusParser.java index c27be73f9e8..c80265b57a7 100644 --- a/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1StatusParser.java +++ b/webclient/http1/src/main/java/io/helidon/webclient/http1/Http1StatusParser.java @@ -21,7 +21,7 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.buffers.Bytes; import io.helidon.common.buffers.DataReader; -import io.helidon.http.Http; +import io.helidon.http.Status; /** * Parser of HTTP/1.0 or HTTP/1.1 response status. @@ -44,7 +44,7 @@ private Http1StatusParser() { * the reader, depending on its * implementation */ - public static Http.Status readStatus(DataReader reader, int maxLength) { + public static Status readStatus(DataReader reader, int maxLength) { int newLine = reader.findNewLine(maxLength); if (newLine == maxLength) { throw new IllegalStateException("HTTP Response did not contain HTTP status line. Line: \n" @@ -92,7 +92,7 @@ public static Http.Status readStatus(DataReader reader, int maxLength) { reader.skip(2); // skip the last CRLF try { - return Http.Status.create(Integer.parseInt(code), phrase); + return Status.create(Integer.parseInt(code), phrase); } catch (NumberFormatException e) { throw new IllegalStateException("HTTP Response did not contain HTTP status line. Line HTTP/1.0 or HTTP/1.1 \n" + BufferData.create(code.getBytes(StandardCharsets.US_ASCII)) + "\n" diff --git a/webclient/http1/src/main/java/io/helidon/webclient/http1/RedirectionProcessor.java b/webclient/http1/src/main/java/io/helidon/webclient/http1/RedirectionProcessor.java index 21f16137e74..2b310581490 100644 --- a/webclient/http1/src/main/java/io/helidon/webclient/http1/RedirectionProcessor.java +++ b/webclient/http1/src/main/java/io/helidon/webclient/http1/RedirectionProcessor.java @@ -19,7 +19,9 @@ import java.net.URI; import io.helidon.common.buffers.BufferData; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.ClientUri; class RedirectionProcessor { @@ -27,8 +29,8 @@ class RedirectionProcessor { private RedirectionProcessor() { } - static boolean redirectionStatusCode(Http.Status status) { - return status.family() == Http.Status.Family.REDIRECTION; + static boolean redirectionStatusCode(Status status) { + return status.family() == Status.Family.REDIRECTION; } static Http1ClientResponseImpl invokeWithFollowRedirects(Http1ClientRequestImpl request, byte[] entity) { @@ -46,12 +48,12 @@ static Http1ClientResponseImpl invokeWithFollowRedirects(Http1ClientRequestImpl return clientResponse; } try (clientResponse) { - if (!clientResponse.headers().contains(Http.HeaderNames.LOCATION)) { - throw new IllegalStateException("There is no " + Http.HeaderNames.LOCATION + if (!clientResponse.headers().contains(HeaderNames.LOCATION)) { + throw new IllegalStateException("There is no " + HeaderNames.LOCATION + " header present in the response! " + "It is not clear where to redirect."); } - String redirectedUri = clientResponse.headers().get(Http.HeaderNames.LOCATION).value(); + String redirectedUri = clientResponse.headers().get(HeaderNames.LOCATION).value(); URI newUri = URI.create(redirectedUri); ClientUri redirectUri = ClientUri.create(newUri); @@ -67,8 +69,8 @@ static Http1ClientResponseImpl invokeWithFollowRedirects(Http1ClientRequestImpl redirectUri.port(resolvedUri.port()); } //Method and entity is required to be the same as with original request with 307 and 308 requests - if (clientResponse.status() == Http.Status.TEMPORARY_REDIRECT_307 - || clientResponse.status() == Http.Status.PERMANENT_REDIRECT_308) { + if (clientResponse.status() == Status.TEMPORARY_REDIRECT_307 + || clientResponse.status() == Status.PERMANENT_REDIRECT_308) { clientRequest = new Http1ClientRequestImpl(clientRequest, clientRequest.method(), redirectUri, @@ -77,7 +79,7 @@ static Http1ClientResponseImpl invokeWithFollowRedirects(Http1ClientRequestImpl //It is possible to change to GET and send no entity with all other redirect codes entityToBeSent = BufferData.EMPTY_BYTES; //We do not want to send entity after this redirect clientRequest = new Http1ClientRequestImpl(clientRequest, - Http.Method.GET, + Method.GET, redirectUri, request.properties()); } diff --git a/webclient/http1/src/main/java/io/helidon/webclient/http1/UpgradeResponse.java b/webclient/http1/src/main/java/io/helidon/webclient/http1/UpgradeResponse.java index 8a4c8ec076a..f8c3462e5d8 100644 --- a/webclient/http1/src/main/java/io/helidon/webclient/http1/UpgradeResponse.java +++ b/webclient/http1/src/main/java/io/helidon/webclient/http1/UpgradeResponse.java @@ -19,7 +19,7 @@ import java.util.NoSuchElementException; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.http.media.ReadableEntity; import io.helidon.webclient.api.ClientConnection; import io.helidon.webclient.api.ClientUri; @@ -108,7 +108,7 @@ private static class NoCloseResponse implements HttpClientResponse { } @Override - public Http.Status status() { + public Status status() { return delegate.status(); } diff --git a/webclient/http1/src/test/java/io/helidon/webclient/http1/Http1ClientTest.java b/webclient/http1/src/test/java/io/helidon/webclient/http1/Http1ClientTest.java index f3c35f5281f..30fd9b0e565 100644 --- a/webclient/http1/src/test/java/io/helidon/webclient/http1/Http1ClientTest.java +++ b/webclient/http1/src/test/java/io/helidon/webclient/http1/Http1ClientTest.java @@ -37,9 +37,14 @@ import io.helidon.common.buffers.DataWriter; import io.helidon.common.socket.HelidonSocket; import io.helidon.common.socket.PeerInfo; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.Http1HeadersParser; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityReader; import io.helidon.http.media.EntityWriter; @@ -69,11 +74,11 @@ class Http1ClientTest { public static final String VALID_HEADER_NAME = "Valid-Header-Name"; public static final String BAD_HEADER_PATH = "/badHeader"; public static final String HEADER_NAME_VALUE_DELIMETER = "->"; - private static final Http.Header REQ_CHUNKED_HEADER = Http.Headers.create( - Http.HeaderNames.create("X-Req-Chunked"), "true"); - private static final Http.Header REQ_EXPECT_100_HEADER_NAME = Http.Headers.create( - Http.HeaderNames.create("X-Req-Expect100"), "true"); - private static final Http.HeaderName REQ_CONTENT_LENGTH_HEADER_NAME = Http.HeaderNames.create("X-Req-ContentLength"); + private static final Header REQ_CHUNKED_HEADER = HeaderValues.create( + HeaderNames.create("X-Req-Chunked"), "true"); + private static final Header REQ_EXPECT_100_HEADER_NAME = HeaderValues.create( + HeaderNames.create("X-Req-Expect100"), "true"); + private static final HeaderName REQ_CONTENT_LENGTH_HEADER_NAME = HeaderNames.create("X-Req-ContentLength"); private static final long NO_CONTENT_LENGTH = -1L; private static final Http1Client client = Http1Client.builder() .sendExpectContinue(false) @@ -135,7 +140,7 @@ void testMediaContext() { void testChunk() { String[] requestEntityParts = {"First", "Second", "Third"}; - Http1ClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test"); + Http1ClientRequest request = getHttp1ClientRequest(Method.PUT, "/test"); request.connection(new FakeHttp1ClientConnection()); Http1ClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); @@ -147,8 +152,8 @@ void testNoChunk() { String[] requestEntityParts = {"First"}; long contentLength = requestEntityParts[0].length(); - Http1ClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test") - .header(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(contentLength)); + Http1ClientRequest request = getHttp1ClientRequest(Method.PUT, "/test") + .header(HeaderNames.CONTENT_LENGTH, String.valueOf(contentLength)); request.connection(new FakeHttp1ClientConnection()); Http1ClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); @@ -159,7 +164,7 @@ void testNoChunk() { void testForcedChunkNoContentLength() { String[] requestEntityParts = {"First"}; - Http1ClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test"); + Http1ClientRequest request = getHttp1ClientRequest(Method.PUT, "/test"); request.connection(new FakeHttp1ClientConnection()); Http1ClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); @@ -170,8 +175,8 @@ void testForcedChunkNoContentLength() { void testForcedChunkTransferEncodingChunked() { String[] requestEntityParts = {"First"}; - Http1ClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test") - .header(Http.Headers.TRANSFER_ENCODING_CHUNKED); + Http1ClientRequest request = getHttp1ClientRequest(Method.PUT, "/test") + .header(HeaderValues.TRANSFER_ENCODING_CHUNKED); request.connection(new FakeHttp1ClientConnection()); Http1ClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); @@ -214,7 +219,7 @@ void testHeadMethod() { @Test void testSkipUrlEncoding() { //Fill with chars which should be encoded - Http1ClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/ěščžř") + Http1ClientRequest request = getHttp1ClientRequest(Method.PUT, "/ěščžř") .queryParam("specialChar+", "someValue,").fragment("someFragment,"); URI uri = request.resolvedUri().toUri(); assertThat(uri.getRawPath(), is("/%C4%9B%C5%A1%C4%8D%C5%BE%C5%99")); @@ -264,7 +269,7 @@ void testRelativeUris(ProxyConfiguration proxyConfig, RelativeUrisValue relative ? getHttp1ClientResponseFromOutputStream(request, new String[] {"Sending Something"}) : request.submit("Sending Something"); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); StringTokenizer st = new StringTokenizer(connection.getPrologue(), " "); // skip method part st.nextToken(); @@ -295,11 +300,11 @@ void testHeaderValues(List headerValues, boolean expectsValid) { }) .build(); Http1ClientRequest request = clientValidateRequestHeaders.get("http://localhost:" + dummyPort + "/test"); - request.header(Http.Headers.create("HeaderName", headerValues)); + request.header(HeaderValues.create("HeaderName", headerValues)); request.connection(new FakeHttp1ClientConnection()); if (expectsValid) { HttpClientResponse response = request.request(); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } else { assertThrows(IllegalArgumentException.class, () -> request.request()); } @@ -307,7 +312,7 @@ void testHeaderValues(List headerValues, boolean expectsValid) { @ParameterizedTest @MethodSource("headers") - void testHeaders(Http.Header header, boolean expectsValid) { + void testHeaders(Header header, boolean expectsValid) { Http1Client clientValidateRequestHeaders = Http1Client.builder() .protocolConfig(it -> { it.validateRequestHeaders(true); @@ -319,7 +324,7 @@ void testHeaders(Http.Header header, boolean expectsValid) { request.header(header); if (expectsValid) { HttpClientResponse response = request.request(); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } else { assertThrows(IllegalArgumentException.class, () -> request.request()); } @@ -327,7 +332,7 @@ void testHeaders(Http.Header header, boolean expectsValid) { @ParameterizedTest @MethodSource("headers") - void testDisableHeaderValidation(Http.Header header, boolean expectsValid) { + void testDisableHeaderValidation(Header header, boolean expectsValid) { Http1Client clientWithDisabledHeaderValidation = Http1Client.builder() .protocolConfig(it -> { it.validateRequestHeaders(false); @@ -339,9 +344,9 @@ void testDisableHeaderValidation(Http.Header header, boolean expectsValid) { request.connection(new FakeHttp1ClientConnection()); HttpClientResponse response = request.submit("Sending Something"); if (expectsValid) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } else { - assertThat(response.status(), is(Http.Status.BAD_REQUEST_400)); + assertThat(response.status(), is(Status.BAD_REQUEST_400)); } } @@ -359,8 +364,8 @@ void testHeadersFromResponse(String headerName, String headerValue, boolean expe String headerNameAndValue = headerName + HEADER_NAME_VALUE_DELIMETER + headerValue; if (expectsValid) { HttpClientResponse response = request.submit(headerNameAndValue); - assertThat(response.status(), is(Http.Status.OK_200)); - String responseHeaderValue = response.headers().get(Http.HeaderNames.create(headerName)).values(); + assertThat(response.status(), is(Status.OK_200)); + String responseHeaderValue = response.headers().get(HeaderNames.create(headerName)).values(); assertThat(responseHeaderValue, is(headerValue.trim())); } else { assertThrows(IllegalArgumentException.class, () -> request.submit(headerNameAndValue)); @@ -379,8 +384,8 @@ void testDisableValidationForHeadersFromResponse(String headerName, String heade Http1ClientRequest request = clientWithNoHeaderValidation.put("http://localhost:" + dummyPort + BAD_HEADER_PATH); request.connection(new FakeHttp1ClientConnection()); Http1ClientResponse response = request.submit(headerName + HEADER_NAME_VALUE_DELIMETER + headerValue); - assertThat(response.status(), is(Http.Status.OK_200)); - String responseHeaderValue = response.headers().get(Http.HeaderNames.create(headerName)).values(); + assertThat(response.status(), is(Status.OK_200)); + String responseHeaderValue = response.headers().get(HeaderNames.create(headerName)).values(); assertThat(responseHeaderValue, is(headerValue.trim())); } @@ -392,7 +397,7 @@ private static void validateSuccessfulResponse(Http1Client client, ClientConnect } Http1ClientResponse response = request.submit(requestEntity); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity().as(String.class), is(requestEntity)); } @@ -409,7 +414,7 @@ private static void validateFailedResponse(Http1Client client, ClientConnection } private static void validateChunkTransfer(Http1ClientResponse response, boolean chunked, long contentLength, String entity) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); if (contentLength == NO_CONTENT_LENGTH) { assertThat(response.headers(), noHeader(REQ_CONTENT_LENGTH_HEADER_NAME)); } else { @@ -424,7 +429,7 @@ private static void validateChunkTransfer(Http1ClientResponse response, boolean assertThat(responseEntity, is(entity)); } - private static Http1ClientRequest getHttp1ClientRequest(Http.Method method, String uriPath) { + private static Http1ClientRequest getHttp1ClientRequest(Method method, String uriPath) { return client.method(method).uri("http://localhost:" + dummyPort + uriPath); } @@ -533,31 +538,31 @@ private static Stream headerValues() { private static Stream headers() { return Stream.of( // Valid headers - arguments(Http.Headers.ACCEPT_RANGES_BYTES, true), - arguments(Http.Headers.CONNECTION_KEEP_ALIVE, true), - arguments(Http.Headers.CONTENT_TYPE_TEXT_PLAIN, true), - arguments(Http.Headers.ACCEPT_TEXT, true), - arguments(Http.Headers.CACHE_NO_CACHE, true), - arguments(Http.Headers.TE_TRAILERS, true), - arguments(Http.Headers.create("!#$Custom~%&\'*Header+^`|", "!Header\tValue~"), true), - arguments(Http.Headers.create("Custom_0-9_a-z_A-Z_Header", + arguments(HeaderValues.ACCEPT_RANGES_BYTES, true), + arguments(HeaderValues.CONNECTION_KEEP_ALIVE, true), + arguments(HeaderValues.CONTENT_TYPE_TEXT_PLAIN, true), + arguments(HeaderValues.ACCEPT_TEXT, true), + arguments(HeaderValues.CACHE_NO_CACHE, true), + arguments(HeaderValues.TE_TRAILERS, true), + arguments(HeaderValues.create("!#$Custom~%&\'*Header+^`|", "!Header\tValue~"), true), + arguments(HeaderValues.create("Custom_0-9_a-z_A-Z_Header", "\u0080Header Value\u00ff"), true), // Invalid headers - arguments(Http.Headers.create(VALID_HEADER_NAME, "H\u001ceaderValue1"), false), - arguments(Http.Headers.create(VALID_HEADER_NAME, + arguments(HeaderValues.create(VALID_HEADER_NAME, "H\u001ceaderValue1"), false), + arguments(HeaderValues.create(VALID_HEADER_NAME, "HeaderValue1, Header\u007fValue"), false), - arguments(Http.Headers.create(VALID_HEADER_NAME, + arguments(HeaderValues.create(VALID_HEADER_NAME, "HeaderValue1\u001f, HeaderValue2"), false), - arguments(Http.Headers.create("Header\u001aName", VALID_HEADER_VALUE), false), - arguments(Http.Headers.create("Header\u000EName", VALID_HEADER_VALUE), false), - arguments(Http.Headers.create("HeaderName\r\n", VALID_HEADER_VALUE), false), - arguments(Http.Headers.create("HeaderName\u00FF\u0124", VALID_HEADER_VALUE), false), - arguments(Http.Headers.create("(Header:Name)", VALID_HEADER_VALUE), false), - arguments(Http.Headers.create("", VALID_HEADER_VALUE), false), - arguments(Http.Headers.create("{Header=Name}", VALID_HEADER_VALUE), false), - arguments(Http.Headers.create("\"HeaderName\"", VALID_HEADER_VALUE), false), - arguments(Http.Headers.create("[\\HeaderName]", VALID_HEADER_VALUE), false), - arguments(Http.Headers.create("@Header,Name;", VALID_HEADER_VALUE), false) + arguments(HeaderValues.create("Header\u001aName", VALID_HEADER_VALUE), false), + arguments(HeaderValues.create("Header\u000EName", VALID_HEADER_VALUE), false), + arguments(HeaderValues.create("HeaderName\r\n", VALID_HEADER_VALUE), false), + arguments(HeaderValues.create("HeaderName\u00FF\u0124", VALID_HEADER_VALUE), false), + arguments(HeaderValues.create("(Header:Name)", VALID_HEADER_VALUE), false), + arguments(HeaderValues.create("", VALID_HEADER_VALUE), false), + arguments(HeaderValues.create("{Header=Name}", VALID_HEADER_VALUE), false), + arguments(HeaderValues.create("\"HeaderName\"", VALID_HEADER_VALUE), false), + arguments(HeaderValues.create("[\\HeaderName]", VALID_HEADER_VALUE), false), + arguments(HeaderValues.create("@Header,Name;", VALID_HEADER_VALUE), false) ); } @@ -753,8 +758,8 @@ private void webServerHandle() { WritableHeaders reqHeaders = null; try { reqHeaders = Http1HeadersParser.readHeaders(serverReader, 16384, false); - for (Iterator it = reqHeaders.iterator(); it.hasNext(); ) { - Http.Header header = it.next(); + for (Iterator
it = reqHeaders.iterator(); it.hasNext(); ) { + Header header = it.next(); header.validate(); } } catch (IllegalArgumentException e) { @@ -763,9 +768,9 @@ private void webServerHandle() { int entitySize = 0; if (!requestFailed) { - if (reqHeaders.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED)) { + if (reqHeaders.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED)) { // Send 100-Continue if requested - if (reqHeaders.contains(Http.Headers.EXPECT_100)) { + if (reqHeaders.contains(HeaderValues.EXPECT_100)) { serverWriter.write( BufferData.create("HTTP/1.1 100 Continue\r\n\r\n".getBytes(StandardCharsets.UTF_8))); } @@ -783,8 +788,8 @@ private void webServerHandle() { serverReader.skip(2); entitySize += chunkLength; } - } else if (reqHeaders.contains(Http.HeaderNames.CONTENT_LENGTH)) { - entitySize = reqHeaders.get(Http.HeaderNames.CONTENT_LENGTH).get(int.class); + } else if (reqHeaders.contains(HeaderNames.CONTENT_LENGTH)) { + entitySize = reqHeaders.get(HeaderNames.CONTENT_LENGTH).get(int.class); if (entitySize > 0) { entity.write(serverReader.getBuffer(entitySize)); } @@ -792,17 +797,17 @@ private void webServerHandle() { } WritableHeaders resHeaders = WritableHeaders.create(); - resHeaders.add(Http.Headers.CONNECTION_KEEP_ALIVE); + resHeaders.add(HeaderValues.CONNECTION_KEEP_ALIVE); if (reqHeaders != null) { // Send headers that can be validated if Expect-100-Continue, Content_Length, and Chunked request headers exist - if (reqHeaders.contains(Http.Headers.EXPECT_100)) { + if (reqHeaders.contains(HeaderValues.EXPECT_100)) { resHeaders.set(REQ_EXPECT_100_HEADER_NAME); } - if (reqHeaders.contains(Http.HeaderNames.CONTENT_LENGTH)) { - resHeaders.set(REQ_CONTENT_LENGTH_HEADER_NAME, reqHeaders.get(Http.HeaderNames.CONTENT_LENGTH).get()); + if (reqHeaders.contains(HeaderNames.CONTENT_LENGTH)) { + resHeaders.set(REQ_CONTENT_LENGTH_HEADER_NAME, reqHeaders.get(HeaderNames.CONTENT_LENGTH).get()); } - if (reqHeaders.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED)) { + if (reqHeaders.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED)) { resHeaders.set(REQ_CHUNKED_HEADER); } } @@ -810,16 +815,16 @@ private void webServerHandle() { // if prologue contains "/badHeader" path, send back the entity (name and value delimited by ->) as a header if (getPrologue().contains(BAD_HEADER_PATH)) { String[] header = entity.readString(entitySize, StandardCharsets.US_ASCII).split(HEADER_NAME_VALUE_DELIMETER); - resHeaders.add(Http.Headers.create(header[0], header[1])); + resHeaders.add(HeaderValues.create(header[0], header[1])); } String responseMessage = !requestFailed ? "HTTP/1.1 200 OK\r\n" : "HTTP/1.1 400 Bad Request\r\n"; serverWriter.write(BufferData.create(responseMessage.getBytes(StandardCharsets.UTF_8))); // Send the headers - resHeaders.add(Http.HeaderNames.CONTENT_LENGTH, Integer.toString(entitySize)); + resHeaders.add(HeaderNames.CONTENT_LENGTH, Integer.toString(entitySize)); BufferData entityBuffer = BufferData.growing(128); - for (Http.Header header : resHeaders) { + for (Header header : resHeaders) { header.writeHttp1Header(entityBuffer); } entityBuffer.write(Bytes.CR_BYTE); diff --git a/webclient/http1/src/test/java/io/helidon/webclient/http1/Http1StatusParserTest.java b/webclient/http1/src/test/java/io/helidon/webclient/http1/Http1StatusParserTest.java index 52f33aba42b..ad1825c37f0 100644 --- a/webclient/http1/src/test/java/io/helidon/webclient/http1/Http1StatusParserTest.java +++ b/webclient/http1/src/test/java/io/helidon/webclient/http1/Http1StatusParserTest.java @@ -16,14 +16,14 @@ package io.helidon.webclient.http1; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertThrows; - import io.helidon.common.buffers.DataReader; -import io.helidon.http.Http.Status; +import io.helidon.http.Status; import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + class Http1StatusParserTest { @Test diff --git a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2CallChainBase.java b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2CallChainBase.java index 7f4b8a57887..13a1c8b3ef1 100644 --- a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2CallChainBase.java +++ b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2CallChainBase.java @@ -27,7 +27,11 @@ import io.helidon.common.tls.Tls; import io.helidon.http.ClientRequestHeaders; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.http.encoding.ContentDecoder; import io.helidon.http.encoding.ContentEncodingContext; import io.helidon.http.http2.Http2Headers; @@ -42,7 +46,7 @@ import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webclient.spi.WebClientService; -import static io.helidon.http.Http.HeaderNames.CONTENT_ENCODING; +import static io.helidon.http.HeaderNames.CONTENT_ENCODING; import static io.helidon.webclient.api.ClientRequestBase.USER_AGENT_HEADER; abstract class Http2CallChainBase implements WebClientService.Chain { @@ -56,7 +60,7 @@ abstract class Http2CallChainBase implements WebClientService.Chain { private Http2ClientStream stream; private HttpClientResponse response; private ClientRequestHeaders requestHeaders; - private Http.Status responseStatus; + private Status responseStatus; Http2CallChainBase(Http2ClientImpl http2Client, Http2ClientRequestImpl clientRequest, @@ -75,8 +79,8 @@ public WebClientServiceResponse proceed(WebClientServiceRequest serviceRequest) ClientUri uri = serviceRequest.uri(); requestHeaders = serviceRequest.headers(); - requestHeaders.setIfAbsent(Http.Headers.create(Http.HeaderNames.HOST, uri.authority())); - requestHeaders.remove(Http.HeaderNames.CONNECTION, LogHeaderConsumer.INSTANCE); + requestHeaders.setIfAbsent(HeaderValues.create(HeaderNames.HOST, uri.authority())); + requestHeaders.remove(HeaderNames.CONNECTION, LogHeaderConsumer.INSTANCE); requestHeaders.setIfAbsent(USER_AGENT_HEADER); ConnectionKey connectionKey = connectionKey(serviceRequest); @@ -104,7 +108,7 @@ ClientRequestHeaders requestHeaders() { return requestHeaders; } - Http.Status responseStatus() { + Status responseStatus() { return responseStatus; } @@ -184,7 +188,7 @@ private ContentDecoder contentDecoder(ClientResponseHeaders responseHeaders) { return ContentDecoder.NO_OP; } - protected Http2Headers prepareHeaders(Http.Method method, ClientRequestHeaders headers, ClientUri uri) { + protected Http2Headers prepareHeaders(Method method, ClientRequestHeaders headers, ClientUri uri) { Http2Headers h2Headers = Http2Headers.create(headers); h2Headers.method(method); h2Headers.path(uri.pathWithQueryAndFragment()); @@ -225,12 +229,12 @@ private ConnectionKey connectionKey(WebClientServiceRequest serviceRequest) { clientRequest.proxy()); } - private static final class LogHeaderConsumer implements Consumer { + private static final class LogHeaderConsumer implements Consumer
{ private static final System.Logger LOGGER = System.getLogger(LogHeaderConsumer.class.getName()); private static final LogHeaderConsumer INSTANCE = new LogHeaderConsumer(); @Override - public void accept(Http.Header httpHeader) { + public void accept(Header httpHeader) { if (LOGGER.isLoggable(System.Logger.Level.DEBUG)) { LOGGER.log(System.Logger.Level.DEBUG, "HTTP/2 request contains wrong header, removing {0}", httpHeader); diff --git a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2CallEntityChain.java b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2CallEntityChain.java index 3174bf29852..d866dc0faa2 100644 --- a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2CallEntityChain.java +++ b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2CallEntityChain.java @@ -22,7 +22,8 @@ import io.helidon.common.GenericType; import io.helidon.common.buffers.BufferData; import io.helidon.http.ClientRequestHeaders; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.http2.Http2Headers; import io.helidon.http.media.EntityWriter; import io.helidon.webclient.api.ClientUri; @@ -55,7 +56,7 @@ protected WebClientServiceResponse doProceed(WebClientServiceRequest serviceRequ entityBytes = entityBytes(entity, headers); } - headers.set(Http.Headers.create(Http.HeaderNames.CONTENT_LENGTH, entityBytes.length)); + headers.set(HeaderValues.create(HeaderNames.CONTENT_LENGTH, entityBytes.length)); ClientUri uri = serviceRequest.uri(); diff --git a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientConnectionHandler.java b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientConnectionHandler.java index 386095dc6c7..5f09c4d390c 100644 --- a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientConnectionHandler.java +++ b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientConnectionHandler.java @@ -29,7 +29,10 @@ import java.util.function.Function; import io.helidon.common.buffers.BufferData; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.http2.Http2Flag; import io.helidon.http.http2.Http2Settings; import io.helidon.webclient.api.ClientConnection; @@ -50,11 +53,11 @@ // this may use one or more connections (depending on parallel streams) class Http2ClientConnectionHandler { private static final System.Logger LOGGER = System.getLogger(Http2ClientConnectionHandler.class.getName()); - private static final Http.Header CONNECTION_UPGRADE_HEADER = Http.Headers.createCached(Http.HeaderNames.CONNECTION, - "Upgrade, HTTP2-Settings"); + private static final Header CONNECTION_UPGRADE_HEADER = HeaderValues.createCached(HeaderNames.CONNECTION, + "Upgrade, HTTP2-Settings"); // h2c stands for HTTP/2 plaintext protocol (only used without TLS) - private static final Http.Header UPGRADE_HEADER = Http.Headers.createCached(Http.HeaderNames.UPGRADE, "h2c"); - private static final Http.HeaderName HTTP2_SETTINGS_HEADER = Http.HeaderNames.create("HTTP2-Settings"); + private static final Header UPGRADE_HEADER = HeaderValues.createCached(HeaderNames.UPGRADE, "h2c"); + private static final HeaderName HTTP2_SETTINGS_HEADER = HeaderNames.create("HTTP2-Settings"); // todo requires handling of timeouts and removal from this queue private final Map h2ConnByConn = diff --git a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientImpl.java b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientImpl.java index e3b63d3a713..5f9c5222506 100644 --- a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientImpl.java +++ b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientImpl.java @@ -17,7 +17,7 @@ package io.helidon.webclient.http2; import io.helidon.common.uri.UriQueryWriteable; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webclient.api.ClientRequest; import io.helidon.webclient.api.ClientUri; import io.helidon.webclient.api.ConnectionKey; @@ -43,7 +43,7 @@ class Http2ClientImpl implements Http2Client, HttpClientSpi { } @Override - public Http2ClientRequest method(Http.Method method) { + public Http2ClientRequest method(Method method) { ClientUri clientUri = clientConfig.baseUri() .map(ClientUri::create) // create from base config .orElseGet(ClientUri::create); // create as empty diff --git a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientRequestImpl.java b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientRequestImpl.java index 684f98ac280..00bdde25b7a 100644 --- a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientRequestImpl.java +++ b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientRequestImpl.java @@ -22,7 +22,9 @@ import java.util.concurrent.CompletableFuture; import io.helidon.common.buffers.BufferData; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.ClientRequestBase; import io.helidon.webclient.api.ClientUri; import io.helidon.webclient.api.FullClientRequest; @@ -40,7 +42,7 @@ class Http2ClientRequestImpl extends ClientRequestBase properties) { super(http2Client.clientConfig(), @@ -56,7 +58,7 @@ class Http2ClientRequestImpl extends ClientRequestBase properties) { this(request.http2Client, method, clientUri, properties); @@ -161,11 +163,11 @@ private Http2ClientResponse invokeEntityFollowRedirects(Object entity) { int code = clientResponse.status().code(); if (code < 300 || code >= 400) { return clientResponse; - } else if (!clientResponse.headers().contains(Http.HeaderNames.LOCATION)) { - throw new IllegalStateException("There is no " + Http.HeaderNames.LOCATION + " header present in the response! " + } else if (!clientResponse.headers().contains(HeaderNames.LOCATION)) { + throw new IllegalStateException("There is no " + HeaderNames.LOCATION + " header present in the response! " + "It is not clear where to redirect."); } - String redirectedUri = clientResponse.headers().get(Http.HeaderNames.LOCATION).value(); + String redirectedUri = clientResponse.headers().get(HeaderNames.LOCATION).value(); URI newUri = URI.create(redirectedUri); ClientUri redirectUri = ClientUri.create(newUri); @@ -181,13 +183,13 @@ private Http2ClientResponse invokeEntityFollowRedirects(Object entity) { redirectUri.port(resolvedUri.port()); } //Method and entity is required to be the same as with original request with 307 and 308 requests - if (clientResponse.status() == Http.Status.TEMPORARY_REDIRECT_307 - || clientResponse.status() == Http.Status.PERMANENT_REDIRECT_308) { + if (clientResponse.status() == Status.TEMPORARY_REDIRECT_307 + || clientResponse.status() == Status.PERMANENT_REDIRECT_308) { clientRequest = new Http2ClientRequestImpl(clientRequest, clientRequest.method(), redirectUri, properties()); } else { //It is possible to change to GET and send no entity with all other redirect codes entityToBeSent = BufferData.EMPTY_BYTES; //We do not want to send entity after this redirect - clientRequest = new Http2ClientRequestImpl(clientRequest, Http.Method.GET, redirectUri, properties()); + clientRequest = new Http2ClientRequestImpl(clientRequest, Method.GET, redirectUri, properties()); } } throw new IllegalStateException("Maximum number of request redirections (" diff --git a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientResponseImpl.java b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientResponseImpl.java index 4109a7742d8..b69f9f7cd40 100644 --- a/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientResponseImpl.java +++ b/webclient/http2/src/main/java/io/helidon/webclient/http2/Http2ClientResponseImpl.java @@ -25,14 +25,14 @@ import io.helidon.common.buffers.BufferData; import io.helidon.http.ClientRequestHeaders; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.http.media.MediaContext; import io.helidon.http.media.ReadableEntity; import io.helidon.webclient.api.ClientResponseEntity; import io.helidon.webclient.api.ClientUri; class Http2ClientResponseImpl implements Http2ClientResponse { - private final Http.Status responseStatus; + private final Status responseStatus; private final ClientRequestHeaders requestHeaders; private final ClientResponseHeaders responseHeaders; private final CompletableFuture complete; @@ -43,7 +43,7 @@ class Http2ClientResponseImpl implements Http2ClientResponse { private final AtomicBoolean closed = new AtomicBoolean(false); - Http2ClientResponseImpl(Http.Status status, + Http2ClientResponseImpl(Status status, ClientRequestHeaders requestHeaders, ClientResponseHeaders responseHeaders, InputStream inputStream, // input stream is nullable - no response entity @@ -62,7 +62,7 @@ class Http2ClientResponseImpl implements Http2ClientResponse { } @Override - public Http.Status status() { + public Status status() { return responseStatus; } diff --git a/webclient/http2/src/test/java/io/helidon/webclient/http2/Http2WebClientTest.java b/webclient/http2/src/test/java/io/helidon/webclient/http2/Http2WebClientTest.java index b44882bd7dc..e1d3c9720b6 100644 --- a/webclient/http2/src/test/java/io/helidon/webclient/http2/Http2WebClientTest.java +++ b/webclient/http2/src/test/java/io/helidon/webclient/http2/Http2WebClientTest.java @@ -33,7 +33,9 @@ import io.helidon.common.configurable.Resource; import io.helidon.common.pki.Keys; import io.helidon.common.tls.Tls; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http1.Http1Route; @@ -48,20 +50,20 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import static io.helidon.http.Http.HeaderNames.USER_AGENT; -import static io.helidon.http.Http.Method.GET; -import static io.helidon.http.Http.Method.POST; -import static io.helidon.http.Http.Method.PUT; +import static io.helidon.http.HeaderNames.USER_AGENT; +import static io.helidon.http.Method.GET; +import static io.helidon.http.Method.POST; +import static io.helidon.http.Method.PUT; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @ServerTest class Http2WebClientTest { - private static final Http.HeaderName CLIENT_CUSTOM_HEADER_NAME = Http.HeaderNames.create("client-custom-header"); - private static final Http.HeaderName SERVER_CUSTOM_HEADER_NAME = Http.HeaderNames.create("server-custom-header"); - private static final Http.HeaderName SERVER_HEADER_FROM_PARAM_NAME = Http.HeaderNames.create("header-from-param"); - private static final Http.HeaderName CLIENT_USER_AGENT_HEADER_NAME = Http.HeaderNames.create("client-user-agent"); + private static final HeaderName CLIENT_CUSTOM_HEADER_NAME = HeaderNames.create("client-custom-header"); + private static final HeaderName SERVER_CUSTOM_HEADER_NAME = HeaderNames.create("server-custom-header"); + private static final HeaderName SERVER_HEADER_FROM_PARAM_NAME = HeaderNames.create("header-from-param"); + private static final HeaderName CLIENT_USER_AGENT_HEADER_NAME = HeaderNames.create("client-user-agent"); private static ExecutorService executorService; private static int plainPort; private static int tlsPort; @@ -150,7 +152,7 @@ static void setUpServer(WebServerConfig.Builder serverBuilder) { res.send("POST " + req.content().as(String.class)); })) .route(Http2Route.route(GET, "/versionspecific/h2streaming", (req, res) -> { - res.status(Http.Status.OK_200); + res.status(Status.OK_200); String execId = req.query().get("execId"); try (OutputStream os = res.outputStream()) { for (int i = 0; i < 5; i++) { @@ -190,7 +192,7 @@ void clientGet(String name, Supplier client) { .queryParam("custQueryParam", "test-get") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is("HTTP/2 route")); assertThat(response.headers().get(CLIENT_USER_AGENT_HEADER_NAME).value(), is(Http2ClientRequestImpl.USER_AGENT_HEADER.value())); @@ -211,7 +213,7 @@ void clientPut(String clientType, Supplier client) { .header(CLIENT_CUSTOM_HEADER_NAME, custHeaderValue) .submit(payload)) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is("PUT " + payload)); assertThat(response.headers().get(CLIENT_USER_AGENT_HEADER_NAME).value(), is(Http2ClientRequestImpl.USER_AGENT_HEADER.value())); @@ -234,7 +236,7 @@ void clientPost(String clientType, Supplier client) { .header(CLIENT_CUSTOM_HEADER_NAME, custHeaderValue) .submit(payload)) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is("POST " + payload)); assertThat(response.headers().get(CLIENT_USER_AGENT_HEADER_NAME).value(), is(Http2ClientRequestImpl.USER_AGENT_HEADER.value())); diff --git a/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientCounter.java b/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientCounter.java index 830693b6665..dec2262651b 100644 --- a/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientCounter.java +++ b/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientCounter.java @@ -15,7 +15,7 @@ */ package io.helidon.webclient.metrics; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.metrics.api.Counter; import io.helidon.webclient.api.WebClientServiceRequest; import io.helidon.webclient.api.WebClientServiceResponse; @@ -31,7 +31,7 @@ class WebClientCounter extends WebClientMetric { @Override public WebClientServiceResponse handle(Chain chain, WebClientServiceRequest request) { - Http.Method method = request.method(); + Method method = request.method(); try { WebClientServiceResponse response = chain.proceed(request); int code = response.status().code(); diff --git a/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientMeter.java b/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientMeter.java index 0c37a4cb467..e0a1059ab1c 100644 --- a/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientMeter.java +++ b/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientMeter.java @@ -15,7 +15,7 @@ */ package io.helidon.webclient.metrics; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.metrics.api.Counter; import io.helidon.webclient.api.WebClientServiceRequest; import io.helidon.webclient.api.WebClientServiceResponse; @@ -31,7 +31,7 @@ public class WebClientMeter extends WebClientMetric { @Override public WebClientServiceResponse handle(Chain chain, WebClientServiceRequest request) { - Http.Method method = request.method(); + Method method = request.method(); try { WebClientServiceResponse response = chain.proceed(request); int code = response.status().code(); diff --git a/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientMetric.java b/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientMetric.java index d21dab8a027..3c445653459 100644 --- a/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientMetric.java +++ b/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientMetric.java @@ -22,7 +22,7 @@ import java.util.stream.Collectors; import io.helidon.common.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.metrics.api.MeterRegistry; import io.helidon.metrics.api.Metrics; import io.helidon.webclient.api.WebClientServiceRequest; @@ -77,15 +77,15 @@ boolean measureErrors() { return errors; } - boolean shouldContinueOnSuccess(Http.Method method, int status) { + boolean shouldContinueOnSuccess(Method method, int status) { return handlesMethod(method) && measureSuccess() && status < ERROR_STATUS_CODE; } - boolean shouldContinueOnError(Http.Method method) { + boolean shouldContinueOnError(Method method) { return handlesMethod(method) && measureErrors(); } - boolean shouldContinueOnError(Http.Method method, int status) { + boolean shouldContinueOnError(Method method, int status) { if (status >= ERROR_STATUS_CODE) { return shouldContinueOnError(method); } @@ -114,7 +114,7 @@ String createName(WebClientServiceRequest request) { return String.format(nameFormat(), request.method().text(), request.uri().host()); } - boolean handlesMethod(Http.Method method) { + boolean handlesMethod(Method method) { return methods().isEmpty() || methods().contains(method.text()); } @@ -151,9 +151,9 @@ public Builder methods(String... methods) { * @param methods metric supported methods * @return updated builder instance */ - public Builder methods(Http.Method... methods) { + public Builder methods(Method... methods) { this.methods = Arrays.stream(methods) - .map(Http.Method::text) + .map(Method::text) .map(String::toUpperCase) .collect(Collectors.toSet()); return this; diff --git a/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientTimer.java b/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientTimer.java index bc0e1cc4012..bf0e5fd0c62 100644 --- a/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientTimer.java +++ b/webclient/metrics/src/main/java/io/helidon/webclient/metrics/WebClientTimer.java @@ -17,7 +17,8 @@ import java.time.Duration; -import io.helidon.http.Http; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.metrics.api.Timer; import io.helidon.webclient.api.WebClientServiceRequest; import io.helidon.webclient.api.WebClientServiceResponse; @@ -34,10 +35,10 @@ class WebClientTimer extends WebClientMetric { @Override public WebClientServiceResponse handle(Chain chain, WebClientServiceRequest request) { long start = System.nanoTime(); - Http.Method method = request.method(); + Method method = request.method(); try { WebClientServiceResponse response = chain.proceed(request); - Http.Status status = response.status(); + Status status = response.status(); if (shouldContinueOnError(method, status.code())) { updateTimer(createMetadata(request, response), start); } diff --git a/webclient/security/src/main/java/io/helidon/webclient/security/WebClientSecurity.java b/webclient/security/src/main/java/io/helidon/webclient/security/WebClientSecurity.java index 3965463295a..ea43dc34a8f 100644 --- a/webclient/security/src/main/java/io/helidon/webclient/security/WebClientSecurity.java +++ b/webclient/security/src/main/java/io/helidon/webclient/security/WebClientSecurity.java @@ -24,7 +24,8 @@ import io.helidon.common.context.Context; import io.helidon.common.context.Contexts; import io.helidon.http.ClientRequestHeaders; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.security.EndpointConfig; import io.helidon.security.OutboundSecurityClientBuilder; import io.helidon.security.OutboundSecurityResponse; @@ -185,7 +186,7 @@ private WebClientServiceResponse processResponse(WebClientServiceRequest request } //replace existing - Http.HeaderName headerName = Http.HeaderNames.create(entry.getKey()); + HeaderName headerName = HeaderNames.create(entry.getKey()); clientHeaders.set(headerName, entry.getValue().toArray(new String[0])); } span.end(); diff --git a/webclient/tests/http1/src/test/java/io/helidon/webclient/http1/Http1ClientTest.java b/webclient/tests/http1/src/test/java/io/helidon/webclient/http1/Http1ClientTest.java index b3d73f98e89..cc296f67b25 100644 --- a/webclient/tests/http1/src/test/java/io/helidon/webclient/http1/Http1ClientTest.java +++ b/webclient/tests/http1/src/test/java/io/helidon/webclient/http1/Http1ClientTest.java @@ -29,8 +29,13 @@ import java.util.concurrent.TimeUnit; import io.helidon.common.GenericType; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityReader; import io.helidon.http.media.EntityWriter; @@ -68,11 +73,11 @@ */ @ServerTest class Http1ClientTest { - private static final Http.Header REQ_CHUNKED_HEADER = Http.Headers.createCached( - Http.HeaderNames.create("X-Req-Chunked"), "true"); - private static final Http.Header REQ_EXPECT_100_HEADER_NAME = Http.Headers.createCached( - Http.HeaderNames.create("X-Req-Expect100"), "true"); - private static final Http.HeaderName REQ_CONTENT_LENGTH_HEADER_NAME = Http.HeaderNames.create("X-Req-ContentLength"); + private static final Header REQ_CHUNKED_HEADER = HeaderValues.createCached( + HeaderNames.create("X-Req-Chunked"), "true"); + private static final Header REQ_EXPECT_100_HEADER_NAME = HeaderValues.createCached( + HeaderNames.create("X-Req-Expect100"), "true"); + private static final HeaderName REQ_CONTENT_LENGTH_HEADER_NAME = HeaderNames.create("X-Req-ContentLength"); private static final String EXPECTED_GET_AFTER_REDIRECT_STRING = "GET after redirect endpoint reached"; private static final long NO_CONTENT_LENGTH = -1L; @@ -140,7 +145,7 @@ void testMediaContext() { void testChunk() { String[] requestEntityParts = {"First", "Second", "Third"}; - HttpClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test"); + HttpClientRequest request = getHttp1ClientRequest(Method.PUT, "/test"); HttpClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); validateChunkTransfer(response, true, NO_CONTENT_LENGTH, String.join("", requestEntityParts)); @@ -150,11 +155,11 @@ void testChunk() { void testChunkAndChunkResponse() { String[] requestEntityParts = {"First", "Second", "Third"}; - HttpClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/chunkresponse"); + HttpClientRequest request = getHttp1ClientRequest(Method.PUT, "/chunkresponse"); HttpClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); validateChunkTransfer(response, true, NO_CONTENT_LENGTH, String.join("", requestEntityParts)); - assertThat(response.headers(), hasHeader(Http.Headers.TRANSFER_ENCODING_CHUNKED)); + assertThat(response.headers(), hasHeader(HeaderValues.TRANSFER_ENCODING_CHUNKED)); } @Test @@ -162,8 +167,8 @@ void testNoChunk() { String[] requestEntityParts = {"First"}; long contentLength = requestEntityParts[0].length(); - HttpClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test") - .header(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(contentLength)); + HttpClientRequest request = getHttp1ClientRequest(Method.PUT, "/test") + .header(HeaderNames.CONTENT_LENGTH, String.valueOf(contentLength)); HttpClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); validateChunkTransfer(response, false, contentLength, requestEntityParts[0]); @@ -173,7 +178,7 @@ void testNoChunk() { void testForcedChunkNoContentLength() { String[] requestEntityParts = {"First"}; - HttpClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test"); + HttpClientRequest request = getHttp1ClientRequest(Method.PUT, "/test"); HttpClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); validateChunkTransfer(response, true, NO_CONTENT_LENGTH, requestEntityParts[0]); @@ -183,8 +188,8 @@ void testForcedChunkNoContentLength() { void testForcedChunkTransferEncodingChunked() { String[] requestEntityParts = {"First"}; - HttpClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test") - .header(Http.Headers.TRANSFER_ENCODING_CHUNKED); + HttpClientRequest request = getHttp1ClientRequest(Method.PUT, "/test") + .header(HeaderValues.TRANSFER_ENCODING_CHUNKED); HttpClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); validateChunkTransfer(response, true, NO_CONTENT_LENGTH, requestEntityParts[0]); @@ -338,12 +343,12 @@ void testRedirect() { try (HttpClientResponse response = injectedHttp1client.put("/redirect") .followRedirects(false) .submit("Test entity")) { - assertThat(response.status(), is(Http.Status.FOUND_302)); + assertThat(response.status(), is(Status.FOUND_302)); } try (HttpClientResponse response = injectedHttp1client.put("/redirect") .submit("Test entity")) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.lastEndpointUri().path().path(), is("/afterRedirect")); assertThat(response.as(String.class), is(EXPECTED_GET_AFTER_REDIRECT_STRING)); } @@ -354,13 +359,13 @@ void testRedirectKeepMethod() { try (HttpClientResponse response = injectedHttp1client.put("/redirectKeepMethod") .followRedirects(false) .submit("Test entity")) { - assertThat(response.status(), is(Http.Status.TEMPORARY_REDIRECT_307)); + assertThat(response.status(), is(Status.TEMPORARY_REDIRECT_307)); } try (HttpClientResponse response = injectedHttp1client.put("/redirectKeepMethod") .submit("Test entity")) { assertThat(response.lastEndpointUri().path().path(), is("/afterRedirect")); - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); } } @@ -369,7 +374,7 @@ void testReadTimeoutPerRequest() { String testEntity = "Test entity"; try (HttpClientResponse response = injectedHttp1client.put("/delayedEndpoint") .submit(testEntity)) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is(testEntity)); } @@ -401,7 +406,7 @@ private static void validateSuccessfulResponse(Http1Client client) { Http1ClientRequest request = client.put("/test"); ClientResponseTyped response = request.submit(requestEntity, String.class); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity(), is(requestEntity)); } @@ -413,7 +418,7 @@ private static void validateFailedResponse(Http1Client client, String errorMessa } private static void validateChunkTransfer(HttpClientResponse response, boolean chunked, long contentLength, String entity) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); if (contentLength == NO_CONTENT_LENGTH) { assertThat(response.headers(), noHeader(REQ_CONTENT_LENGTH_HEADER_NAME)); } else { @@ -429,20 +434,20 @@ private static void validateChunkTransfer(HttpClientResponse response, boolean c } private static void redirect(ServerRequest req, ServerResponse res) { - res.status(Http.Status.FOUND_302) - .header(Http.HeaderNames.LOCATION, "/afterRedirect") + res.status(Status.FOUND_302) + .header(HeaderNames.LOCATION, "/afterRedirect") .send(); } private static void redirectKeepMethod(ServerRequest req, ServerResponse res) { - res.status(Http.Status.TEMPORARY_REDIRECT_307) - .header(Http.HeaderNames.LOCATION, "/afterRedirect") + res.status(Status.TEMPORARY_REDIRECT_307) + .header(HeaderNames.LOCATION, "/afterRedirect") .send(); } private static void afterRedirectGet(ServerRequest req, ServerResponse res) { if (req.content().hasEntity()) { - res.status(Http.Status.BAD_REQUEST_400) + res.status(Status.BAD_REQUEST_400) .send("GET after redirect endpoint reached with entity"); return; } @@ -452,11 +457,11 @@ private static void afterRedirectGet(ServerRequest req, ServerResponse res) { private static void afterRedirectPut(ServerRequest req, ServerResponse res) { String entity = req.content().as(String.class); if (!entity.equals("Test entity")) { - res.status(Http.Status.BAD_REQUEST_400) + res.status(Status.BAD_REQUEST_400) .send("Entity was not kept the same after the redirect"); return; } - res.status(Http.Status.NO_CONTENT_204) + res.status(Status.NO_CONTENT_204) .send(); } @@ -475,13 +480,13 @@ private static void chunkResponseHandler(ServerRequest req, ServerResponse res) private static void customHandler(ServerRequest req, ServerResponse res, boolean chunkResponse) throws IOException { Headers reqHeaders = req.headers(); - if (reqHeaders.contains(Http.Headers.EXPECT_100)) { + if (reqHeaders.contains(HeaderValues.EXPECT_100)) { res.headers().set(REQ_EXPECT_100_HEADER_NAME); } - if (reqHeaders.contains(Http.HeaderNames.CONTENT_LENGTH)) { - res.headers().set(REQ_CONTENT_LENGTH_HEADER_NAME, reqHeaders.get(Http.HeaderNames.CONTENT_LENGTH).get()); + if (reqHeaders.contains(HeaderNames.CONTENT_LENGTH)) { + res.headers().set(REQ_CONTENT_LENGTH_HEADER_NAME, reqHeaders.get(HeaderNames.CONTENT_LENGTH).get()); } - if (reqHeaders.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED)) { + if (reqHeaders.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED)) { res.headers().set(REQ_CHUNKED_HEADER); } @@ -517,7 +522,7 @@ private static HttpClientResponse getHttp1ClientResponseFromOutputStream(HttpCli }); } - private HttpClientRequest getHttp1ClientRequest(Http.Method method, String uriPath) { + private HttpClientRequest getHttp1ClientRequest(Method method, String uriPath) { return injectedHttp1client.method(method).uri(uriPath); } diff --git a/webclient/tests/http1/src/test/java/io/helidon/webclient/http1/ValidateHeadersTest.java b/webclient/tests/http1/src/test/java/io/helidon/webclient/http1/ValidateHeadersTest.java index 9a60b29a6e4..a460c30b598 100644 --- a/webclient/tests/http1/src/test/java/io/helidon/webclient/http1/ValidateHeadersTest.java +++ b/webclient/tests/http1/src/test/java/io/helidon/webclient/http1/ValidateHeadersTest.java @@ -16,34 +16,14 @@ package io.helidon.webclient.http1; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UncheckedIOException; -import java.net.SocketTimeoutException; import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; import java.util.stream.Stream; -import java.util.concurrent.TimeUnit; -import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.ServerRequestHeaders; -import io.helidon.http.media.EntityReader; -import io.helidon.http.media.EntityWriter; -import io.helidon.http.media.MediaContext; -import io.helidon.http.media.MediaContextConfig; -import io.helidon.common.GenericType; -import io.helidon.webclient.api.ClientConnection; -import io.helidon.webclient.api.ClientResponseTyped; -import io.helidon.webclient.api.HttpClientRequest; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; -import io.helidon.webclient.api.Proxy; -import io.helidon.webclient.api.WebClient; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRules; @@ -56,7 +36,6 @@ import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webserver.testing.junit5.SetUpServer; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -66,15 +45,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.params.provider.Arguments.arguments; -import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; -import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.noHeader; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.instanceOf; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.core.IsNot.not; -import static org.junit.jupiter.api.Assertions.assertThrows; - /** * Test for validating client side outbound/inbound headers (request/response headers) */ @@ -115,10 +85,10 @@ void testRequestHeaders(String headerName, String headerValue, boolean expectsVa }) ); Http1ClientRequest request = client.put(baseURI + "/test"); - request.header(Http.Headers.create(Http.HeaderNames.create(headerName), headerValue)); + request.header(HeaderValues.create(HeaderNames.create(headerName), headerValue)); if (expectsValid) { HttpClientResponse response = request.request(); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } else { assertThrows(IllegalArgumentException.class, () -> request.request()); } @@ -134,11 +104,11 @@ void testResponsetHeaders(String headerName, String headerValue, boolean expects }) ); Http1ClientRequest request = client.put(baseURI + "/test"); - request.header(Http.Headers.create(Http.HeaderNames.create(headerName), headerValue)); + request.header(HeaderValues.create(HeaderNames.create(headerName), headerValue)); if (expectsValid) { HttpClientResponse response = request.request(); - assertThat(response.status(), is(Http.Status.OK_200)); - String responseHeaderValue = response.headers().get(Http.HeaderNames.create(headerName)).values(); + assertThat(response.status(), is(Status.OK_200)); + String responseHeaderValue = response.headers().get(HeaderNames.create(headerName)).values(); assertThat(responseHeaderValue, is(headerValue.trim())); } else { assertThrows(IllegalArgumentException.class, () -> request.request()); @@ -156,14 +126,14 @@ void testOutputStreamResponsetHeaders(String headerName, String headerValue, boo .sendExpectContinue(false) ); Http1ClientRequest request = client.put(baseURI + "/test"); - request.header(Http.Headers.create(Http.HeaderNames.create(headerName), headerValue)); + request.header(HeaderValues.create(HeaderNames.create(headerName), headerValue)); if (expectsValid) { HttpClientResponse response = request.outputStream(it -> { it.write("Foo Bar".getBytes(StandardCharsets.UTF_8)); it.close(); }); - assertThat(response.status(), is(Http.Status.OK_200)); - String responseHeaderValue = response.headers().get(Http.HeaderNames.create(headerName)).values(); + assertThat(response.status(), is(Status.OK_200)); + String responseHeaderValue = response.headers().get(HeaderNames.create(headerName)).values(); assertThat(responseHeaderValue, is(headerValue.trim())); } else { assertThrows( @@ -185,10 +155,10 @@ void testDisableHeaderValidation(String headerName, String headerValue, boolean }) ); Http1ClientRequest request = client.put(baseURI + "/test"); - request.header(Http.Headers.create(Http.HeaderNames.create(headerName), headerValue)); + request.header(HeaderValues.create(HeaderNames.create(headerName), headerValue)); HttpClientResponse response = request.request(); - assertThat(response.status(), is(Http.Status.OK_200)); - String responseHeaderValue = response.headers().get(Http.HeaderNames.create(headerName)).values(); + assertThat(response.status(), is(Status.OK_200)); + String responseHeaderValue = response.headers().get(HeaderNames.create(headerName)).values(); assertThat(responseHeaderValue, is(headerValue.trim())); } @@ -196,7 +166,7 @@ private static void headerValidationHandler(ServerRequest request, ServerRespons ServerRequestHeaders headers = request.headers(); request.headers().toMap().forEach((k, v) -> { if (k.contains("Header")) { - response.headers().add(Http.Headers.create(Http.HeaderNames.create(k), v)); + response.headers().add(HeaderValues.create(HeaderNames.create(k), v)); } }); response.send("any"); diff --git a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/AuthHttpProxyTest.java b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/AuthHttpProxyTest.java index 7d9c944a994..75c7eb2572d 100644 --- a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/AuthHttpProxyTest.java +++ b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/AuthHttpProxyTest.java @@ -16,23 +16,23 @@ package io.helidon.webclient.tests; -import io.helidon.http.Http; -import io.helidon.webclient.http2.Http2Client; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClient; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.Proxy; import io.helidon.webclient.api.Proxy.ProxyType; import io.helidon.webclient.http1.Http1Client; +import io.helidon.webclient.http2.Http2Client; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; +import static io.helidon.http.Method.GET; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; @@ -109,7 +109,7 @@ void testUserPasswordNotCorrect2() { private void successVerify(Proxy proxy, HttpClient client) { try (HttpClientResponse response = client.get("/get").proxy(proxy).request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); } diff --git a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/AuthHttpsProxyTest.java b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/AuthHttpsProxyTest.java index 4d139181854..9175b095044 100644 --- a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/AuthHttpsProxyTest.java +++ b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/AuthHttpsProxyTest.java @@ -17,27 +17,27 @@ package io.helidon.webclient.tests; import io.helidon.common.configurable.Resource; -import io.helidon.http.Http; import io.helidon.common.pki.Keys; import io.helidon.common.tls.Tls; -import io.helidon.webclient.http2.Http2Client; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClient; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.Proxy; import io.helidon.webclient.api.Proxy.ProxyType; import io.helidon.webclient.http1.Http1Client; +import io.helidon.webclient.http2.Http2Client; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig.Builder; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; +import static io.helidon.http.Method.GET; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.fail; @@ -149,7 +149,7 @@ private void failVerify(Proxy proxy, HttpClient client) { private void successVerify(Proxy proxy, HttpClient client) { try (HttpClientResponse response = client.get("/get").proxy(proxy).request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); } diff --git a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/CookieTest.java b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/CookieTest.java index 49622e7377e..f93fe31fc51 100644 --- a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/CookieTest.java +++ b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/CookieTest.java @@ -16,9 +16,11 @@ package io.helidon.webclient.tests; -import io.helidon.http.Http; import io.helidon.config.Config; import io.helidon.config.ConfigSources; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServer; @@ -75,7 +77,7 @@ void afterAll() { @Order(1) void testCookieGet() { try (Http1ClientResponse response = client.get("/cookie").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } } @@ -83,7 +85,7 @@ void testCookieGet() { @Order(2) void testCookiePut() { try (Http1ClientResponse response = client.put("/cookie").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } } @@ -91,44 +93,44 @@ void testCookiePut() { @Order(3) void testCookieGetAfterPut() { try (Http1ClientResponse response = client.get("/cookie").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } } private static void getHandler(ServerRequest req, ServerResponse res) { - if (req.headers().contains(Http.HeaderNames.COOKIE)) { - Http.Header cookies = req.headers().get(Http.HeaderNames.COOKIE); + if (req.headers().contains(HeaderNames.COOKIE)) { + Header cookies = req.headers().get(HeaderNames.COOKIE); if (cookies.allValues().size() == 2 && cookies.allValues().contains("flavor3=strawberry") // in application.yaml && cookies.allValues().contains("flavor4=raspberry")) { // in application.yaml - res.header(Http.HeaderNames.SET_COOKIE, "flavor1=chocolate", "flavor2=vanilla"); - res.status(Http.Status.OK_200).send(); + res.header(HeaderNames.SET_COOKIE, "flavor1=chocolate", "flavor2=vanilla"); + res.status(Status.OK_200).send(); } else { - res.status(Http.Status.BAD_REQUEST_400).send(); + res.status(Status.BAD_REQUEST_400).send(); } } else { - res.status(Http.Status.BAD_REQUEST_400).send(); + res.status(Status.BAD_REQUEST_400).send(); } } private static void putHandler(ServerRequest req, ServerResponse res) { - if (req.headers().contains(Http.HeaderNames.COOKIE)) { - Http.Header cookies = req.headers().get(Http.HeaderNames.COOKIE); + if (req.headers().contains(HeaderNames.COOKIE)) { + Header cookies = req.headers().get(HeaderNames.COOKIE); if (cookies.allValues().size() == 4 && cookies.allValues().contains("flavor1=chocolate") && cookies.allValues().contains("flavor2=vanilla") && cookies.allValues().contains("flavor3=strawberry") && cookies.allValues().contains("flavor4=raspberry")) { // clear flavor1 and flavor2 - res.header(Http.HeaderNames.SET_COOKIE, - "flavor1=; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Max-Age=0", - "flavor2=; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Max-Age=0"); - res.status(Http.Status.OK_200).send(); + res.header(HeaderNames.SET_COOKIE, + "flavor1=; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Max-Age=0", + "flavor2=; Expires=Thu, 01-Jan-1970 00:00:10 GMT; Max-Age=0"); + res.status(Status.OK_200).send(); } else { - res.status(Http.Status.BAD_REQUEST_400).send(); + res.status(Status.BAD_REQUEST_400).send(); } } else { - res.status(Http.Status.BAD_REQUEST_400).send(); + res.status(Status.BAD_REQUEST_400).send(); } } } \ No newline at end of file diff --git a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HeadersTest.java b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HeadersTest.java index 5d5c3fd15c7..4ba166b1fed 100644 --- a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HeadersTest.java +++ b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HeadersTest.java @@ -18,19 +18,22 @@ import java.util.Optional; +import io.helidon.common.media.type.ParserMode; import io.helidon.http.ClientResponseHeaders; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpMediaType; -import io.helidon.common.media.type.ParserMode; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.WebClient; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -56,12 +59,12 @@ static void routing(HttpRules rules) { // Verify that invalid content type is present in response headers and is accessible @Test public void testInvalidContentType() { - try (HttpClientResponse res = client.method(Http.Method.GET) + try (HttpClientResponse res = client.method(Method.GET) .path("/test/invalidContentType") .request()) { ClientResponseHeaders h = res.headers(); - Http.Header contentType = h.get(Http.HeaderNames.CONTENT_TYPE); - assertThat(res.status(), is(Http.Status.OK_200)); + Header contentType = h.get(HeaderNames.CONTENT_TYPE); + assertThat(res.status(), is(Status.OK_200)); assertThat(contentType.value(), is(TestService.INVALID_CONTENT_TYPE_VALUE)); } } @@ -69,13 +72,13 @@ public void testInvalidContentType() { // Verify that "Content-Type: text" header parsing fails in strict mode @Test public void testInvalidTextContentTypeStrict() { - try (HttpClientResponse res = client.method(Http.Method.GET) + try (HttpClientResponse res = client.method(Method.GET) .path("/test/invalidTextContentType") .request()) { - assertThat(res.status(), is(Http.Status.OK_200)); + assertThat(res.status(), is(Status.OK_200)); Headers h = res.headers(); // Raw protocol data value - Http.Header rawContentType = h.get(Http.HeaderNames.CONTENT_TYPE); + Header rawContentType = h.get(HeaderNames.CONTENT_TYPE); assertThat(rawContentType.value(), is(TestService.INVALID_CONTENT_TYPE_TEXT)); // Media type parsed value is invalid, IllegalArgumentException shall be thrown try { @@ -94,13 +97,13 @@ public void testInvalidTextContentTypeRelaxed() { .from(this.client.prototype()) .mediaTypeParserMode(ParserMode.RELAXED) .build(); - try (HttpClientResponse res = client.method(Http.Method.GET) + try (HttpClientResponse res = client.method(Method.GET) .path("/test/invalidTextContentType") .request()) { - assertThat(res.status(), is(Http.Status.OK_200)); + assertThat(res.status(), is(Status.OK_200)); Headers h = res.headers(); // Raw protocol data value - Http.Header rawContentType = h.get(Http.HeaderNames.CONTENT_TYPE); + Header rawContentType = h.get(HeaderNames.CONTENT_TYPE); assertThat(rawContentType.value(), is(TestService.INVALID_CONTENT_TYPE_TEXT)); // Media type parsed value Optional contentType = h.contentType(); @@ -124,7 +127,7 @@ public void routing(HttpRules rules) { private static final String INVALID_CONTENT_TYPE_VALUE = "invalid header value"; private void invalidContentType(ServerRequest request, ServerResponse response) { - response.header(Http.HeaderNames.CONTENT_TYPE, INVALID_CONTENT_TYPE_VALUE) + response.header(HeaderNames.CONTENT_TYPE, INVALID_CONTENT_TYPE_VALUE) .send(); } @@ -133,7 +136,7 @@ private void invalidContentType(ServerRequest request, ServerResponse response) // Returns Content-Type: text instead of text/plain private void invalidTextContentType(ServerRequest request, ServerResponse response) { - response.header(Http.HeaderNames.CONTENT_TYPE, INVALID_CONTENT_TYPE_TEXT) + response.header(HeaderNames.CONTENT_TYPE, INVALID_CONTENT_TYPE_TEXT) .send(); } diff --git a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HttpProxyTest.java b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HttpProxyTest.java index 1f8e8cc5ab3..17dec4e243d 100644 --- a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HttpProxyTest.java +++ b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HttpProxyTest.java @@ -19,23 +19,23 @@ import java.net.InetSocketAddress; import java.net.ProxySelector; -import io.helidon.http.Http; -import io.helidon.webclient.http2.Http2Client; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClient; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.Proxy; import io.helidon.webclient.api.Proxy.ProxyType; import io.helidon.webclient.http1.Http1Client; +import io.helidon.webclient.http2.Http2Client; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; +import static io.helidon.http.Method.GET; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -189,7 +189,7 @@ void testSystemProxy2() { private void noHosts(HttpClient client) { Proxy proxy = Proxy.builder().host(PROXY_HOST).port(proxyPort).addNoProxy(PROXY_HOST).build(); try (HttpClientResponse response = client.get("/get").proxy(proxy).request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); } @@ -198,7 +198,7 @@ private void noHosts(HttpClient client) { private void successVerify(Proxy proxy, HttpClient client) { try (HttpClientResponse response = client.get("/get").proxy(proxy).request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); } @@ -207,7 +207,7 @@ private void successVerify(Proxy proxy, HttpClient client) { private void noProxyChecks(HttpClient client) { try (HttpClientResponse response = client.get("/get").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); } diff --git a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HttpsProxyTest.java b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HttpsProxyTest.java index ef87a79b4e5..f6f33463515 100644 --- a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HttpsProxyTest.java +++ b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/HttpsProxyTest.java @@ -21,27 +21,27 @@ import java.net.ProxySelector; import io.helidon.common.configurable.Resource; -import io.helidon.http.Http; import io.helidon.common.pki.Keys; import io.helidon.common.tls.Tls; -import io.helidon.webclient.http2.Http2Client; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClient; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.Proxy; import io.helidon.webclient.api.Proxy.ProxyType; import io.helidon.webclient.http1.Http1Client; +import io.helidon.webclient.http2.Http2Client; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig.Builder; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; +import static io.helidon.http.Method.GET; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -182,7 +182,7 @@ void testSystemProxy2() { private void successVerify(Proxy proxy, HttpClient client) { try (HttpClientResponse response = client.get("/get").proxy(proxy).request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); } @@ -190,7 +190,7 @@ private void successVerify(Proxy proxy, HttpClient client) { private void noProxyChecks(HttpClient client) { try (HttpClientResponse response = client.get("/get").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); } diff --git a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/SharedCacheTest.java b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/SharedCacheTest.java index 3f404af404d..dc3858f942d 100644 --- a/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/SharedCacheTest.java +++ b/webclient/tests/http1/src/test/java/io/helidon/webclient/tests/SharedCacheTest.java @@ -16,7 +16,9 @@ package io.helidon.webclient.tests; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webclient.api.WebClient; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.HttpRouting; @@ -24,7 +26,7 @@ import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.POST; +import static io.helidon.http.Method.POST; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -50,7 +52,7 @@ void cacheHttp1WithServerRestart() { .build(); try (var res = webClient.post().submit("WHATEVER")) { - assertThat(res.status(), is(Http.Status.OK_200)); + assertThat(res.status(), is(Status.OK_200)); } webServer.stop(); webServer = WebServer.builder() @@ -60,7 +62,7 @@ void cacheHttp1WithServerRestart() { .start(); try (var res = webClient.post().submit("WHATEVER")) { - assertThat(res.status(), is(Http.Status.OK_200)); + assertThat(res.status(), is(Status.OK_200)); } } finally { if (webServer != null) { @@ -71,7 +73,7 @@ void cacheHttp1WithServerRestart() { @Test void cacheHttp1NoRestart() { - Http.HeaderName clientPortHeader = Http.HeaderNames.create("client-port"); + HeaderName clientPortHeader = HeaderNames.create("client-port"); WebServer webServer = null; try { HttpRouting routing = HttpRouting.builder() @@ -96,13 +98,13 @@ void cacheHttp1NoRestart() { Integer firstReqClientPort; try (var res = webClient.post().submit("WHATEVER")) { firstReqClientPort = res.headers().get(clientPortHeader).get(Integer.TYPE); - assertThat(res.status(), is(Http.Status.OK_200)); + assertThat(res.status(), is(Status.OK_200)); } Integer secondReqClientPort; try (var res = webClient.post().submit("WHATEVER")) { secondReqClientPort = res.headers().get(clientPortHeader).get(Integer.TYPE); - assertThat(res.status(), is(Http.Status.OK_200)); + assertThat(res.status(), is(Status.OK_200)); } assertThat("In case of cached connection client port must be the same.", diff --git a/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/ClientFlowControlTest.java b/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/ClientFlowControlTest.java index aedffd1a5ec..848f9ec3c83 100644 --- a/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/ClientFlowControlTest.java +++ b/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/ClientFlowControlTest.java @@ -30,9 +30,9 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicLong; -import io.helidon.http.Http; -import io.helidon.logging.common.LogConfig; +import io.helidon.http.Method; import io.helidon.http.http2.WindowSize; +import io.helidon.logging.common.LogConfig; import io.helidon.webclient.http2.Http2Client; import io.helidon.webclient.http2.Http2ClientResponse; @@ -129,7 +129,7 @@ void clientOutbound() throws InterruptedException, ExecutionException, TimeoutEx ByteArrayInputStream baos = new ByteArrayInputStream(EXPECTED.getBytes()); CompletableFuture clientFuture = CompletableFuture.supplyAsync(() -> { try (Http2ClientResponse res = client - .method(Http.Method.PUT) + .method(Method.PUT) .path("/out") .priorKnowledge(true) .outputStream(out -> { @@ -166,7 +166,7 @@ void clientInbound() throws InterruptedException { AtomicLong receivedByteSize = new AtomicLong(); try (Http2ClientResponse res = client - .method(Http.Method.GET) + .method(Method.GET) .path("/in") .priorKnowledge(true) .request()) { diff --git a/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/GetTest.java b/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/GetTest.java index 150a5532036..fe6a04b98c1 100644 --- a/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/GetTest.java +++ b/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/GetTest.java @@ -28,16 +28,19 @@ import java.util.OptionalLong; import java.util.Random; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; -import io.helidon.http.Http.HeaderNames; -import io.helidon.webserver.http2.Http2Route; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webserver.http.Handler; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.http2.Http2Route; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -51,10 +54,10 @@ class GetTest { private static final String REQUEST_HEADER_VALUE_STRING = "some nice value"; private static final String RESPONSE_HEADER_NAME_STRING = "X-REsponSE-HeADER"; private static final String RESPONSE_HEADER_VALUE_STRING = "another nice value"; - private static final HeaderName REQUEST_HEADER_NAME = Http.HeaderNames.create(REQUEST_HEADER_NAME_STRING); + private static final HeaderName REQUEST_HEADER_NAME = HeaderNames.create(REQUEST_HEADER_NAME_STRING); private static final HeaderName RESPONSE_HEADER_NAME = HeaderNames.create(RESPONSE_HEADER_NAME_STRING); - private static final Http.Header RESPONSE_HEADER_VALUE = Http.Headers.createCached(RESPONSE_HEADER_NAME, - RESPONSE_HEADER_VALUE_STRING); + private static final Header RESPONSE_HEADER_VALUE = HeaderValues.createCached(RESPONSE_HEADER_NAME, + RESPONSE_HEADER_VALUE_STRING); static { Random random = new Random(); @@ -75,10 +78,10 @@ public GetTest(URI uri) { @SetUpRoute static void routing(HttpRouting.Builder router) { // enforce http/2 so we know if upgrade failed - router.route(Http2Route.route(Http.Method.GET, "/string", Handler.create(Routes::string))) - .route(Http.Method.GET, "/bytes", Routes::bytes) - .route(Http.Method.GET, "/chunked", Routes::chunked) - .route(Http.Method.GET, "/headers", Routes::headers); + router.route(Http2Route.route(Method.GET, "/string", Handler.create(Routes::string))) + .route(Method.GET, "/bytes", Routes::bytes) + .route(Method.GET, "/chunked", Routes::chunked) + .route(Method.GET, "/headers", Routes::headers); } @Test @@ -89,7 +92,7 @@ void testStringRoute() throws IOException, InterruptedException { .build(); HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); assertThat(response.body(), is("Hello")); java.net.http.HttpHeaders headers = response.headers(); @@ -105,7 +108,7 @@ void testByteRoute() throws IOException, InterruptedException { .build(); HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); assertThat(response.body(), is(BYTES)); java.net.http.HttpHeaders headers = response.headers(); assertThat(headers.firstValueAsLong(HeaderNames.CONTENT_LENGTH.defaultCase()), @@ -121,7 +124,7 @@ void testChunkedRoute() throws IOException, InterruptedException { .build(); HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofByteArray()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); assertThat(response.body(), is(BYTES)); java.net.http.HttpHeaders headers = response.headers(); assertThat(headers.firstValueAsLong(HeaderNames.CONTENT_LENGTH.defaultCase()), @@ -138,11 +141,11 @@ void testHeadersRoute() throws IOException, InterruptedException { HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); assertThat(response.body(), is("Hello")); java.net.http.HttpHeaders headers = response.headers(); - assertThat(headers.firstValueAsLong(Http.HeaderNames.CONTENT_LENGTH.defaultCase()), + assertThat(headers.firstValueAsLong(HeaderNames.CONTENT_LENGTH.defaultCase()), is(OptionalLong.of(5))); assertThat("Should contain echoed request header", headers.firstValue(REQUEST_HEADER_NAME_STRING), is(Optional.of(REQUEST_HEADER_VALUE_STRING))); diff --git a/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/HeadersTest.java b/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/HeadersTest.java index 5cd771740dd..b3f0d190a5c 100644 --- a/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/HeadersTest.java +++ b/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/HeadersTest.java @@ -26,8 +26,10 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeoutException; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.logging.common.LogConfig; import io.helidon.webclient.http2.Http2Client; import io.helidon.webclient.http2.Http2ClientResponse; @@ -124,14 +126,14 @@ void trailerHeader() { try (Http2ClientResponse res = Http2Client.builder() .baseUri("http://localhost:" + port + "/") .build() - .method(Http.Method.GET) + .method(Method.GET) .path("/trailer") .priorKnowledge(true) .request()) { Headers h = res.headers(); - assertThat(h.first(Http.HeaderNames.create("test")).orElse(null), is("before")); + assertThat(h.first(HeaderNames.create("test")).orElse(null), is("before")); assertThat(res.as(String.class), is(DATA)); - assertThat(h.first(Http.HeaderNames.create("Trailer-header")).orElse(null), is("trailer-test")); + assertThat(h.first(HeaderNames.create("Trailer-header")).orElse(null), is("trailer-test")); } } @@ -140,7 +142,7 @@ void continuationInbound() { try (Http2ClientResponse res = Http2Client.builder() .baseUri("http://localhost:" + port + "/") .build() - .method(Http.Method.GET) + .method(Method.GET) .path("/cont-in") .priorKnowledge(true) .request()) { @@ -148,7 +150,7 @@ void continuationInbound() { Headers h = res.headers(); for (int i = 0; i < 500; i++) { String name = "test-header-" + i; - assertThat("Headers " + name, h.first(Http.HeaderNames.create(name)).orElse(null), is(DATA)); + assertThat("Headers " + name, h.first(HeaderNames.create(name)).orElse(null), is(DATA)); } assertThat(res.as(String.class), is(DATA)); @@ -161,12 +163,12 @@ void continuationOutbound() { try (Http2ClientResponse res = Http2Client.builder() .baseUri("http://localhost:" + port + "/") .build() - .method(Http.Method.GET) + .method(Method.GET) .path("/cont-out") .priorKnowledge(true) .headers(hv -> { for (int i = 0; i < 500; i++) { - hv.add(Http.Headers.createCached("test-header-" + i, DATA + i)); + hv.add(HeaderValues.createCached("test-header-" + i, DATA + i)); expected.add("test-header-" + i + "=" + DATA + i); } }) @@ -182,12 +184,12 @@ void continuationOutboundPost() { try (Http2ClientResponse res = Http2Client.builder() .baseUri("http://localhost:" + port + "/") .build() - .method(Http.Method.POST) + .method(Method.POST) .path("/cont-out") .priorKnowledge(true) .headers(hv -> { for (int i = 0; i < 500; i++) { - hv.add(Http.Headers.createCached("test-header-" + i, DATA + i)); + hv.add(HeaderValues.createCached("test-header-" + i, DATA + i)); expected.add("test-header-" + i + "=" + DATA + i); } }) diff --git a/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/Http2ClientTest.java b/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/Http2ClientTest.java index 04abb51e01c..707ce75f9af 100644 --- a/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/Http2ClientTest.java +++ b/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/Http2ClientTest.java @@ -16,28 +16,30 @@ package io.helidon.webclient.tests.http2; +import java.util.function.Supplier; + import io.helidon.common.configurable.Resource; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderNames; import io.helidon.common.pki.Keys; import io.helidon.common.tls.Tls; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; +import io.helidon.webclient.http1.Http1Client; +import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webclient.http2.Http2Client; import io.helidon.webclient.http2.Http2ClientResponse; +import io.helidon.webserver.WebServer; +import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http2.Http2Route; import io.helidon.webserver.testing.junit5.ServerTest; import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webserver.testing.junit5.SetUpServer; -import io.helidon.webclient.http1.Http1Client; -import io.helidon.webclient.http1.Http1ClientResponse; -import io.helidon.webserver.WebServer; -import io.helidon.webserver.WebServerConfig; -import io.helidon.webserver.http.HttpRouting; import org.junit.jupiter.api.Test; -import java.util.function.Supplier; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; @@ -48,7 +50,7 @@ class Http2ClientTest { private static final String MESSAGE = "Hello World!"; private static final String TEST_HEADER_NAME = "custom_header"; private static final String TEST_HEADER_VALUE = "as!fd"; - private static final Header TEST_HEADER = Http.Headers.create(HeaderNames.create(TEST_HEADER_NAME), TEST_HEADER_VALUE); + private static final Header TEST_HEADER = HeaderValues.create(HeaderNames.create(TEST_HEADER_NAME), TEST_HEADER_VALUE); private final Http1Client http1Client; private final Supplier tlsClient; private final Supplier plainClient; @@ -95,7 +97,7 @@ static void setUpServer(WebServerConfig.Builder serverBuilder) { @SetUpRoute static void router(HttpRouting.Builder router) { // explicitly on HTTP/2 only, to make sure we do upgrade - router.route(Http2Route.route(Http.Method.GET, "/", (req, res) -> res.header(TEST_HEADER) + router.route(Http2Route.route(Method.GET, "/", (req, res) -> res.header(TEST_HEADER) .send(MESSAGE))); } @@ -106,7 +108,7 @@ void testHttp1() { .get("/") .request()) { - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } } @@ -131,7 +133,7 @@ void testUpgrade() { .get("/") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is(MESSAGE)); assertThat(TEST_HEADER + " header must be present in response", response.headers().contains(TEST_HEADER), is(true)); @@ -144,7 +146,7 @@ void testAppProtocol() { .get("/") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is(MESSAGE)); assertThat(TEST_HEADER + " header must be present in response", response.headers().contains(TEST_HEADER), is(true)); @@ -158,7 +160,7 @@ void testPriorKnowledge() { .priorKnowledge(true) .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is(MESSAGE)); assertThat(TEST_HEADER + " header must be present in response", response.headers().contains(TEST_HEADER), is(true)); diff --git a/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/PostTest.java b/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/PostTest.java index 7435c002850..1945fb9103b 100644 --- a/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/PostTest.java +++ b/webclient/tests/http2/src/test/java/io/helidon/webclient/tests/http2/PostTest.java @@ -23,10 +23,13 @@ import java.util.OptionalLong; import java.util.Random; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http2.Http2Client; import io.helidon.webclient.http2.Http2ClientResponse; import io.helidon.webserver.WebServer; @@ -46,11 +49,11 @@ class PostTest { private static final byte[] BYTES = new byte[256]; private static final HeaderName REQUEST_HEADER_NAME = HeaderNames.create("X-REquEst-HEADeR"); private static final String REQUEST_HEADER_VALUE_STRING = "some nice value"; - private static final Http.Header REQUEST_HEADER_VALUE = Http.Headers.createCached(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); + private static final Header REQUEST_HEADER_VALUE = HeaderValues.createCached(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); private static final HeaderName RESPONSE_HEADER_NAME = HeaderNames.create("X-REsponSE-HeADER"); private static final String RESPONSE_HEADER_VALUE_STRING = "another nice value"; - private static final Http.Header RESPONSE_HEADER_VALUE = Http.Headers.create(RESPONSE_HEADER_NAME, - RESPONSE_HEADER_VALUE_STRING); + private static final Header RESPONSE_HEADER_VALUE = HeaderValues.create(RESPONSE_HEADER_NAME, + RESPONSE_HEADER_VALUE_STRING); private static WebServer server; private static Http2Client client; @@ -66,11 +69,11 @@ static void startServer() { .host("localhost") .port(-1) .routing(routing -> routing - .route(Http.Method.POST, "/string", Handler.create(String.class, Routes::string)) - .route(Http.Method.POST, "/bytes", Handler.create(byte[].class, Routes::bytes)) - .route(Http.Method.POST, "/chunked", Routes::chunked) - .route(Http.Method.POST, "/headers", Routes::headers) - .route(Http.Method.POST, "/close", Routes::close) + .route(Method.POST, "/string", Handler.create(String.class, Routes::string)) + .route(Method.POST, "/bytes", Handler.create(byte[].class, Routes::bytes)) + .route(Method.POST, "/chunked", Routes::chunked) + .route(Method.POST, "/headers", Routes::headers) + .route(Method.POST, "/close", Routes::close) ) .build() .start(); @@ -91,11 +94,11 @@ static void stopServer() { @Test void testStringRoute() { Http2ClientResponse response = client - .method(Http.Method.POST) + .method(Method.POST) .uri("/string") .submit("Hello"); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); Headers headers = response.headers(); @@ -105,11 +108,11 @@ void testStringRoute() { @Test void testByteRoute() { Http2ClientResponse response = client - .method(Http.Method.POST) + .method(Method.POST) .uri("/bytes") .submit(BYTES); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); byte[] entity = response.entity().as(byte[].class); assertThat(entity, is(BYTES)); Headers headers = response.headers(); @@ -119,14 +122,14 @@ void testByteRoute() { @Test void testChunkedRoute() { Http2ClientResponse response = client - .method(Http.Method.POST) + .method(Method.POST) .uri("/chunked") .outputStream(outputStream -> { outputStream.write(BYTES); outputStream.close(); }); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); byte[] entity = response.entity().as(byte[].class); assertThat(entity, is(BYTES)); } @@ -134,12 +137,12 @@ void testChunkedRoute() { @Test void testHeadersRoute() { Http2ClientResponse response = client - .method(Http.Method.POST) + .method(Method.POST) .uri("/headers") .header(REQUEST_HEADER_VALUE) .submit("Hello"); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); Headers headers = response.headers(); @@ -151,18 +154,18 @@ void testHeadersRoute() { @Test void testCloseRoute() { Http2ClientResponse response = client - .method(Http.Method.POST) + .method(Method.POST) .uri("/close") .submit("Hello"); - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); String entity = response.entity().as(String.class); assertThat(entity, is("")); } private static class Routes { public static void close(ServerRequest req, ServerResponse res) { - res.status(Http.Status.NO_CONTENT_204); + res.status(Status.NO_CONTENT_204); res.send(); } diff --git a/webclient/tests/webclient/src/main/java/io/helidon/webclient/tests/GreetService.java b/webclient/tests/webclient/src/main/java/io/helidon/webclient/tests/GreetService.java index 0f060347fa1..9bc4f33fda9 100644 --- a/webclient/tests/webclient/src/main/java/io/helidon/webclient/tests/GreetService.java +++ b/webclient/tests/webclient/src/main/java/io/helidon/webclient/tests/GreetService.java @@ -25,10 +25,12 @@ import io.helidon.common.context.Context; import io.helidon.common.context.Contexts; -import io.helidon.http.Http; import io.helidon.common.parameters.Parameters; import io.helidon.common.uri.UriFragment; import io.helidon.config.Config; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; +import io.helidon.security.SecurityContext; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webclient.security.WebClientSecurity; @@ -36,7 +38,6 @@ import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; -import io.helidon.security.SecurityContext; import jakarta.json.Json; import jakarta.json.JsonBuilderFactory; @@ -104,8 +105,8 @@ public void routing(HttpRules rules) { private void contentLength(ServerRequest serverRequest, ServerResponse serverResponse) { serverRequest.headers().contentLength() - .ifPresentOrElse(value -> serverResponse.send(Http.HeaderNames.CONTENT_LENGTH + " is " + value), - () -> serverResponse.send("No " + Http.HeaderNames.CONTENT_LENGTH + " has been set")); + .ifPresentOrElse(value -> serverResponse.send(HeaderNames.CONTENT_LENGTH + " is " + value), + () -> serverResponse.send("No " + HeaderNames.CONTENT_LENGTH + " has been set")); } private void basicAuthOutbound(ServerRequest request, ServerResponse response) { @@ -115,7 +116,7 @@ private void basicAuthOutbound(ServerRequest request, ServerResponse response) { + "/greet/secure/basic") .request()) { response.status(clientResponse.status()); - if (clientResponse.status() == Http.Status.OK_200) { + if (clientResponse.status() == Status.OK_200) { response.send(clientResponse.entity().as(String.class)); } else { response.send(); @@ -126,7 +127,7 @@ private void basicAuthOutbound(ServerRequest request, ServerResponse response) { private void valuesPropagated(ServerRequest serverRequest, ServerResponse serverResponse) { String queryParam = serverRequest.query().first("param").orElse("Query param not present"); String fragment = serverRequest.prologue().fragment().value(); - serverResponse.status(Http.Status.OK_200); + serverResponse.status(Status.OK_200); serverResponse.send(queryParam + " " + fragment); } @@ -135,7 +136,7 @@ private void obtainedQuery(ServerRequest serverRequest, ServerResponse serverRes String queryValue = serverRequest.query().first(queryParam).orElse("Query " + queryParam + " param not present"); UriFragment uriFragment = serverRequest.prologue().fragment(); String fragment = uriFragment.hasValue() ? uriFragment.value() : null; - serverResponse.status(Http.Status.OK_200); + serverResponse.status(Status.OK_200); serverResponse.send(queryValue + " " + (fragment == null ? "" : fragment)); } @@ -167,18 +168,18 @@ private void getDefaultMessageHandler(ServerRequest request, * @param response the server response */ private void redirect(ServerRequest request, ServerResponse response) { - response.headers().add(Http.HeaderNames.LOCATION, "http://localhost:" + request.requestedUri().port() + "/greet"); - response.status(Http.Status.MOVED_PERMANENTLY_301).send(); + response.headers().add(HeaderNames.LOCATION, "http://localhost:" + request.requestedUri().port() + "/greet"); + response.status(Status.MOVED_PERMANENTLY_301).send(); } private void redirectPath(ServerRequest request, ServerResponse response) { - response.headers().add(Http.HeaderNames.LOCATION, "/greet"); - response.status(Http.Status.MOVED_PERMANENTLY_301).send(); + response.headers().add(HeaderNames.LOCATION, "/greet"); + response.status(Status.MOVED_PERMANENTLY_301).send(); } private void redirectInfinite(ServerRequest request, ServerResponse response) { - response.headers().add(Http.HeaderNames.LOCATION, "http://localhost:" + request.requestedUri().port() + "/greet/redirect/infinite"); - response.status(Http.Status.MOVED_PERMANENTLY_301).send(); + response.headers().add(HeaderNames.LOCATION, "http://localhost:" + request.requestedUri().port() + "/greet/redirect/infinite"); + response.status(Status.MOVED_PERMANENTLY_301).send(); } private void form(ServerRequest req, ServerResponse res) { @@ -207,7 +208,7 @@ private void updateGreetingHandler(ServerRequest request, JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "Invalid JSON") .build(); - response.status(Http.Status.BAD_REQUEST_400).send(jsonErrorObject); + response.status(Status.BAD_REQUEST_400).send(jsonErrorObject); } } @@ -226,13 +227,13 @@ private void updateGreetingFromJson(JsonObject jo, ServerResponse response) { JsonObject jsonErrorObject = JSON.createObjectBuilder() .add("error", "No greeting provided") .build(); - response.status(Http.Status.BAD_REQUEST_400) + response.status(Status.BAD_REQUEST_400) .send(jsonErrorObject); return; } greeting.set(jo.getString("greeting")); - response.status(Http.Status.NO_CONTENT_204).send(); + response.status(Status.NO_CONTENT_204).send(); } /** @@ -250,7 +251,7 @@ private void contextCheck(ServerRequest request, ServerResponse response) { // Verify that context was propagated with auth enabled if (context.isEmpty()) { - response.status(Http.Status.INTERNAL_SERVER_ERROR_500).send(); + response.status(Status.INTERNAL_SERVER_ERROR_500).send(); return; } @@ -261,7 +262,7 @@ private void contextCheck(ServerRequest request, ServerResponse response) { try (Http1ClientResponse ignored = webClient.get().request()) { Context singleContext = Contexts.context().orElseThrow(); Objects.requireNonNull(singleContext.get(GreetService.class)); - response.status(Http.Status.OK_200); + response.status(Status.OK_200); response.send(); } } diff --git a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/ContextCheckTest.java b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/ContextCheckTest.java index a87a1e16dff..020315d18a0 100644 --- a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/ContextCheckTest.java +++ b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/ContextCheckTest.java @@ -16,7 +16,7 @@ package io.helidon.webclient.tests; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.security.EndpointConfig; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; @@ -41,7 +41,7 @@ void testContextCheck() { .property(EndpointConfig.PROPERTY_OUTBOUND_ID, "jack") .property(EndpointConfig.PROPERTY_OUTBOUND_SECRET, "password") .request()) { - assertThat(r.status().code(), is(Http.Status.OK_200.code())); + assertThat(r.status().code(), is(Status.OK_200.code())); } } } diff --git a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/HeaderTest.java b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/HeaderTest.java index da55a81d76a..3ac2f45a0e4 100644 --- a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/HeaderTest.java +++ b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/HeaderTest.java @@ -17,7 +17,7 @@ import java.util.List; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.webclient.api.WebClientServiceRequest; import io.helidon.webclient.api.WebClientServiceResponse; import io.helidon.webclient.http1.Http1Client; @@ -49,7 +49,7 @@ public void userAgentNotOverridden() { Http1Client webClient = createNewClient(new HeaderTestService(TEST_USER)); webClient.get() - .header(Http.HeaderNames.USER_AGENT, TEST_USER) + .header(HeaderNames.USER_AGENT, TEST_USER) .request(JsonObject.class); } @@ -59,18 +59,18 @@ public void contentLengthSet() { try (Http1ClientResponse res = webClient.post("contentLength").request()) { String contentLength = res.as(String.class); - assertThat(contentLength, is(Http.HeaderNames.CONTENT_LENGTH + " is 0")); + assertThat(contentLength, is(HeaderNames.CONTENT_LENGTH + " is 0")); } try (Http1ClientResponse res = webClient.post("contentLength").request()) { String contentLength = res.as(String.class); - assertThat(contentLength, is(Http.HeaderNames.CONTENT_LENGTH + " is 0")); + assertThat(contentLength, is(HeaderNames.CONTENT_LENGTH + " is 0")); } String sampleSmallEntity = "Hi there"; try (Http1ClientResponse res = webClient.post("contentLength").submit(sampleSmallEntity)) { String contentLength = res.as(String.class); - assertThat(contentLength, is(Http.HeaderNames.CONTENT_LENGTH + " is " + sampleSmallEntity.length())); + assertThat(contentLength, is(HeaderNames.CONTENT_LENGTH + " is " + sampleSmallEntity.length())); } try (Http1ClientResponse res = webClient.post() @@ -80,7 +80,7 @@ public void contentLengthSet() { .path("contentLength") .submit(sampleSmallEntity)) { String contentLength = res.as(String.class); - assertThat(contentLength, is(Http.HeaderNames.CONTENT_LENGTH + " is " + sampleSmallEntity.length())); + assertThat(contentLength, is(HeaderNames.CONTENT_LENGTH + " is " + sampleSmallEntity.length())); } } @@ -88,7 +88,7 @@ private record HeaderTestService(String user) implements WebClientService { @Override public WebClientServiceResponse handle(Chain chain, WebClientServiceRequest request) { - List userAgent = request.headers().all(Http.HeaderNames.USER_AGENT, List::of); + List userAgent = request.headers().all(HeaderNames.USER_AGENT, List::of); assertThat(userAgent, hasSize(1)); assertThat(userAgent, contains(user)); return chain.proceed(request); diff --git a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MediaContextTest.java b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MediaContextTest.java index 7458ce3f871..6595c5ccb15 100644 --- a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MediaContextTest.java +++ b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MediaContextTest.java @@ -18,7 +18,7 @@ import java.io.InputStream; import java.util.Collections; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.http.media.MediaContext; import io.helidon.http.media.UnsupportedTypeException; import io.helidon.webclient.http1.Http1Client; @@ -75,7 +75,7 @@ public void testInputStream() { try (Http1ClientResponse res = client.get().request()) { InputStream is = res.inputStream(); assertAll( - () -> assertThat(res.status(), is(Http.Status.OK_200)), + () -> assertThat(res.status(), is(Status.OK_200)), () -> assertThat(new String(is.readAllBytes()), is("{\"message\":\"Hello World!\"}")) ); } diff --git a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MetricsTest.java b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MetricsTest.java index 29c8331d739..3347ba1db22 100644 --- a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MetricsTest.java +++ b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MetricsTest.java @@ -15,7 +15,7 @@ */ package io.helidon.webclient.tests; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.metrics.api.Counter; import io.helidon.metrics.api.Gauge; import io.helidon.metrics.api.MeterRegistry; @@ -47,7 +47,7 @@ public class MetricsTest extends TestParent { public void testCounter() { WebClientService serviceCounterAll = WebClientMetrics.counter().nameFormat("counter.%1$s.%2$s").build(); WebClientService serviceCounterGet = WebClientMetrics.counter() - .methods(Http.Method.GET) + .methods(Method.GET) .nameFormat("counter.get.%1$s.%2$s") .build(); WebClientService serviceCounterError = WebClientMetrics.counter() @@ -89,7 +89,7 @@ public void testMeter() { .nameFormat("meter.%1$s.%2$s") .build(); WebClientService serviceMeterGet = WebClientMetrics.meter() - .methods(Http.Method.GET) + .methods(Method.GET) .nameFormat("meter.get.%1$s.%2$s") .build(); WebClientService serviceMeterError = WebClientMetrics.meter() @@ -131,11 +131,11 @@ public void testMeter() { public void testGaugeInProgress() { WebClientService inProgressAll = WebClientMetrics.gaugeInProgress().nameFormat("gauge.%1$s.%2$s").build(); WebClientService inProgressPut = WebClientMetrics.gaugeInProgress() - .methods(Http.Method.PUT) + .methods(Method.PUT) .nameFormat("gauge.put.%1$s.%2$s") .build(); WebClientService inProgressGet = WebClientMetrics.gaugeInProgress() - .methods(Http.Method.GET) + .methods(Method.GET) .nameFormat("gauge.get.%1$s.%2$s") .build(); @@ -174,12 +174,12 @@ public void testErrorHandling() { .nameFormat("counter.all.errors.%2$s") .build(); WebClientService errorGet = WebClientMetrics.counter() - .methods(Http.Method.GET) + .methods(Method.GET) .success(false) .nameFormat("counter.errors.%1$s.%2$s") .build(); WebClientService errorPut = WebClientMetrics.counter() - .methods(Http.Method.PUT) + .methods(Method.PUT) .success(false) .nameFormat("counter.errors.%1$s.%2$s") .build(); diff --git a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MutualTlsTest.java b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MutualTlsTest.java index 42aa3fcf164..2a39b85edfe 100644 --- a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MutualTlsTest.java +++ b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/MutualTlsTest.java @@ -18,21 +18,20 @@ import java.io.UncheckedIOException; import java.util.concurrent.atomic.AtomicBoolean; -import io.helidon.http.Http; +import io.helidon.common.tls.Tls; import io.helidon.config.Config; import io.helidon.config.ConfigSources; -import io.helidon.common.tls.Tls; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.HeaderValues; import io.helidon.webclient.http1.Http1Client; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.X_HELIDON_CN; - +import static io.helidon.http.HeaderNames.X_HELIDON_CN; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.endsWith; import static org.hamcrest.CoreMatchers.is; @@ -184,7 +183,7 @@ private static void mTlsRouting(HttpRouting.Builder routing) { routing.get("/", (req, res) -> { // close to avoid re-using cached connections on the client side - res.header(Http.Headers.CONNECTION_CLOSE); + res.header(HeaderValues.CONNECTION_CLOSE); res.send("Hello " + req.headers().value(X_HELIDON_CN).orElse("Unknown CN") + "!"); }); } diff --git a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/RequestTest.java b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/RequestTest.java index 82c22774363..9b263d283d3 100644 --- a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/RequestTest.java +++ b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/RequestTest.java @@ -19,7 +19,7 @@ import java.net.URI; import java.util.Collections; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1ClientRequest; import io.helidon.webclient.http1.Http1ClientResponse; @@ -67,7 +67,7 @@ public void testHelloWorld() { @Test public void testIncorrect() { try (Http1ClientResponse response = client.get("/incorrect").request()) { - if (response.status() != Http.Status.NOT_FOUND_404) { + if (response.status() != Status.NOT_FOUND_404) { fail("This request should be 404!"); } } @@ -84,7 +84,7 @@ public void testFollowRedirect() { .path("/redirect") .followRedirects(false) .request()) { - assertThat(response.status(), is(Http.Status.MOVED_PERMANENTLY_301)); + assertThat(response.status(), is(Status.MOVED_PERMANENTLY_301)); } } @@ -121,7 +121,7 @@ public void testPut() { @Test public void testEntityNotHandled() { try (HttpClientResponse response = client.get("/incorrect").request()) { - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } } diff --git a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/SecurityTest.java b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/SecurityTest.java index 6f036b31868..b3d88348719 100644 --- a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/SecurityTest.java +++ b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/SecurityTest.java @@ -16,7 +16,7 @@ package io.helidon.webclient.tests; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.security.EndpointConfig; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webclient.security.WebClientSecurity; @@ -55,7 +55,7 @@ private void performOperation(String path) { .property(EndpointConfig.PROPERTY_OUTBOUND_SECRET, "password") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(JsonObject.class).getString("message"), is("Hello jack!")); } } diff --git a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/TracingPropagationTest.java b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/TracingPropagationTest.java index 6497937c987..51292c9897f 100644 --- a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/TracingPropagationTest.java +++ b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/TracingPropagationTest.java @@ -25,18 +25,18 @@ import java.util.concurrent.atomic.AtomicReference; import io.helidon.common.context.Context; -import io.helidon.http.Http; import io.helidon.config.Config; +import io.helidon.http.Status; import io.helidon.http.media.MediaContext; import io.helidon.http.media.jsonp.JsonpSupport; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.tracing.Tracer; +import io.helidon.tracing.providers.opentracing.OpenTracing; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webclient.tracing.WebClientTracing; import io.helidon.webserver.WebServerConfig; -import io.helidon.tracing.Tracer; -import io.helidon.tracing.providers.opentracing.OpenTracing; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import io.opentracing.mock.MockSpan; import io.opentracing.mock.MockTracer; @@ -100,7 +100,7 @@ void testTracingSuccess() throws InterruptedException { .queryParam("some", "value") .fragment("fragment") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity().as(JsonObject.class), notNullValue()); } diff --git a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/UriPartTest.java b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/UriPartTest.java index ad93aa404cd..7061c11b72b 100644 --- a/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/UriPartTest.java +++ b/webclient/tests/webclient/src/test/java/io/helidon/webclient/tests/UriPartTest.java @@ -16,7 +16,7 @@ package io.helidon.webclient.tests; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webclient.api.ClientResponseTyped; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.WebClient; @@ -52,7 +52,7 @@ void testQuerySpace() { .queryParam("test", EXPECTED_QUERY) .skipUriEncoding(true) .request()) { - assertThat(fullResponse.status(), is(Http.Status.BAD_REQUEST_400)); + assertThat(fullResponse.status(), is(Status.BAD_REQUEST_400)); } } @@ -104,7 +104,7 @@ void testBadFragment() { .fragment(fragment) .request()) { - assertThat(response.status(), is(Http.Status.BAD_REQUEST_400)); + assertThat(response.status(), is(Status.BAD_REQUEST_400)); } } @@ -150,7 +150,7 @@ void testPathNotDecoded() { .request(String.class); // the path is not valid - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } } diff --git a/webclient/tracing/src/main/java/io/helidon/webclient/tracing/WebClientTracing.java b/webclient/tracing/src/main/java/io/helidon/webclient/tracing/WebClientTracing.java index 3c72a7f30ba..c16b578c6b0 100644 --- a/webclient/tracing/src/main/java/io/helidon/webclient/tracing/WebClientTracing.java +++ b/webclient/tracing/src/main/java/io/helidon/webclient/tracing/WebClientTracing.java @@ -23,7 +23,11 @@ import io.helidon.common.context.Context; import io.helidon.http.ClientRequestHeaders; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.tracing.HeaderConsumer; import io.helidon.tracing.HeaderProvider; import io.helidon.tracing.Span; @@ -97,13 +101,13 @@ public WebClientServiceResponse handle(Chain chain, WebClientServiceRequest requ try { WebClientServiceResponse response = chain.proceed(request); - Http.Status status = response.status(); + Status status = response.status(); span.tag(Tag.HTTP_STATUS.create(status.code())); - Http.Status.Family family = status.family(); + Status.Family family = status.family(); if (status.code() >= 400) { - String errorKind = family == Http.Status.Family.CLIENT_ERROR ? "ClientError" : "ServerError"; + String errorKind = family == Status.Family.CLIENT_ERROR ? "ClientError" : "ServerError"; span.addEvent("error", Map.of("message", "Response HTTP status: " + status, "error.kind", errorKind)); @@ -127,7 +131,7 @@ private ClientHeaderConsumer(ClientRequestHeaders headers) { @Override public void setIfAbsent(String key, String... values) { - Http.HeaderName name = Http.HeaderNames.create(key); + HeaderName name = HeaderNames.create(key); if (!headers.contains(name)) { headers.set(name, values); } @@ -135,29 +139,29 @@ public void setIfAbsent(String key, String... values) { @Override public void set(String key, String... values) { - headers.set(Http.Headers.create(key, values)); + headers.set(HeaderValues.create(key, values)); } @Override public Iterable keys() { return headers.stream() - .map(Http.Header::name) + .map(Header::name) .toList(); } @Override public Optional get(String key) { - return headers.first(Http.HeaderNames.create(key)); + return headers.first(HeaderNames.create(key)); } @Override public Iterable getAll(String key) { - return headers.all(Http.HeaderNames.create(key), List::of); + return headers.all(HeaderNames.create(key), List::of); } @Override public boolean contains(String key) { - return headers.contains(Http.HeaderNames.create(key)); + return headers.contains(HeaderNames.create(key)); } } } diff --git a/webclient/websocket/src/main/java/io/helidon/webclient/websocket/WsClientImpl.java b/webclient/websocket/src/main/java/io/helidon/webclient/websocket/WsClientImpl.java index 5eef11bfd2f..a2f74a49889 100644 --- a/webclient/websocket/src/main/java/io/helidon/webclient/websocket/WsClientImpl.java +++ b/webclient/websocket/src/main/java/io/helidon/webclient/websocket/WsClientImpl.java @@ -30,7 +30,10 @@ import io.helidon.common.uri.UriInfo; import io.helidon.http.ClientRequestHeaders; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.webclient.api.ClientConnection; import io.helidon.webclient.api.ClientUri; import io.helidon.webclient.api.HttpClientResponse; @@ -45,15 +48,15 @@ class WsClientImpl implements WsClient { * Supported WebSocket version. */ static final String SUPPORTED_VERSION = "13"; - static final Http.Header HEADER_UPGRADE_WS = Http.Headers.createCached(Http.HeaderNames.UPGRADE, "websocket"); - static final Http.HeaderName HEADER_WS_PROTOCOL = Http.HeaderNames.create("Sec-WebSocket-Protocol"); - private static final Http.Header HEADER_WS_VERSION = Http.Headers.createCached(Http.HeaderNames.create( + static final Header HEADER_UPGRADE_WS = HeaderValues.createCached(HeaderNames.UPGRADE, "websocket"); + static final HeaderName HEADER_WS_PROTOCOL = HeaderNames.create("Sec-WebSocket-Protocol"); + private static final Header HEADER_WS_VERSION = HeaderValues.createCached(HeaderNames.create( "Sec-WebSocket-Version"), SUPPORTED_VERSION); private static final System.Logger LOGGER = System.getLogger(WsClient.class.getName()); - private static final Http.Header HEADER_CONN_UPGRADE = Http.Headers.create(Http.HeaderNames.CONNECTION, "Upgrade"); - private static final Http.HeaderName HEADER_WS_ACCEPT = Http.HeaderNames.create("Sec-WebSocket-Accept"); - private static final Http.HeaderName HEADER_WS_KEY = Http.HeaderNames.create("Sec-WebSocket-Key"); + private static final Header HEADER_CONN_UPGRADE = HeaderValues.create(HeaderNames.CONNECTION, "Upgrade"); + private static final HeaderName HEADER_WS_ACCEPT = HeaderNames.create("Sec-WebSocket-Accept"); + private static final HeaderName HEADER_WS_KEY = HeaderNames.create("Sec-WebSocket-Key"); private static final LazyValue RANDOM = LazyValue.create(SecureRandom::new); private static final byte[] KEY_SUFFIX = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".getBytes(StandardCharsets.US_ASCII); private static final int KEY_SUFFIX_LENGTH = KEY_SUFFIX.length; @@ -72,7 +75,7 @@ class WsClientImpl implements WsClient { ClientRequestHeaders headers = http1Client.prototype().defaultRequestHeaders(); headers.set(HEADER_UPGRADE_WS); headers.set(HEADER_WS_VERSION); - headers.set(Http.Headers.CONTENT_LENGTH_ZERO); + headers.set(HeaderValues.CONTENT_LENGTH_ZERO); if (clientConfig.protocolConfig().subProtocols().isEmpty()) { headers.remove(HEADER_WS_PROTOCOL); } else { @@ -111,7 +114,7 @@ public void connect(URI uri, WsListener listener) { upgradeRequest.uri(ClientUri.create(resolvedUri).scheme("https")); } - upgradeRequest.headers(headers -> headers.setIfAbsent(Http.Headers.create(Http.HeaderNames.HOST, resolvedUri + upgradeRequest.headers(headers -> headers.setIfAbsent(HeaderValues.create(HeaderNames.HOST, resolvedUri .authority()))); UpgradeResponse upgradeResponse = upgradeRequest.upgrade("websocket"); diff --git a/webserver/access-log/src/main/java/io/helidon/webserver/accesslog/HeaderLogEntry.java b/webserver/access-log/src/main/java/io/helidon/webserver/accesslog/HeaderLogEntry.java index 0d29ae87706..e9d39f915e7 100644 --- a/webserver/access-log/src/main/java/io/helidon/webserver/accesslog/HeaderLogEntry.java +++ b/webserver/access-log/src/main/java/io/helidon/webserver/accesslog/HeaderLogEntry.java @@ -18,8 +18,8 @@ import java.util.List; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; /** * Access log entry for header values. @@ -82,7 +82,7 @@ public static final class Builder extends AbstractLogEntry.Builder httpHeaders = headers.readHeaders(httpPrologue); - boolean hasContent = httpHeaders.contains(Http.HeaderNames.CONTENT_LENGTH); - String authority = httpHeaders.get(Http.HeaderNames.HOST).value(); + boolean hasContent = httpHeaders.contains(HeaderNames.CONTENT_LENGTH); + String authority = httpHeaders.get(HeaderNames.HOST).value(); bh.consume(hasContent); bh.consume(authority); diff --git a/webserver/benchmark/jmh/src/main/java/io/helidon/webserver/benchmark/jmh/HttpJmhTest.java b/webserver/benchmark/jmh/src/main/java/io/helidon/webserver/benchmark/jmh/HttpJmhTest.java index c85e526fe97..134fe3fb8e7 100644 --- a/webserver/benchmark/jmh/src/main/java/io/helidon/webserver/benchmark/jmh/HttpJmhTest.java +++ b/webserver/benchmark/jmh/src/main/java/io/helidon/webserver/benchmark/jmh/HttpJmhTest.java @@ -24,8 +24,10 @@ import java.nio.charset.StandardCharsets; import java.time.Duration; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; import io.helidon.logging.common.LogConfig; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.Handler; @@ -42,10 +44,10 @@ @State(Scope.Benchmark) public class HttpJmhTest { - private static final Http.Header CONTENT_TYPE = Http.Headers.createCached(Http.HeaderNames.CONTENT_TYPE, - "text/plain; charset=UTF-8"); - private static final Http.Header CONTENT_LENGTH = Http.Headers.createCached(HeaderNames.CONTENT_LENGTH, "13"); - private static final Http.Header SERVER = Http.Headers.createCached(Http.HeaderNames.SERVER, "Helidon"); + private static final Header CONTENT_TYPE = HeaderValues.createCached(HeaderNames.CONTENT_TYPE, + "text/plain; charset=UTF-8"); + private static final Header CONTENT_LENGTH = HeaderValues.createCached(HeaderNames.CONTENT_LENGTH, "13"); + private static final Header SERVER = HeaderValues.createCached(HeaderNames.SERVER, "Helidon"); private static final byte[] RESPONSE_BYTES = "Hello, World!".getBytes(StandardCharsets.UTF_8); private WebServer server; private int serverPort; @@ -65,7 +67,7 @@ public void setup() { .writeQueueLength(4000) .host("127.0.0.1") .backlog(8192) - .routing(router -> router.route(Http1Route.route(Http.Method.GET, "/plaintext", new PlaintextHandler()))) + .routing(router -> router.route(Http1Route.route(Method.GET, "/plaintext", new PlaintextHandler()))) .build() .start(); diff --git a/webserver/cors/src/main/java/io/helidon/webserver/cors/CorsServerRequestAdapter.java b/webserver/cors/src/main/java/io/helidon/webserver/cors/CorsServerRequestAdapter.java index d4c835ba9d3..a75c03f0d2d 100644 --- a/webserver/cors/src/main/java/io/helidon/webserver/cors/CorsServerRequestAdapter.java +++ b/webserver/cors/src/main/java/io/helidon/webserver/cors/CorsServerRequestAdapter.java @@ -19,7 +19,7 @@ import java.util.Optional; import io.helidon.cors.CorsRequestAdapter; -import io.helidon.http.Http.HeaderName; +import io.helidon.http.HeaderName; import io.helidon.http.ServerRequestHeaders; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; diff --git a/webserver/cors/src/main/java/io/helidon/webserver/cors/CorsServerResponseAdapter.java b/webserver/cors/src/main/java/io/helidon/webserver/cors/CorsServerResponseAdapter.java index bfb4aa97b36..6abdbc47a25 100644 --- a/webserver/cors/src/main/java/io/helidon/webserver/cors/CorsServerResponseAdapter.java +++ b/webserver/cors/src/main/java/io/helidon/webserver/cors/CorsServerResponseAdapter.java @@ -16,8 +16,8 @@ package io.helidon.webserver.cors; import io.helidon.cors.CorsResponseAdapter; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; +import io.helidon.http.HeaderName; +import io.helidon.http.Status; import io.helidon.webserver.http.ServerResponse; /** @@ -45,13 +45,13 @@ public CorsServerResponseAdapter header(HeaderName key, Object value) { @Override public ServerResponse forbidden(String message) { - serverResponse.status(Http.Status.create(Http.Status.FORBIDDEN_403.code(), message)); + serverResponse.status(Status.create(Status.FORBIDDEN_403.code(), message)); return serverResponse; } @Override public ServerResponse ok() { - serverResponse.status(Http.Status.OK_200); + serverResponse.status(Status.OK_200); return serverResponse; } diff --git a/webserver/cors/src/test/java/io/helidon/webserver/cors/AbstractCorsTest.java b/webserver/cors/src/test/java/io/helidon/webserver/cors/AbstractCorsTest.java index 12b3dda01a7..d484aca0fc4 100644 --- a/webserver/cors/src/test/java/io/helidon/webserver/cors/AbstractCorsTest.java +++ b/webserver/cors/src/test/java/io/helidon/webserver/cors/AbstractCorsTest.java @@ -15,7 +15,9 @@ */ package io.helidon.webserver.cors; -import io.helidon.http.Http; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientRequest; @@ -23,16 +25,16 @@ import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_MAX_AGE; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_REQUEST_HEADERS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD; -import static io.helidon.http.Http.HeaderNames.ORIGIN; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.noHeader; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_MAX_AGE; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_REQUEST_HEADERS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD; +import static io.helidon.http.HeaderNames.ORIGIN; import static io.helidon.webserver.cors.CorsTestServices.SERVICE_1; import static io.helidon.webserver.cors.CorsTestServices.SERVICE_2; import static org.hamcrest.CoreMatchers.containsString; @@ -53,23 +55,23 @@ abstract class AbstractCorsTest extends CorsRouting { @Test void testSimple() { try (Http1ClientResponse response = client().get(contextRoot()) - .header(Http.Headers.ACCEPT_TEXT) + .header(HeaderValues.ACCEPT_TEXT) .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } } @Test void test1PreFlightAllowedHeaders1() { - try (Http1ClientResponse response = client().method(Http.Method.OPTIONS) + try (Http1ClientResponse response = client().method(Method.OPTIONS) .uri(TestUtil.path(SERVICE_1)) .header(ORIGIN, "http://foo.bar") .header(ACCESS_CONTROL_REQUEST_METHOD, "PUT") .header(ACCESS_CONTROL_REQUEST_HEADERS, "X-foo") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "http://foo.bar")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_METHODS, "PUT")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_HEADERS, "X-foo")); @@ -79,14 +81,14 @@ void test1PreFlightAllowedHeaders1() { @Test void test1PreFlightAllowedHeaders2() { - try (Http1ClientResponse response = client().method(Http.Method.OPTIONS) + try (Http1ClientResponse response = client().method(Method.OPTIONS) .uri(TestUtil.path(SERVICE_1)) .header(ORIGIN, "http://foo.bar") .header(ACCESS_CONTROL_REQUEST_METHOD, "PUT") .header(ACCESS_CONTROL_REQUEST_HEADERS, "X-foo, X-bar") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "http://foo.bar")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_METHODS, "PUT")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_HEADERS)); @@ -98,8 +100,8 @@ void test1PreFlightAllowedHeaders2() { @Test void test2PreFlightForbiddenOrigin() { - Http.Status status; - try (Http1ClientResponse response = client().method(Http.Method.OPTIONS) + Status status; + try (Http1ClientResponse response = client().method(Method.OPTIONS) .uri(TestUtil.path(SERVICE_2)) .header(ORIGIN, "http://not.allowed") .header(ACCESS_CONTROL_REQUEST_METHOD, "PUT") @@ -107,13 +109,13 @@ void test2PreFlightForbiddenOrigin() { status = response.status(); } - assertThat(status.code(), is(Http.Status.FORBIDDEN_403.code())); + assertThat(status.code(), is(Status.FORBIDDEN_403.code())); assertThat(status.reasonPhrase(), is("CORS origin is not in allowed list")); } @Test void test2PreFlightAllowedOrigin() { - Http1ClientRequest request = client().method(Http.Method.OPTIONS) + Http1ClientRequest request = client().method(Method.OPTIONS) .uri(TestUtil.path(SERVICE_2)); request.header(ORIGIN, "http://foo.bar"); @@ -121,7 +123,7 @@ void test2PreFlightAllowedOrigin() { try (Http1ClientResponse response = request.request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "http://foo.bar")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_METHODS, "PUT")); @@ -133,23 +135,23 @@ void test2PreFlightAllowedOrigin() { @Test void test2PreFlightForbiddenMethod() { - Http1ClientRequest request = client().method(Http.Method.OPTIONS) + Http1ClientRequest request = client().method(Method.OPTIONS) .uri(TestUtil.path(SERVICE_2)); request.header(ORIGIN, "http://foo.bar"); request.header(ACCESS_CONTROL_REQUEST_METHOD, "POST"); - Http.Status status; + Status status; try (Http1ClientResponse response = request.request()) { status = response.status(); } - assertThat(status.code(), is(Http.Status.FORBIDDEN_403.code())); + assertThat(status.code(), is(Status.FORBIDDEN_403.code())); assertThat(status.reasonPhrase(), is("CORS origin is denied")); } @Test void test2PreFlightForbiddenHeader() { - Http1ClientRequest request = client().method(Http.Method.OPTIONS) + Http1ClientRequest request = client().method(Method.OPTIONS) .uri(TestUtil.path(SERVICE_2)); request.header(ORIGIN, "http://foo.bar"); @@ -157,15 +159,15 @@ void test2PreFlightForbiddenHeader() { request.header(ACCESS_CONTROL_REQUEST_HEADERS, "X-foo, X-bar, X-oops"); try (Http1ClientResponse response = request.request()) { - Http.Status status = response.status(); - assertThat(status.code(), is(Http.Status.FORBIDDEN_403.code())); + Status status = response.status(); + assertThat(status.code(), is(Status.FORBIDDEN_403.code())); assertThat(status.reasonPhrase(), is("CORS headers not in allowed list")); } } @Test void test2PreFlightAllowedHeaders1() { - Http1ClientRequest request = client().method(Http.Method.OPTIONS) + Http1ClientRequest request = client().method(Method.OPTIONS) .uri(TestUtil.path(contextRoot(), SERVICE_2)); request.header(ORIGIN, fooOrigin()); @@ -174,7 +176,7 @@ void test2PreFlightAllowedHeaders1() { try (Http1ClientResponse response = request.request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers() .get(ACCESS_CONTROL_ALLOW_ORIGIN).value(), is(fooOrigin())); assertThat(response.headers() @@ -189,7 +191,7 @@ void test2PreFlightAllowedHeaders1() { @Test void test2PreFlightAllowedHeaders2() { - Http1ClientRequest request = client().method(Http.Method.OPTIONS) + Http1ClientRequest request = client().method(Method.OPTIONS) .uri(TestUtil.path(SERVICE_2)); request.header(ORIGIN, "http://foo.bar"); @@ -198,7 +200,7 @@ void test2PreFlightAllowedHeaders2() { try (Http1ClientResponse response = request.request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "http://foo.bar")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_METHODS, "PUT")); @@ -210,7 +212,7 @@ void test2PreFlightAllowedHeaders2() { @Test void test2PreFlightAllowedHeaders3() { - Http1ClientRequest request = client().method(Http.Method.OPTIONS) + Http1ClientRequest request = client().method(Method.OPTIONS) .uri(TestUtil.path(SERVICE_2)); request.header(ORIGIN, "http://foo.bar"); @@ -220,7 +222,7 @@ void test2PreFlightAllowedHeaders3() { try (Http1ClientResponse response = request.request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "http://foo.bar")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_METHODS, "PUT")); @@ -232,31 +234,31 @@ void test2PreFlightAllowedHeaders3() { @Test void test1ActualAllowedOrigin() { - Http1ClientRequest request = client().method(Http.Method.PUT) + Http1ClientRequest request = client().method(Method.PUT) .uri(TestUtil.path(SERVICE_1)) - .header(Http.Headers.CONTENT_TYPE_TEXT_PLAIN); + .header(HeaderValues.CONTENT_TYPE_TEXT_PLAIN); request.header(ORIGIN, "http://foo.bar"); request.header(ACCESS_CONTROL_REQUEST_METHOD, "PUT"); try (HttpClientResponse response = request.submit("")) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "*")); } } @Test void test2ActualAllowedOrigin() { - Http1ClientRequest request = client().method(Http.Method.PUT) + Http1ClientRequest request = client().method(Method.PUT) .uri(TestUtil.path(SERVICE_2)) - .header(Http.Headers.CONTENT_TYPE_TEXT_PLAIN); + .header(HeaderValues.CONTENT_TYPE_TEXT_PLAIN); request.header(ORIGIN, "http://foo.bar"); try (HttpClientResponse response = request.submit("")) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "http://foo.bar")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")); } @@ -265,19 +267,19 @@ void test2ActualAllowedOrigin() { @Test void test2ErrorResponse() { Http1ClientRequest request = client().get(TestUtil.path(SERVICE_2) + "/notfound") - .header(Http.Headers.CONTENT_TYPE_TEXT_PLAIN); + .header(HeaderValues.CONTENT_TYPE_TEXT_PLAIN); request.header(ORIGIN, "http://foo.bar"); try (HttpClientResponse response = request.request()) { - assertThat(response.status(), is(not(Http.Status.OK_200))); + assertThat(response.status(), is(not(Status.OK_200))); assertThat(response.headers(), noHeader(ACCESS_CONTROL_ALLOW_ORIGIN)); } } HttpClientResponse runTest1PreFlightAllowedOrigin() { - Http1ClientRequest request = client().method(Http.Method.OPTIONS) + Http1ClientRequest request = client().method(Method.OPTIONS) .uri(TestUtil.path(contextRoot(), SERVICE_1)); request.header(ORIGIN, fooOrigin()); diff --git a/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsRouting.java b/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsRouting.java index f405ebd33c9..fdbe59dc13b 100644 --- a/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsRouting.java +++ b/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsRouting.java @@ -16,12 +16,12 @@ package io.helidon.webserver.cors; -import io.helidon.http.Http; import io.helidon.config.Config; import io.helidon.config.ConfigSources; import io.helidon.cors.CrossOriginConfig; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.SetUpRoute; import static io.helidon.webserver.cors.CorsTestServices.SERVICE_3; @@ -67,12 +67,12 @@ static void routing(HttpRules routing) { new TestUtil.GreetService("Other Hello")) .any(TestHandlerRegistration.CORS4_CONTEXT_ROOT, CorsSupport.create(somewhatRestrictedConfig), // handler settings from config subnode - (req, resp) -> resp.status(Http.Status.OK_200).send()) + (req, resp) -> resp.status(Status.OK_200).send()) .get(TestHandlerRegistration.CORS4_CONTEXT_ROOT, // handler settings in-line CorsSupport.builder() .allowOrigins("*") .allowMethods("GET") .build(), - (req, resp) -> resp.status(Http.Status.OK_200).send()); + (req, resp) -> resp.status(Status.OK_200).send()); } } diff --git a/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsTest.java b/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsTest.java index c1f146cabf0..7715bf9b9cb 100644 --- a/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsTest.java +++ b/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsTest.java @@ -16,19 +16,19 @@ package io.helidon.webserver.cors; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; +import io.helidon.webserver.testing.junit5.ServerTest; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_MAX_AGE; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.noHeader; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_MAX_AGE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -66,7 +66,7 @@ void test1PreFlightAllowedOrigin() { String origin = fooOrigin(); HttpClientResponse response = runTest1PreFlightAllowedOrigin(); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_ORIGIN, origin)); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_METHODS, "PUT")); assertThat(response.headers(), noHeader(ACCESS_CONTROL_ALLOW_HEADERS)); diff --git a/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsTestServices.java b/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsTestServices.java index f62672deae1..af4baf6638a 100644 --- a/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsTestServices.java +++ b/webserver/cors/src/test/java/io/helidon/webserver/cors/CorsTestServices.java @@ -17,7 +17,7 @@ import java.util.List; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -51,7 +51,7 @@ String path() { } void ok(ServerRequest request, ServerResponse response) { - response.status(Http.Status.OK_200); + response.status(Status.OK_200); response.send(); } } diff --git a/webserver/cors/src/test/java/io/helidon/webserver/cors/TestDefaultCorsSupport.java b/webserver/cors/src/test/java/io/helidon/webserver/cors/TestDefaultCorsSupport.java index 2098b59e90f..349aa3c7977 100644 --- a/webserver/cors/src/test/java/io/helidon/webserver/cors/TestDefaultCorsSupport.java +++ b/webserver/cors/src/test/java/io/helidon/webserver/cors/TestDefaultCorsSupport.java @@ -15,9 +15,9 @@ */ package io.helidon.webserver.cors; +import io.helidon.http.HeaderNames; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.WebClient; import io.helidon.webserver.WebServer; @@ -25,9 +25,9 @@ import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.noHeader; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -42,7 +42,7 @@ static void prepRouting(HttpRules rules, boolean withCors) { } rules.get("/greet", (req, res) -> res.send("Hello World!")) - .options("/greet", (req, res) -> res.status(Http.Status.OK_200).send()); + .options("/greet", (req, res) -> res.status(Status.OK_200).send()); } @Test @@ -86,7 +86,7 @@ void testOptionsWithCors() { try (HttpClientResponse response = client.get("/greet") .header(HeaderNames.ORIGIN, "http://foo.com") - .header(Http.HeaderNames.HOST, "bar.com") + .header(HeaderNames.HOST, "bar.com") .request()) { Headers headers = response.headers(); @@ -113,8 +113,8 @@ void testOptionsWithoutCors() { .build(); try (HttpClientResponse response = client.get("/greet") - .header(Http.HeaderNames.ORIGIN, "http://foo.com") - .header(Http.HeaderNames.HOST, "bar.com") + .header(HeaderNames.ORIGIN, "http://foo.com") + .header(HeaderNames.HOST, "bar.com") .request()) { assertThat(response.headers(), noHeader(ACCESS_CONTROL_ALLOW_ORIGIN)); diff --git a/webserver/cors/src/test/java/io/helidon/webserver/cors/TestHandlerRegistration.java b/webserver/cors/src/test/java/io/helidon/webserver/cors/TestHandlerRegistration.java index 3ac91208e0c..d927e0a0f8e 100644 --- a/webserver/cors/src/test/java/io/helidon/webserver/cors/TestHandlerRegistration.java +++ b/webserver/cors/src/test/java/io/helidon/webserver/cors/TestHandlerRegistration.java @@ -16,20 +16,21 @@ package io.helidon.webserver.cors; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; +import io.helidon.webserver.testing.junit5.ServerTest; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_REQUEST_HEADERS; -import static io.helidon.http.Http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD; -import static io.helidon.http.Http.HeaderNames.ORIGIN; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_REQUEST_HEADERS; +import static io.helidon.http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD; +import static io.helidon.http.HeaderNames.ORIGIN; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -47,14 +48,14 @@ class TestHandlerRegistration extends CorsRouting { @Test void test4PreFlightAllowedHeaders2() { - try (HttpClientResponse response = client.method(Http.Method.OPTIONS) + try (HttpClientResponse response = client.method(Method.OPTIONS) .uri(CORS4_CONTEXT_ROOT) .header(ORIGIN, "http://foo.bar") .header(ACCESS_CONTROL_REQUEST_METHOD, "PUT") .header(ACCESS_CONTROL_REQUEST_HEADERS, "X-foo, X-bar") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_ORIGIN, "http://foo.bar")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_METHODS, "PUT")); assertThat(response.headers(), hasHeader(ACCESS_CONTROL_ALLOW_HEADERS)); diff --git a/webserver/cors/src/test/java/io/helidon/webserver/cors/TestTwoCorsConfigs.java b/webserver/cors/src/test/java/io/helidon/webserver/cors/TestTwoCorsConfigs.java index 04fbf8e77c0..cdec414870f 100644 --- a/webserver/cors/src/test/java/io/helidon/webserver/cors/TestTwoCorsConfigs.java +++ b/webserver/cors/src/test/java/io/helidon/webserver/cors/TestTwoCorsConfigs.java @@ -16,10 +16,10 @@ package io.helidon.webserver.cors; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; +import io.helidon.webserver.testing.junit5.ServerTest; import org.junit.jupiter.api.Test; @@ -58,8 +58,8 @@ String fooHeader() { void test1PreFlightAllowedOriginOtherGreeting() { HttpClientResponse response = runTest1PreFlightAllowedOrigin(); - Http.Status status = response.status(); - assertThat(status.code(), is(Http.Status.FORBIDDEN_403.code())); + Status status = response.status(); + assertThat(status.code(), is(Status.FORBIDDEN_403.code())); assertThat(status.reasonPhrase(), is("CORS origin is denied")); } diff --git a/webserver/cors/src/test/java/io/helidon/webserver/cors/TestUtil.java b/webserver/cors/src/test/java/io/helidon/webserver/cors/TestUtil.java index 2a4554a0be6..e900bd10c83 100644 --- a/webserver/cors/src/test/java/io/helidon/webserver/cors/TestUtil.java +++ b/webserver/cors/src/test/java/io/helidon/webserver/cors/TestUtil.java @@ -17,7 +17,7 @@ import java.util.Date; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.HttpService; import io.helidon.webserver.http.ServerRequest; @@ -59,7 +59,7 @@ public void routing(HttpRules rules) { void getDefaultMessageHandler(ServerRequest request, ServerResponse response) { String msg = String.format("%s %s!", greeting, new Date().toString()); - response.status(Http.Status.OK_200); + response.status(Status.OK_200); response.send(msg); } diff --git a/webserver/graphql/src/test/java/io/helidon/webserver/graphql/GraphQlServiceTest.java b/webserver/graphql/src/test/java/io/helidon/webserver/graphql/GraphQlServiceTest.java index c7631917460..a5283b19efa 100644 --- a/webserver/graphql/src/test/java/io/helidon/webserver/graphql/GraphQlServiceTest.java +++ b/webserver/graphql/src/test/java/io/helidon/webserver/graphql/GraphQlServiceTest.java @@ -16,12 +16,12 @@ package io.helidon.webserver.graphql; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import graphql.schema.GraphQLSchema; import graphql.schema.StaticDataFetcher; @@ -55,7 +55,7 @@ static void routing(HttpRouting.Builder builder) { void testHelloWorld() { try (Http1ClientResponse response = client.post("/graphql") .submit("{\"query\": \"{hello}\"}")) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat("POST errors: " + json.get("errors"), json, notNullValue()); assertThat("POST", json.get("data").asJsonObject().getJsonString("hello").getString(), is("world")); @@ -64,7 +64,7 @@ void testHelloWorld() { try (Http1ClientResponse response = client.get("/graphql") .queryParam("query", "{hello}") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat("GET errors: " + json.get("errors"), json, notNullValue()); assertThat("GET", json.get("data").asJsonObject().getJsonString("hello").getString(), is("world")); diff --git a/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcProtocolHandler.java b/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcProtocolHandler.java index 88675304d1d..cf0e9664d5f 100644 --- a/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcProtocolHandler.java +++ b/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcProtocolHandler.java @@ -21,9 +21,9 @@ import java.io.InputStream; import io.helidon.common.buffers.BufferData; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.HttpPrologue; import io.helidon.http.WritableHeaders; import io.helidon.http.http2.Http2Flag; @@ -49,8 +49,8 @@ class GrpcProtocolHandler implements Http2SubProtocolSelector.SubProtocolHandler { private static final System.Logger LOGGER = System.getLogger(GrpcProtocolHandler.class.getName()); - private static final Header GRPC_CONTENT_TYPE = Http.Headers.createCached(HeaderNames.CONTENT_TYPE, "application/grpc"); - private static final Header GRPC_ENCODING_IDENTITY = Http.Headers.createCached("grpc-encoding", "identity"); + private static final Header GRPC_CONTENT_TYPE = HeaderValues.createCached(HeaderNames.CONTENT_TYPE, "application/grpc"); + private static final Header GRPC_ENCODING_IDENTITY = HeaderValues.createCached("grpc-encoding", "identity"); private final HttpPrologue prologue; private final Http2Headers headers; @@ -166,7 +166,7 @@ public void sendHeaders(Metadata headers) { writable.set(GRPC_ENCODING_IDENTITY); Http2Headers http2Headers = Http2Headers.create(writable); - http2Headers.status(Http.Status.OK_200); + http2Headers.status(io.helidon.http.Status.OK_200); streamWriter.writeHeaders(http2Headers, streamId, Http2Flag.HeaderFlags.create(Http2Flag.END_OF_HEADERS), @@ -203,13 +203,13 @@ public void close(Status status, Metadata trailers) { // write the expected gRPC headers for content type and status writable.set(GRPC_CONTENT_TYPE); - writable.set(Http.Headers.create(GrpcStatus.STATUS_NAME, status.getCode().value())); + writable.set(HeaderValues.create(GrpcStatus.STATUS_NAME, status.getCode().value())); String description = status.getDescription(); if (description != null) { - writable.set(Http.Headers.create(GrpcStatus.MESSAGE_NAME, description)); + writable.set(HeaderValues.create(GrpcStatus.MESSAGE_NAME, description)); } - Http2Headers http2Headers = Http2Headers.create(writable).status(Http.Status.OK_200); + Http2Headers http2Headers = Http2Headers.create(writable).status(io.helidon.http.Status.OK_200); streamWriter.writeHeaders(http2Headers, streamId, Http2Flag.HeaderFlags.create(Http2Flag.END_OF_HEADERS | Http2Flag.END_OF_STREAM), diff --git a/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcProtocolSelector.java b/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcProtocolSelector.java index 7f7dd6514ff..3c7d108a0ad 100644 --- a/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcProtocolSelector.java +++ b/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcProtocolSelector.java @@ -16,9 +16,10 @@ package io.helidon.webserver.grpc; +import io.helidon.http.HeaderNames; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpPrologue; +import io.helidon.http.Method; import io.helidon.http.http2.Http2Headers; import io.helidon.http.http2.Http2Settings; import io.helidon.http.http2.Http2StreamState; @@ -56,15 +57,15 @@ public SubProtocolResult subProtocol(ConnectionContext ctx, StreamFlowControl flowControl, Http2StreamState currentStreamState, Router router) { - if (prologue.method() != Http.Method.POST) { + if (prologue.method() != Method.POST) { return NOT_SUPPORTED; } // we know this is HTTP/2, so no need to check protocol and version Headers httpHeaders = headers.httpHeaders(); - if (httpHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { - String contentType = httpHeaders.get(Http.HeaderNames.CONTENT_TYPE).value(); + if (httpHeaders.contains(HeaderNames.CONTENT_TYPE)) { + String contentType = httpHeaders.get(HeaderNames.CONTENT_TYPE).value(); if (contentType.startsWith("application/grpc")) { GrpcRouting routing = router.routing(GrpcRouting.class, GrpcRouting.empty()); diff --git a/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcStatus.java b/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcStatus.java index cd8681a5bcb..faa66f2a894 100644 --- a/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcStatus.java +++ b/webserver/grpc/src/main/java/io/helidon/webserver/grpc/GrpcStatus.java @@ -16,10 +16,10 @@ package io.helidon.webserver.grpc; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderName; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.grpc.Status; @@ -42,11 +42,11 @@ public final class GrpcStatus { /** * The operation completed successfully. */ - public static final Header OK = Http.Headers.createCached(STATUS_NAME, Status.Code.OK.value()); + public static final Header OK = HeaderValues.createCached(STATUS_NAME, Status.Code.OK.value()); /** * The operation was cancelled (typically by the caller). */ - public static final Http.Header CANCELLED = Http.Headers.createCached(STATUS_NAME, Status.Code.CANCELLED.value()); + public static final Header CANCELLED = HeaderValues.createCached(STATUS_NAME, Status.Code.CANCELLED.value()); /** * Unknown error. An example of where this error may be returned is * if a Status value received from another address space belongs to @@ -54,14 +54,14 @@ public final class GrpcStatus { * errors raised by APIs that do not return enough error information * may be converted to this error. */ - public static final Http.Header UNKNOWN = Http.Headers.createCached(STATUS_NAME, Status.Code.UNKNOWN.value()); + public static final Header UNKNOWN = HeaderValues.createCached(STATUS_NAME, Status.Code.UNKNOWN.value()); /** * Client specified an invalid argument. Note that this differs * from FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments * that are problematic regardless of the state of the system * (e.g., a malformed file name). */ - public static final Header INVALID_ARGUMENT = Http.Headers.createCached(STATUS_NAME, Status.Code.INVALID_ARGUMENT.value()); + public static final Header INVALID_ARGUMENT = HeaderValues.createCached(STATUS_NAME, Status.Code.INVALID_ARGUMENT.value()); /** * Deadline expired before operation could complete. For operations * that change the state of the system, this error may be returned @@ -69,16 +69,16 @@ public final class GrpcStatus { * successful response from a server could have been delayed long * enough for the deadline to expire. */ - public static final Http.Header DEADLINE_EXCEEDED = - Http.Headers.createCached(STATUS_NAME, Status.Code.DEADLINE_EXCEEDED.value()); + public static final Header DEADLINE_EXCEEDED = + HeaderValues.createCached(STATUS_NAME, Status.Code.DEADLINE_EXCEEDED.value()); /** * Some requested entity (e.g., file or directory) was not found. */ - public static final Header NOT_FOUND = Http.Headers.createCached(STATUS_NAME, Status.Code.NOT_FOUND.value()); + public static final Header NOT_FOUND = HeaderValues.createCached(STATUS_NAME, Status.Code.NOT_FOUND.value()); /** * Some entity that we attempted to create (e.g., file or directory) already exists. */ - public static final Header ALREADY_EXISTS = Http.Headers.createCached(STATUS_NAME, Status.Code.ALREADY_EXISTS.value()); + public static final Header ALREADY_EXISTS = HeaderValues.createCached(STATUS_NAME, Status.Code.ALREADY_EXISTS.value()); /** * The caller does not have permission to execute the specified * operation. PERMISSION_DENIED must not be used for rejections @@ -87,14 +87,14 @@ public final class GrpcStatus { * used if the caller cannot be identified (use UNAUTHENTICATED * instead for those errors). */ - public static final Http.Header PERMISSION_DENIED = - Http.Headers.createCached(STATUS_NAME, Status.Code.PERMISSION_DENIED.value()); + public static final Header PERMISSION_DENIED = + HeaderValues.createCached(STATUS_NAME, Status.Code.PERMISSION_DENIED.value()); /** * Some resource has been exhausted, perhaps a per-user quota, or * perhaps the entire file system is out of space. */ - public static final Http.Header RESOURCE_EXHAUSTED = - Http.Headers.createCached(STATUS_NAME, Status.Code.RESOURCE_EXHAUSTED.value()); + public static final Header RESOURCE_EXHAUSTED = + HeaderValues.createCached(STATUS_NAME, Status.Code.RESOURCE_EXHAUSTED.value()); /** * Operation was rejected because the system is not in a state * required for the operation's execution. For example, directory @@ -112,8 +112,8 @@ public final class GrpcStatus { * should be returned since the client should not retry unless * they have first fixed up the directory by deleting files from it. */ - public static final Http.Header FAILED_PRECONDITION = Http.Headers.createCached(STATUS_NAME, - Status.Code.FAILED_PRECONDITION.value()); + public static final Header FAILED_PRECONDITION = HeaderValues.createCached(STATUS_NAME, + Status.Code.FAILED_PRECONDITION.value()); /** * The operation was aborted, typically due to a concurrency issue * like sequencer check failures, transaction aborts, etc. @@ -121,7 +121,7 @@ public final class GrpcStatus { *

See litmus test above for deciding between FAILED_PRECONDITION, * ABORTED, and UNAVAILABLE. */ - public static final Header ABORTED = Http.Headers.createCached(STATUS_NAME, Status.Code.ABORTED.value()); + public static final Header ABORTED = HeaderValues.createCached(STATUS_NAME, Status.Code.ABORTED.value()); /** * Operation was attempted past the valid range. E.g., seeking or * reading past end of file. @@ -138,17 +138,17 @@ public final class GrpcStatus { * so that callers who are iterating through * a space can easily look for an OUT_OF_RANGE error to detect when they are done. */ - public static final Http.Header OUT_OF_RANGE = Http.Headers.createCached(STATUS_NAME, Status.Code.OUT_OF_RANGE.value()); + public static final Header OUT_OF_RANGE = HeaderValues.createCached(STATUS_NAME, Status.Code.OUT_OF_RANGE.value()); /** * Operation is not implemented or not supported/enabled in this service. */ - public static final Http.Header UNIMPLEMENTED = Http.Headers.createCached(STATUS_NAME, Status.Code.UNIMPLEMENTED.value()); + public static final Header UNIMPLEMENTED = HeaderValues.createCached(STATUS_NAME, Status.Code.UNIMPLEMENTED.value()); /** * Internal errors. Means some invariants expected by underlying * system has been broken. If you see one of these errors, * something is very broken. */ - public static final Header INTERNAL = Http.Headers.createCached(STATUS_NAME, Status.Code.INTERNAL.value()); + public static final Header INTERNAL = HeaderValues.createCached(STATUS_NAME, Status.Code.INTERNAL.value()); /** * The service is currently unavailable. This is a most likely a * transient condition and may be corrected by retrying with @@ -158,16 +158,16 @@ public final class GrpcStatus { *

See litmus test above for deciding between FAILED_PRECONDITION, * ABORTED, and UNAVAILABLE. */ - public static final Header UNAVAILABLE = Http.Headers.createCached(STATUS_NAME, Status.Code.UNAVAILABLE.value()); + public static final Header UNAVAILABLE = HeaderValues.createCached(STATUS_NAME, Status.Code.UNAVAILABLE.value()); /** * Unrecoverable data loss or corruption. */ - public static final Http.Header DATA_LOSS = Http.Headers.createCached(STATUS_NAME, Status.Code.DATA_LOSS.value()); + public static final Header DATA_LOSS = HeaderValues.createCached(STATUS_NAME, Status.Code.DATA_LOSS.value()); /** * The request does not have valid authentication credentials for the * operation. */ - public static final Http.Header UNAUTHENTICATED = Http.Headers.createCached(STATUS_NAME, Status.Code.UNAUTHENTICATED.value()); + public static final Header UNAUTHENTICATED = HeaderValues.createCached(STATUS_NAME, Status.Code.UNAUTHENTICATED.value()); private GrpcStatus() { } diff --git a/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2Connection.java b/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2Connection.java index 9d87c6ae00b..3e77b2bec29 100644 --- a/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2Connection.java +++ b/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2Connection.java @@ -31,9 +31,11 @@ import io.helidon.common.buffers.DataReader; import io.helidon.common.task.InterruptableTask; import io.helidon.common.tls.TlsUtils; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.DateTime; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.HttpPrologue; +import io.helidon.http.Method; import io.helidon.http.WritableHeaders; import io.helidon.http.http2.ConnectionFlowControl; import io.helidon.http.http2.Http2ConnectionWriter; @@ -64,7 +66,7 @@ import io.helidon.webserver.http2.spi.Http2SubProtocolSelector; import io.helidon.webserver.spi.ServerConnection; -import static io.helidon.http.Http.HeaderNames.X_HELIDON_CN; +import static io.helidon.http.HeaderNames.X_HELIDON_CN; import static io.helidon.http.http2.Http2Util.PREFACE_LENGTH; import static java.lang.System.Logger.Level.DEBUG; import static java.lang.System.Logger.Level.TRACE; @@ -142,7 +144,7 @@ public class Http2Connection implements ServerConnection, InterruptableTask methodPredicate; + private final Predicate methodPredicate; private final PathMatcher pathMatcher; private final Handler handler; - private Http2Route(Predicate methodPredicate, PathMatcher pathMatcher, Handler handler) { + private Http2Route(Predicate methodPredicate, PathMatcher pathMatcher, Handler handler) { this.methodPredicate = methodPredicate; this.pathMatcher = pathMatcher; this.handler = handler; @@ -49,8 +49,8 @@ private Http2Route(Predicate methodPredicate, PathMatcher pathMatch * @param handler handler * @return a new route */ - public static Http2Route route(Http.Method method, String path, Handler handler) { - return new Http2Route(Http.Method.predicate(method), + public static Http2Route route(Method method, String path, Handler handler) { + return new Http2Route(Method.predicate(method), PathMatchers.create(path), handler); } diff --git a/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerRequest.java b/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerRequest.java index a6cf4a232c5..2fd994c9e9d 100644 --- a/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerRequest.java +++ b/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerRequest.java @@ -25,7 +25,7 @@ import io.helidon.common.socket.PeerInfo; import io.helidon.common.uri.UriInfo; import io.helidon.common.uri.UriQuery; -import io.helidon.http.Http; +import io.helidon.http.Header; import io.helidon.http.HttpPrologue; import io.helidon.http.RoutedPath; import io.helidon.http.ServerRequestHeaders; @@ -153,7 +153,7 @@ public String authority() { } @Override - public void header(Http.Header header) { + public void header(Header header) { if (writable == null) { writable = WritableHeaders.create(headers); } diff --git a/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerResponse.java b/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerResponse.java index 8cab93dfe27..88da4be8d34 100644 --- a/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerResponse.java +++ b/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerResponse.java @@ -21,11 +21,12 @@ import java.io.UncheckedIOException; import io.helidon.common.buffers.BufferData; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderNames; -import io.helidon.http.Http.Headers; +import io.helidon.http.DateTime; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.ServerResponseHeaders; +import io.helidon.http.Status; import io.helidon.http.http2.FlowControl; import io.helidon.http.http2.Http2Flag; import io.helidon.http.http2.Http2Flag.DataFlags; @@ -84,11 +85,11 @@ public void send(byte[] entityBytes) { // handle content encoding byte[] bytes = entityBytes(entityBytes); - headers.setIfAbsent(Headers.create(HeaderNames.CONTENT_LENGTH, - true, - false, - String.valueOf(bytes.length))); - headers.setIfAbsent(Headers.create(HeaderNames.DATE, true, false, Http.DateTime.rfc1123String())); + headers.setIfAbsent(HeaderValues.create(HeaderNames.CONTENT_LENGTH, + true, + false, + String.valueOf(bytes.length))); + headers.setIfAbsent(HeaderValues.create(HeaderNames.DATE, true, false, DateTime.rfc1123String())); Http2Headers http2Headers = Http2Headers.create(headers); http2Headers.status(status()); @@ -178,7 +179,7 @@ private static class BlockingOutputStream extends OutputStream { private final Http2StreamWriter writer; private final int streamId; private final FlowControl.Outbound flowControl; - private final Http.Status status; + private final Status status; private final Runnable responseCloseRunnable; private BufferData firstBuffer; @@ -190,7 +191,7 @@ private BlockingOutputStream(ServerResponseHeaders headers, Http2StreamWriter writer, int streamId, FlowControl.Outbound flowControl, - Http.Status status, + Status status, Runnable responseCloseRunnable) { this.headers = headers; @@ -268,16 +269,16 @@ private void write(BufferData buffer) throws IOException { private void sendFirstChunkOnly() { int contentLength; if (firstBuffer == null) { - headers.set(Headers.CONTENT_LENGTH_ZERO); + headers.set(HeaderValues.CONTENT_LENGTH_ZERO); contentLength = 0; } else { - headers.set(Headers.create(HeaderNames.CONTENT_LENGTH, - true, - false, - String.valueOf(firstBuffer.available()))); + headers.set(HeaderValues.create(HeaderNames.CONTENT_LENGTH, + true, + false, + String.valueOf(firstBuffer.available()))); contentLength = firstBuffer.available(); } - headers.setIfAbsent(Headers.create(HeaderNames.DATE, true, false, Http.DateTime.rfc1123String())); + headers.setIfAbsent(HeaderValues.create(HeaderNames.DATE, true, false, DateTime.rfc1123String())); Http2Headers http2Headers = Http2Headers.create(headers); http2Headers.status(status); @@ -307,7 +308,7 @@ private void sendFirstChunkOnly() { } private void sendHeadersAndPrepare() { - headers.setIfAbsent(Headers.create(HeaderNames.DATE, true, false, Http.DateTime.rfc1123String())); + headers.setIfAbsent(HeaderValues.create(HeaderNames.DATE, true, false, DateTime.rfc1123String())); Http2Headers http2Headers = Http2Headers.create(headers); http2Headers.status(status); diff --git a/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerStream.java b/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerStream.java index 257eac78a68..34c06361017 100644 --- a/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerStream.java +++ b/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2ServerStream.java @@ -25,12 +25,13 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.socket.SocketWriterException; import io.helidon.http.DirectHandler; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.Headers; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; import io.helidon.http.HttpPrologue; import io.helidon.http.RequestException; import io.helidon.http.ServerResponseHeaders; +import io.helidon.http.Status; import io.helidon.http.encoding.ContentDecoder; import io.helidon.http.encoding.ContentEncodingContext; import io.helidon.http.http2.ConnectionFlowControl; @@ -297,7 +298,7 @@ public void run() { ServerResponseHeaders headers = response.headers(); byte[] message = response.entity().orElse(BufferData.EMPTY_BYTES); if (message.length != 0) { - headers.set(Http.Headers.create(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(message.length))); + headers.set(HeaderValues.create(HeaderNames.CONTENT_LENGTH, String.valueOf(message.length))); } Http2Headers http2Headers = Http2Headers.create(headers); if (message.length == 0) { @@ -355,7 +356,7 @@ private BufferData readEntityFromPipeline() { private void handle() { Headers httpHeaders = headers.httpHeaders(); - if (httpHeaders.contains(Http.HeaderNames.CONTENT_LENGTH)) { + if (httpHeaders.contains(HeaderNames.CONTENT_LENGTH)) { this.expectedLength = httpHeaders.get(HeaderNames.CONTENT_LENGTH).get(long.class); } @@ -382,14 +383,14 @@ private void handle() { ContentEncodingContext contentEncodingContext = ctx.listenerContext().contentEncodingContext(); ContentDecoder decoder; if (contentEncodingContext.contentDecodingEnabled()) { - if (httpHeaders.contains(Http.HeaderNames.CONTENT_ENCODING)) { - String contentEncoding = httpHeaders.get(Http.HeaderNames.CONTENT_ENCODING).get(); + if (httpHeaders.contains(HeaderNames.CONTENT_ENCODING)) { + String contentEncoding = httpHeaders.get(HeaderNames.CONTENT_ENCODING).get(); if (contentEncodingContext.contentDecodingSupported(contentEncoding)) { decoder = contentEncodingContext.decoder(contentEncoding); } else { throw RequestException.builder() .type(DirectHandler.EventType.OTHER) - .status(Http.Status.UNSUPPORTED_MEDIA_TYPE_415) + .status(Status.UNSUPPORTED_MEDIA_TYPE_415) .message("Unsupported content encoding") .build(); } @@ -414,7 +415,7 @@ private void handle() { routing.route(ctx, request, response); } else { ctx.log(LOGGER, TRACE, "Too many concurrent requests, rejecting request."); - response.status(Http.Status.SERVICE_UNAVAILABLE_503) + response.status(Status.SERVICE_UNAVAILABLE_503) .send("Too Many Concurrent Requests"); response.commit(); } diff --git a/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2Upgrader.java b/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2Upgrader.java index 94d577c21a6..8ec43b0bc5d 100644 --- a/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2Upgrader.java +++ b/webserver/http2/src/main/java/io/helidon/webserver/http2/Http2Upgrader.java @@ -22,8 +22,8 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.buffers.DataWriter; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; import io.helidon.http.HttpPrologue; import io.helidon.http.WritableHeaders; import io.helidon.http.http2.Http2Headers; @@ -42,7 +42,7 @@ public class Http2Upgrader implements Http1Upgrader { + "Connection: Upgrade\r\n" + "Upgrade: h2c\r\n\r\n") .getBytes(StandardCharsets.UTF_8); - private static final HeaderName HTTP2_SETTINGS_HEADER_NAME = Http.HeaderNames.create("HTTP2-Settings"); + private static final HeaderName HTTP2_SETTINGS_HEADER_NAME = HeaderNames.create("HTTP2-Settings"); private static final Base64.Decoder BASE_64_DECODER = Base64.getDecoder(); private final Http2Config config; @@ -85,7 +85,7 @@ public ServerConnection upgrade(ConnectionContext ctx, Http2Headers http2Headers = Http2Headers.create(headers); http2Headers.path(prologue.uriPath().rawPath()); http2Headers.method(prologue.method()); - headers.remove(Http.HeaderNames.HOST, + headers.remove(HeaderNames.HOST, it -> http2Headers.authority(it.value())); http2Headers.scheme("http"); // TODO need to get if https (ctx)? diff --git a/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthFeature.java b/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthFeature.java index 8e211cb7f69..a62a93dc87d 100644 --- a/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthFeature.java +++ b/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthFeature.java @@ -41,8 +41,8 @@ /** * Observe health endpoints. - * This service provides endpoints for {@link io.helidon.http.Http.Method#GET} and - * {@link io.helidon.http.Http.Method#HEAD} methods. + * This service provides endpoints for {@link io.helidon.http.Method#GET} and + * {@link io.helidon.http.Method#HEAD} methods. */ public class HealthFeature extends HelidonFeatureSupport { private static final System.Logger LOGGER = System.getLogger(HealthFeature.class.getName()); @@ -173,10 +173,10 @@ public Builder enabled(boolean enabled) { /** * Whether details should be printed. - * By default, health only returns a {@link io.helidon.http.Http.Status#NO_CONTENT_204} for success, - * {@link io.helidon.http.Http.Status#SERVICE_UNAVAILABLE_503} for health down, - * and {@link io.helidon.http.Http.Status#INTERNAL_SERVER_ERROR_500} in case of error with no entity. - * When details are enabled, health returns {@link io.helidon.http.Http.Status#OK_200} for success, same codes + * By default, health only returns a {@link io.helidon.http.Status#NO_CONTENT_204} for success, + * {@link io.helidon.http.Status#SERVICE_UNAVAILABLE_503} for health down, + * and {@link io.helidon.http.Status#INTERNAL_SERVER_ERROR_500} in case of error with no entity. + * When details are enabled, health returns {@link io.helidon.http.Status#OK_200} for success, same codes * otherwise * and a JSON entity with detailed information about each health check executed. * diff --git a/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthHandler.java b/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthHandler.java index 69f45c058e3..e248de26e85 100644 --- a/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthHandler.java +++ b/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthHandler.java @@ -23,7 +23,7 @@ import io.helidon.health.HealthCheck; import io.helidon.health.HealthCheckResponse; import io.helidon.http.HtmlEncoder; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.http.media.EntityWriter; import io.helidon.http.media.jsonp.JsonpSupport; import io.helidon.webserver.http.Handler; @@ -77,10 +77,10 @@ public void handle(ServerRequest req, ServerResponse res) { } } - Http.Status responseStatus = switch (status) { - case UP -> details ? Http.Status.OK_200 : Http.Status.NO_CONTENT_204; - case DOWN -> Http.Status.SERVICE_UNAVAILABLE_503; - case ERROR -> Http.Status.INTERNAL_SERVER_ERROR_500; + Status responseStatus = switch (status) { + case UP -> details ? Status.OK_200 : Status.NO_CONTENT_204; + case DOWN -> Status.SERVICE_UNAVAILABLE_503; + case ERROR -> Status.INTERNAL_SERVER_ERROR_500; }; res.status(responseStatus); diff --git a/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthObserveProvider.java b/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthObserveProvider.java index 333f001d735..9eea2243c97 100644 --- a/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthObserveProvider.java +++ b/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/HealthObserveProvider.java @@ -17,7 +17,7 @@ package io.helidon.webserver.observe.health; import io.helidon.common.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.observe.spi.ObserveProvider; @@ -84,7 +84,7 @@ public void register(Config config, String componentPath, HttpRouting.Builder ro observer.context(componentPath); routing.addFeature(observer); } else { - routing.get(componentPath + "/*", (req, res) -> res.status(Http.Status.SERVICE_UNAVAILABLE_503) + routing.get(componentPath + "/*", (req, res) -> res.status(Status.SERVICE_UNAVAILABLE_503) .send()); } } diff --git a/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/SingleCheckHandler.java b/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/SingleCheckHandler.java index a8f2949cefa..dc176e1eae3 100644 --- a/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/SingleCheckHandler.java +++ b/webserver/observe/health/src/main/java/io/helidon/webserver/observe/health/SingleCheckHandler.java @@ -25,8 +25,8 @@ import io.helidon.health.HealthCheck; import io.helidon.health.HealthCheckResponse; import io.helidon.http.HtmlEncoder; -import io.helidon.http.Http; import io.helidon.http.NotFoundException; +import io.helidon.http.Status; import io.helidon.http.media.EntityWriter; import io.helidon.http.media.jsonp.JsonpSupport; import io.helidon.webserver.http.Handler; @@ -76,10 +76,10 @@ public void handle(ServerRequest req, ServerResponse res) { LOGGER.log(System.Logger.Level.ERROR, "Unexpected failure of health check", e); } - Http.Status responseStatus = switch (response.status()) { - case UP -> details ? Http.Status.OK_200 : Http.Status.NO_CONTENT_204; - case DOWN -> Http.Status.SERVICE_UNAVAILABLE_503; - case ERROR -> Http.Status.INTERNAL_SERVER_ERROR_500; + Status responseStatus = switch (response.status()) { + case UP -> details ? Status.OK_200 : Status.NO_CONTENT_204; + case DOWN -> Status.SERVICE_UNAVAILABLE_503; + case ERROR -> Status.INTERNAL_SERVER_ERROR_500; }; res.status(responseStatus); @@ -93,7 +93,7 @@ public void handle(ServerRequest req, ServerResponse res) { res.headers()); } catch (IOException e) { LOGGER.log(System.Logger.Level.TRACE, "Failed to write health check response", e); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500) + res.status(Status.INTERNAL_SERVER_ERROR_500) .send(); } } else { diff --git a/webserver/observe/log/src/main/java/io/helidon/webserver/observe/log/LogService.java b/webserver/observe/log/src/main/java/io/helidon/webserver/observe/log/LogService.java index ca1d58ca0a4..84645c6db9f 100644 --- a/webserver/observe/log/src/main/java/io/helidon/webserver/observe/log/LogService.java +++ b/webserver/observe/log/src/main/java/io/helidon/webserver/observe/log/LogService.java @@ -37,9 +37,12 @@ import io.helidon.common.config.Config; import io.helidon.common.media.type.MediaType; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.HttpMediaType; import io.helidon.http.HttpMediaTypes; +import io.helidon.http.Status; import io.helidon.http.media.EntityReader; import io.helidon.http.media.EntityWriter; import io.helidon.http.media.jsonp.JsonpSupport; @@ -68,7 +71,7 @@ class LogService implements HttpService { private final AtomicBoolean logHandlingInitialized = new AtomicBoolean(); private final boolean permitAll; private final boolean logStreamEnabled; - private final Http.Header logStreamMediaTypeHeader; + private final Header logStreamMediaTypeHeader; private final long logStreamSleepSeconds; private final int logStreamQueueSize; private final String logStreamIdleString; @@ -161,7 +164,7 @@ private void initializeLogHandling() { private void unsetLoggerHandler(ServerRequest req, ServerResponse res) { String logger = req.path().pathParameters().first("logger").orElse(""); Logger.getLogger(logger).setLevel(null); - res.status(Http.Status.NO_CONTENT_204).send(); + res.status(Status.NO_CONTENT_204).send(); } private void setLevelHandler(ServerRequest req, ServerResponse res) { @@ -175,7 +178,7 @@ private void setLevelHandler(ServerRequest req, ServerResponse res) { Logger.getLogger(logger) .setLevel(desiredLevel); - res.status(Http.Status.NO_CONTENT_204).send(); + res.status(Status.NO_CONTENT_204).send(); } private void loggerHandler(ServerRequest req, ServerResponse res) { @@ -262,8 +265,8 @@ private void write(ServerRequest req, ServerResponse res, JsonObject json) { static class Builder implements io.helidon.common.Builder { private boolean permitAll = false; private boolean logStreamEnabled = true; - private Http.Header logStreamMediaTypeHeader = Http.Headers.create(Http.HeaderNames.CONTENT_TYPE, - HttpMediaTypes.PLAINTEXT_UTF_8.text()); + private Header logStreamMediaTypeHeader = HeaderValues.create(HeaderNames.CONTENT_TYPE, + HttpMediaTypes.PLAINTEXT_UTF_8.text()); private Charset logStreamCharset = StandardCharsets.UTF_8; private long logStreamSleepSeconds = 5L; private int logStreamQueueSize = 100; @@ -305,7 +308,7 @@ Builder logStreamEnabled(boolean logStreamAllow) { } Builder logStreamMediaType(HttpMediaType logStreamMediaType) { - this.logStreamMediaTypeHeader = Http.Headers.createCached(Http.HeaderNames.CONTENT_TYPE, logStreamMediaType.text()); + this.logStreamMediaTypeHeader = HeaderValues.createCached(HeaderNames.CONTENT_TYPE, logStreamMediaType.text()); this.logStreamCharset = logStreamMediaType.charset().map(Charset::forName).orElse(StandardCharsets.UTF_8); return this; } diff --git a/webserver/observe/metrics/src/main/java/io/helidon/webserver/observe/metrics/MetricsFeature.java b/webserver/observe/metrics/src/main/java/io/helidon/webserver/observe/metrics/MetricsFeature.java index 366badd0c46..b033be7299f 100644 --- a/webserver/observe/metrics/src/main/java/io/helidon/webserver/observe/metrics/MetricsFeature.java +++ b/webserver/observe/metrics/src/main/java/io/helidon/webserver/observe/metrics/MetricsFeature.java @@ -28,8 +28,9 @@ import io.helidon.common.media.type.MediaTypes; import io.helidon.config.Config; import io.helidon.config.metadata.ConfiguredOption; -import io.helidon.http.Http; +import io.helidon.http.HeaderValues; import io.helidon.http.HttpException; +import io.helidon.http.Status; import io.helidon.metrics.api.Meter; import io.helidon.metrics.api.MeterRegistry; import io.helidon.metrics.api.MeterRegistryFormatter; @@ -46,10 +47,10 @@ import io.helidon.webserver.http.ServerResponse; import io.helidon.webserver.servicecommon.HelidonFeatureSupport; -import static io.helidon.http.Http.HeaderNames.ALLOW; -import static io.helidon.http.Http.Status.METHOD_NOT_ALLOWED_405; -import static io.helidon.http.Http.Status.NOT_FOUND_404; -import static io.helidon.http.Http.Status.OK_200; +import static io.helidon.http.HeaderNames.ALLOW; +import static io.helidon.http.Status.METHOD_NOT_ALLOWED_405; +import static io.helidon.http.Status.NOT_FOUND_404; +import static io.helidon.http.Status.OK_200; /** * Support for metrics for Helidon WebServer. @@ -90,7 +91,7 @@ public class MetricsFeature extends HelidonFeatureSupport { private static final String KPI_METER_NAME_PREFIX_WITH_DOT = KPI_METER_NAME_PREFIX + "."; private static final System.Logger LOGGER = System.getLogger(MetricsFeature.class.getName()); - private static final Handler DISABLED_ENDPOINT_HANDLER = (req, res) -> res.status(Http.Status.NOT_FOUND_404) + private static final Handler DISABLED_ENDPOINT_HANDLER = (req, res) -> res.status(Status.NOT_FOUND_404) .send("Metrics are disabled"); private static final Iterable EMPTY_ITERABLE = Collections::emptyIterator; @@ -237,7 +238,7 @@ private MeterRegistryFormatter chooseFormatter(MeterRegistry meterRegistry, return formatter.get(); } throw new HttpException("Unsupported media type for metrics formatting: " + mediaType, - Http.Status.UNSUPPORTED_MEDIA_TYPE_415, + Status.UNSUPPORTED_MEDIA_TYPE_415, true); } @@ -251,9 +252,9 @@ private void getMatching(ServerRequest req, Iterable scopeSelection, Iterable nameSelection) { MediaType mediaType = bestAccepted(req); - res.header(Http.Headers.CACHE_NO_CACHE); + res.header(HeaderValues.CACHE_NO_CACHE); if (mediaType == null) { - res.status(Http.Status.NOT_ACCEPTABLE_406); + res.status(Status.NOT_ACCEPTABLE_406); res.send(); } diff --git a/webserver/observe/metrics/src/main/java/io/helidon/webserver/observe/metrics/MetricsObserveProvider.java b/webserver/observe/metrics/src/main/java/io/helidon/webserver/observe/metrics/MetricsObserveProvider.java index 8f0b3321ddb..bb19530745c 100644 --- a/webserver/observe/metrics/src/main/java/io/helidon/webserver/observe/metrics/MetricsObserveProvider.java +++ b/webserver/observe/metrics/src/main/java/io/helidon/webserver/observe/metrics/MetricsObserveProvider.java @@ -16,7 +16,7 @@ package io.helidon.webserver.observe.metrics; import io.helidon.common.config.Config; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.observe.spi.ObserveProvider; @@ -87,7 +87,7 @@ public void register(Config config, String componentPath, HttpRouting.Builder ro routing.addFeature(observer); } else { String finalPath = componentPath + (componentPath.endsWith("/") ? "*" : "/*"); - routing.get(finalPath, (req, res) -> res.status(Http.Status.SERVICE_UNAVAILABLE_503) + routing.get(finalPath, (req, res) -> res.status(Status.SERVICE_UNAVAILABLE_503) .send()); } } diff --git a/webserver/observe/observe/src/main/java/io/helidon/webserver/observe/ObserveFeature.java b/webserver/observe/observe/src/main/java/io/helidon/webserver/observe/ObserveFeature.java index d390cbf73ca..fa670d71721 100644 --- a/webserver/observe/observe/src/main/java/io/helidon/webserver/observe/ObserveFeature.java +++ b/webserver/observe/observe/src/main/java/io/helidon/webserver/observe/ObserveFeature.java @@ -24,8 +24,8 @@ import io.helidon.common.Weighted; import io.helidon.common.config.Config; import io.helidon.common.config.GlobalConfig; -import io.helidon.http.Http; import io.helidon.http.HttpException; +import io.helidon.http.Status; import io.helidon.webserver.cors.CorsSupport; import io.helidon.webserver.http.HttpFeature; import io.helidon.webserver.http.HttpRouting; @@ -105,7 +105,7 @@ public void setup(HttpRouting.Builder routing) { } } else { routing.get(endpoint, (req, res) -> { - throw new HttpException("Observe endpoint is disabled", Http.Status.SERVICE_UNAVAILABLE_503, true); + throw new HttpException("Observe endpoint is disabled", Status.SERVICE_UNAVAILABLE_503, true); }); } } diff --git a/webserver/security/src/main/java/io/helidon/webserver/security/SecurityFeature.java b/webserver/security/src/main/java/io/helidon/webserver/security/SecurityFeature.java index 36add13be7e..3aa283b9f37 100644 --- a/webserver/security/src/main/java/io/helidon/webserver/security/SecurityFeature.java +++ b/webserver/security/src/main/java/io/helidon/webserver/security/SecurityFeature.java @@ -30,7 +30,7 @@ import io.helidon.config.Config; import io.helidon.config.ConfigValue; import io.helidon.http.ForbiddenException; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.http.PathMatchers; import io.helidon.http.UnauthorizedException; import io.helidon.security.EndpointConfig; @@ -447,11 +447,11 @@ private void registerRouting(HttpRules routing) { if (configuredPaths.isPresent()) { List paths = configuredPaths.get(); for (Config pathConfig : paths) { - List methods = pathConfig.get("methods").asNodeList().orElse(List.of()) + List methods = pathConfig.get("methods").asNodeList().orElse(List.of()) .stream() .map(Config::asString) .map(ConfigValue::get) - .map(Http.Method::create) + .map(Method::create) .collect(Collectors.toList()); String path = pathConfig.get("path") @@ -462,7 +462,7 @@ private void registerRouting(HttpRules routing) { if (methods.isEmpty()) { routing.any(path, SecurityHandler.create(pathConfig, defaults)); } else { - routing.route(Http.Method.predicate(methods), + routing.route(Method.predicate(methods), PathMatchers.create(path), SecurityHandler.create(pathConfig, defaults)); } diff --git a/webserver/security/src/main/java/io/helidon/webserver/security/SecurityHandler.java b/webserver/security/src/main/java/io/helidon/webserver/security/SecurityHandler.java index fe7ad782b0a..73ca889df8f 100644 --- a/webserver/security/src/main/java/io/helidon/webserver/security/SecurityHandler.java +++ b/webserver/security/src/main/java/io/helidon/webserver/security/SecurityHandler.java @@ -35,9 +35,13 @@ import io.helidon.common.context.Contexts; import io.helidon.common.uri.UriQuery; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; import io.helidon.http.RoutedPath; import io.helidon.http.ServerResponseHeaders; +import io.helidon.http.Status; import io.helidon.security.AuditEvent; import io.helidon.security.AuthenticationResponse; import io.helidon.security.AuthorizationResponse; @@ -544,7 +548,7 @@ private void processSecurity(SecurityContext securityContext, ServerRequest req, } catch (Exception e) { tracing.error(e); LOGGER.log(Level.SEVERE, "Unexpected exception during security processing", e); - abortRequest(res, null, Http.Status.INTERNAL_SERVER_ERROR_500.code(), Map.of()); + abortRequest(res, null, Status.INTERNAL_SERVER_ERROR_500.code(), Map.of()); } // auditing @@ -553,7 +557,7 @@ private void processSecurity(SecurityContext securityContext, ServerRequest req, private void processAudit(ServerRequest req, ServerResponse res, SecurityContext securityContext) { - Http.Method method = req.prologue().method(); + Method method = req.prologue().method(); // make sure we actually should audit if (!audited.orElse(true)) { @@ -563,7 +567,7 @@ private void processAudit(ServerRequest req, ServerResponse res, SecurityContext if (audited.isEmpty()) { // use defaults - if (method == Http.Method.GET || method == Http.Method.HEAD) { + if (method == Method.GET || method == Method.HEAD) { // get and head are not audited by default return; } @@ -619,7 +623,7 @@ private AtxResult processAuthentication(ServerResponse res, AuthenticationResponse response = clientBuilder.explicitProvider(explicitAuthenticator.orElse(null)).submit(); // copy headers to be returned with the current response response.responseHeaders() - .forEach((key, value) -> res.headers().set(Http.Headers.create(key, value))); + .forEach((key, value) -> res.headers().set(HeaderValues.create(key, value))); switch (response.status()) { case SUCCESS: @@ -670,8 +674,8 @@ private boolean atnAbstainFailure(ServerResponse res, AuthenticationResponse res abortRequest(res, response, - Http.Status.UNAUTHORIZED_401.code(), - Map.of(Http.HeaderNames.WWW_AUTHENTICATE, + Status.UNAUTHORIZED_401.code(), + Map.of(HeaderNames.WWW_AUTHENTICATE, List.of("Basic realm=\"Security Realm\""))); return true; } @@ -681,7 +685,7 @@ private boolean atnFinishFailure(ServerResponse res, AuthenticationResponse resp LOGGER.finest("Authentication failed, but was optional, so assuming anonymous"); return false; } else { - int defaultStatusCode = Http.Status.UNAUTHORIZED_401.code(); + int defaultStatusCode = Status.UNAUTHORIZED_401.code(); abortRequest(res, response, defaultStatusCode, Map.of()); return true; @@ -689,23 +693,23 @@ private boolean atnFinishFailure(ServerResponse res, AuthenticationResponse resp } private void atnFinish(ServerResponse res, AuthenticationResponse response) { - int defaultStatusCode = Http.Status.OK_200.code(); + int defaultStatusCode = Status.OK_200.code(); abortRequest(res, response, defaultStatusCode, Map.of()); } private void abortRequest(ServerResponse res, SecurityResponse response, int defaultCode, - Map> defaultHeaders) { + Map> defaultHeaders) { int statusCode = ((null == response) ? defaultCode : response.statusCode().orElse(defaultCode)); - Map> responseHeaders; + Map> responseHeaders; if (response == null) { responseHeaders = defaultHeaders; } else { - Map> tmpHeaders = new HashMap<>(); + Map> tmpHeaders = new HashMap<>(); response.responseHeaders() - .forEach((key, value) -> tmpHeaders.put(Http.HeaderNames.create(key), value)); + .forEach((key, value) -> tmpHeaders.put(HeaderNames.create(key), value)); responseHeaders = tmpHeaders; } @@ -713,11 +717,11 @@ private void abortRequest(ServerResponse res, ServerResponseHeaders httpHeaders = res.headers(); - for (Map.Entry> entry : responseHeaders.entrySet()) { + for (Map.Entry> entry : responseHeaders.entrySet()) { httpHeaders.set(entry.getKey(), entry.getValue()); } - res.status(Http.Status.create(statusCode)); + res.status(Status.create(statusCode)); res.send(); } @@ -749,14 +753,14 @@ private AtxResult processAuthorization(ServerRequest req, if (explicitAuthorizer.isPresent()) { if (rolesSet.stream().noneMatch(role -> context.isUserInRole(role, explicitAuthorizer.get()))) { auditRoleMissing(context, req.path(), context.user(), rolesSet); - abortRequest(res, null, Http.Status.FORBIDDEN_403.code(), Map.of()); + abortRequest(res, null, Status.FORBIDDEN_403.code(), Map.of()); atzTracing.finish(); return AtxResult.STOP; } } else { if (rolesSet.stream().noneMatch(context::isUserInRole)) { auditRoleMissing(context, req.path(), context.user(), rolesSet); - abortRequest(res, null, Http.Status.FORBIDDEN_403.code(), Map.of()); + abortRequest(res, null, Status.FORBIDDEN_403.code(), Map.of()); atzTracing.finish(); return AtxResult.STOP; } @@ -780,8 +784,8 @@ private AtxResult processAuthorization(ServerRequest req, case FAILURE_FINISH: case SUCCESS_FINISH: int defaultStatus = (response.status() == AuthenticationResponse.SecurityStatus.FAILURE_FINISH) - ? Http.Status.FORBIDDEN_403.code() - : Http.Status.OK_200.code(); + ? Status.FORBIDDEN_403.code() + : Status.OK_200.code(); atzTracing.finish(); abortRequest(res, response, defaultStatus, Map.of()); @@ -789,7 +793,7 @@ private AtxResult processAuthorization(ServerRequest req, case ABSTAIN: case FAILURE: atzTracing.finish(); - abortRequest(res, response, Http.Status.FORBIDDEN_403.code(), Map.of()); + abortRequest(res, response, Status.FORBIDDEN_403.code(), Map.of()); return AtxResult.STOP; default: throw new SecurityException("Invalid SecurityStatus returned: " + response.status()); diff --git a/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityBuilderGateDefaultsTest.java b/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityBuilderGateDefaultsTest.java index 2ef9571f14f..f7a1ae949c8 100644 --- a/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityBuilderGateDefaultsTest.java +++ b/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityBuilderGateDefaultsTest.java @@ -22,8 +22,9 @@ import io.helidon.common.context.Context; import io.helidon.common.context.Contexts; import io.helidon.config.Config; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; import io.helidon.http.HttpMediaTypes; +import io.helidon.http.Status; import io.helidon.security.AuditEvent; import io.helidon.security.EndpointConfig; import io.helidon.security.Security; @@ -121,7 +122,7 @@ public void testCustomizedAudit() { // as then audit is called twice - first time with 401 (challenge) and second time with 200 (correct request) // and that intermittently breaks this test try (Http1ClientResponse response = webClient.get("/auditOnly").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } // audit @@ -168,19 +169,19 @@ void basicTestJill() { void basicTest401() { try (Http1ClientResponse response = webClient.get("/noRoles").request()) { - if (response.status() != Http.Status.UNAUTHORIZED_401) { + if (response.status() != Status.UNAUTHORIZED_401) { assertThat("Response received: " + response.entity().as(String.class), response.status(), - is(Http.Status.UNAUTHORIZED_401)); + is(Status.UNAUTHORIZED_401)); } - assertThat(response.headers().first(Http.HeaderNames.WWW_AUTHENTICATE), + assertThat(response.headers().first(HeaderNames.WWW_AUTHENTICATE), optionalValue(is("Basic realm=\"mic\""))); } try (HttpClientResponse response = callProtected("/noRoles", "invalidUser", "invalidPassword")) { - assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); - assertThat(response.headers().first(Http.HeaderNames.WWW_AUTHENTICATE), + assertThat(response.status(), is(Status.UNAUTHORIZED_401)); + assertThat(response.headers().first(HeaderNames.WWW_AUTHENTICATE), optionalValue(is("Basic realm=\"mic\""))); } @@ -190,7 +191,7 @@ private void testForbidden(String uri, String username, String password) { try (HttpClientResponse response = callProtected(uri, username, password)) { assertThat(uri + " for user " + username + " should be forbidden", response.status(), - is(Http.Status.FORBIDDEN_403)); + is(Status.FORBIDDEN_403)); } } @@ -202,7 +203,7 @@ private void testProtected(String uri, String entity; try (HttpClientResponse response = callProtected(uri, username, password)) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); entity = response.entity().as(String.class); diff --git a/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityProgrammaticTest.java b/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityProgrammaticTest.java index 9f3a1566ac7..5131489d18e 100644 --- a/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityProgrammaticTest.java +++ b/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityProgrammaticTest.java @@ -21,18 +21,18 @@ import io.helidon.common.context.Context; import io.helidon.common.context.Contexts; -import io.helidon.http.Http; -import io.helidon.http.HttpMediaTypes; import io.helidon.config.Config; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.HttpMediaTypes; +import io.helidon.http.Status; +import io.helidon.security.Security; +import io.helidon.security.SecurityContext; +import io.helidon.security.util.TokenHandler; import io.helidon.webclient.http1.Http1Client; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.context.ContextFeature; -import io.helidon.security.Security; -import io.helidon.security.SecurityContext; -import io.helidon.security.util.TokenHandler; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; /** * Unit test for {@link SecurityFeature}. @@ -75,7 +75,7 @@ public static void setup(WebServerConfig.Builder serverBuilder) { .get("/user[/{*}]", SecurityFeature.rolesAllowed("user")) .get("/admin", SecurityFeature.rolesAllowed("admin")) .get("/deny", SecurityFeature.rolesAllowed("deny"), (req, res) -> { - res.status(Http.Status.INTERNAL_SERVER_ERROR_500); + res.status(Status.INTERNAL_SERVER_ERROR_500); res.send("Should not get here, this role doesn't exist"); }) .get("/auditOnly", SecurityFeature diff --git a/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityTests.java b/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityTests.java index b65868f1523..b0f92a4ff10 100644 --- a/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityTests.java +++ b/webserver/security/src/test/java/io/helidon/webserver/security/WebSecurityTests.java @@ -18,7 +18,8 @@ import java.util.Set; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.security.AuditEvent; import io.helidon.security.Security; import io.helidon.security.providers.httpauth.HttpBasicAuthProvider; @@ -99,23 +100,23 @@ void basicTestJill() { @Test void basicTest401() { try (Http1ClientResponse response = webClient.get("/noRoles").request()) { - assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); + assertThat(response.status(), is(Status.UNAUTHORIZED_401)); String header = response.headers() - .first(Http.HeaderNames.WWW_AUTHENTICATE) + .first(HeaderNames.WWW_AUTHENTICATE) .orElseThrow(() -> new IllegalStateException( - "Header " + Http.HeaderNames.WWW_AUTHENTICATE + " is" + " not present in response!")); + "Header " + HeaderNames.WWW_AUTHENTICATE + " is" + " not present in response!")); assertThat(header.toLowerCase(), is("basic realm=\"mic\"")); } try (HttpClientResponse response = callProtected("/noRoles", "invalidUser", "invalidPassword")) { - assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); + assertThat(response.status(), is(Status.UNAUTHORIZED_401)); String header = response.headers() - .first(Http.HeaderNames.WWW_AUTHENTICATE) + .first(HeaderNames.WWW_AUTHENTICATE) .orElseThrow(() -> new IllegalStateException( - "Header " + Http.HeaderNames.WWW_AUTHENTICATE + " is" + " not present in response!")); + "Header " + HeaderNames.WWW_AUTHENTICATE + " is" + " not present in response!")); assertThat(header.toLowerCase(), is("basic realm=\"mic\"")); } } @@ -123,7 +124,7 @@ void basicTest401() { @Test void testCustomizedAudit() { try (Http1ClientResponse response = webClient.get("/auditOnly").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } // audit @@ -137,7 +138,7 @@ private void testForbidden(String uri, String username, String password) { try (HttpClientResponse response = callProtected(uri, username, password)) { assertThat(uri + " for user " + username + " should be forbidden", response.status(), - is(Http.Status.FORBIDDEN_403)); + is(Status.FORBIDDEN_403)); } } @@ -149,7 +150,7 @@ private void testProtected(String uri, try (HttpClientResponse response = callProtected(uri, username, password)) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); diff --git a/webserver/sse/src/main/java/io/helidon/webserver/sse/SseSink.java b/webserver/sse/src/main/java/io/helidon/webserver/sse/SseSink.java index 85d03327e99..1baffffe929 100644 --- a/webserver/sse/src/main/java/io/helidon/webserver/sse/SseSink.java +++ b/webserver/sse/src/main/java/io/helidon/webserver/sse/SseSink.java @@ -26,13 +26,13 @@ import io.helidon.common.GenericType; import io.helidon.common.media.type.MediaType; import io.helidon.common.media.type.MediaTypes; -import io.helidon.http.Http; import io.helidon.http.HttpMediaType; +import io.helidon.http.Status; import io.helidon.http.sse.SseEvent; import io.helidon.webserver.http.ServerResponse; import io.helidon.webserver.http.spi.Sink; -import static io.helidon.http.Http.Headers.CONTENT_TYPE_EVENT_STREAM; +import static io.helidon.http.HeaderValues.CONTENT_TYPE_EVENT_STREAM; /** * Implementation of an SSE sink. Emits {@link SseEvent}s. @@ -57,7 +57,7 @@ public class SseSink implements Sink { SseSink(ServerResponse serverResponse, BiConsumer eventConsumer, Runnable closeRunnable) { // Verify response has no status or content type HttpMediaType ct = serverResponse.headers().contentType().orElse(null); - if (serverResponse.status().code() != Http.Status.OK_200.code() + if (serverResponse.status().code() != Status.OK_200.code() || ct != null && !CONTENT_TYPE_EVENT_STREAM.values().equals(ct.mediaType().text())) { throw new IllegalStateException("ServerResponse instance cannot be used to create SseResponse"); } diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/ByteRangeRequest.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/ByteRangeRequest.java index 04412ab3690..062891f4f04 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/ByteRangeRequest.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/ByteRangeRequest.java @@ -22,9 +22,10 @@ import java.util.regex.Pattern; import io.helidon.http.BadRequestException; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.HttpException; +import io.helidon.http.Status; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -73,17 +74,17 @@ void setContentRange(ServerResponse response) { // Content-Range: bytes 0-1023/146515 // Content-Length: 1024 long last = (offset + length) - 1; - response.header(Http.Headers.create(HeaderNames.CONTENT_RANGE, true, + response.header(HeaderValues.create(HeaderNames.CONTENT_RANGE, true, false, "bytes " + offset + "-" + last + "/" + fileLength)); response.contentLength(length); - response.status(Http.Status.PARTIAL_CONTENT_206); + response.status(Status.PARTIAL_CONTENT_206); } private static ByteRangeRequest create(ServerRequest req, ServerResponse res, long offset, long last, long fileLength) { if (offset >= fileLength || last < offset) { res.header(HeaderNames.CONTENT_RANGE, "*/" + fileLength); - throw new HttpException("Wrong range", Http.Status.REQUESTED_RANGE_NOT_SATISFIABLE_416, true); + throw new HttpException("Wrong range", Status.REQUESTED_RANGE_NOT_SATISFIABLE_416, true); } long length = (last - offset) + 1; diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandler.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandler.java index 0ae80637d6b..1abda3f83cd 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandler.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandler.java @@ -19,13 +19,13 @@ import java.io.IOException; import io.helidon.common.configurable.LruCache; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; interface CachedHandler { boolean handle(LruCache cache, - Http.Method method, + Method method, ServerRequest request, ServerResponse response, String requestedResource) throws IOException; diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerInMemory.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerInMemory.java index caa285366f8..06ac5ab9d7a 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerInMemory.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerInMemory.java @@ -23,10 +23,13 @@ import io.helidon.common.configurable.LruCache; import io.helidon.common.media.type.MediaType; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; import io.helidon.http.HttpException; +import io.helidon.http.Method; import io.helidon.http.ServerRequestHeaders; import io.helidon.http.ServerResponseHeaders; +import io.helidon.http.Status; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -38,11 +41,11 @@ record CachedHandlerInMemory(MediaType mediaType, BiConsumer setLastModifiedHeader, byte[] bytes, int contentLength, - Http.Header contentLengthHeader) implements CachedHandler { + Header contentLengthHeader) implements CachedHandler { @Override public boolean handle(LruCache cache, - Http.Method method, + Method method, ServerRequest request, ServerResponse response, String requestedResource) { @@ -54,7 +57,7 @@ public boolean handle(LruCache cache, response.headers().contentType(mediaType); - if (method == Http.Method.GET) { + if (method == Method.GET) { send(request, response); } else { response.headers().set(contentLengthHeader()); @@ -67,21 +70,21 @@ public boolean handle(LruCache cache, private void send(ServerRequest request, ServerResponse response) { ServerRequestHeaders headers = request.headers(); - if (headers.contains(Http.HeaderNames.RANGE)) { + if (headers.contains(HeaderNames.RANGE)) { long contentLength = contentLength(); List ranges = ByteRangeRequest.parse(request, response, - headers.get(Http.HeaderNames.RANGE).values(), + headers.get(HeaderNames.RANGE).values(), contentLength); if (ranges.size() == 1) { // single response ByteRangeRequest range = ranges.get(0); if (range.offset() > contentLength()) { - throw new HttpException("Invalid range offset", Http.Status.REQUESTED_RANGE_NOT_SATISFIABLE_416, true); + throw new HttpException("Invalid range offset", Status.REQUESTED_RANGE_NOT_SATISFIABLE_416, true); } if (range.length() > (contentLength() - range.offset())) { - throw new HttpException("Invalid length", Http.Status.REQUESTED_RANGE_NOT_SATISFIABLE_416, true); + throw new HttpException("Invalid length", Status.REQUESTED_RANGE_NOT_SATISFIABLE_416, true); } range.setContentRange(response); diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerJar.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerJar.java index 847a3986388..62612bd01db 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerJar.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerJar.java @@ -25,7 +25,7 @@ import io.helidon.common.configurable.LruCache; import io.helidon.common.media.type.MediaType; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.http.ServerResponseHeaders; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -41,7 +41,7 @@ record CachedHandlerJar(Path path, @Override public boolean handle(LruCache cache, - Http.Method method, + Method method, ServerRequest request, ServerResponse response, String requestedResource) throws IOException { @@ -65,7 +65,7 @@ public boolean handle(LruCache cache, response.headers().contentType(mediaType); - if (method == Http.Method.GET) { + if (method == Method.GET) { FileBasedContentHandler.send(request, response, path); } else { response.headers().contentLength(FileBasedContentHandler.contentLength(path)); diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerPath.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerPath.java index fafbddf3d0b..7caafe27bef 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerPath.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerPath.java @@ -26,7 +26,7 @@ import io.helidon.common.configurable.LruCache; import io.helidon.common.media.type.MediaType; import io.helidon.http.ForbiddenException; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.http.ServerResponseHeaders; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -42,7 +42,7 @@ record CachedHandlerPath(Path path, @Override public boolean handle(LruCache cache, - Http.Method method, + Method method, ServerRequest request, ServerResponse response, String requestedResource) throws IOException { @@ -69,7 +69,7 @@ public boolean handle(LruCache cache, response.headers().contentType(mediaType); - if (method == Http.Method.GET) { + if (method == Method.GET) { FileBasedContentHandler.send(request, response, path); } else { FileBasedContentHandler.processContentLength(path, response.headers()); diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerRedirect.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerRedirect.java index c4c21d274f6..b54d15dd0b5 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerRedirect.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerRedirect.java @@ -20,14 +20,16 @@ import io.helidon.common.configurable.LruCache; import io.helidon.common.uri.UriQuery; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; record CachedHandlerRedirect(String location) implements CachedHandler { @Override public boolean handle(LruCache cache, - Http.Method method, + Method method, ServerRequest request, ServerResponse response, String requestedResource) throws IOException { @@ -40,8 +42,8 @@ public boolean handle(LruCache cache, locationWithQuery = location() + "?" + query.rawValue(); } - response.status(Http.Status.MOVED_PERMANENTLY_301); - response.headers().set(Http.HeaderNames.LOCATION, locationWithQuery); + response.status(Status.MOVED_PERMANENTLY_301); + response.headers().set(HeaderNames.LOCATION, locationWithQuery); response.send(); return true; } diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerUrlStream.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerUrlStream.java index a27ba343497..3dd3c977482 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerUrlStream.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/CachedHandlerUrlStream.java @@ -25,7 +25,7 @@ import io.helidon.common.configurable.LruCache; import io.helidon.common.media.type.MediaType; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -34,7 +34,7 @@ record CachedHandlerUrlStream(MediaType mediaType, URL url) implements CachedHan @Override public boolean handle(LruCache cache, - Http.Method method, + Method method, ServerRequest request, ServerResponse response, String requestedResource) throws IOException { @@ -53,7 +53,7 @@ public boolean handle(LruCache cache, response.headers().contentType(mediaType); - if (method == Http.Method.HEAD) { + if (method == Method.HEAD) { response.send(); return true; } diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/ClassPathContentHandler.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/ClassPathContentHandler.java index 0ce94da0d45..7391b8589ff 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/ClassPathContentHandler.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/ClassPathContentHandler.java @@ -40,8 +40,11 @@ import java.util.jar.JarFile; import io.helidon.common.media.type.MediaType; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.InternalServerException; +import io.helidon.http.Method; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -120,7 +123,7 @@ void releaseCache() { @SuppressWarnings("checkstyle:RegexpSinglelineJava") @Override - boolean doHandle(Http.Method method, String requestedPath, ServerRequest request, ServerResponse response, boolean mapped) + boolean doHandle(Method method, String requestedPath, ServerRequest request, ServerResponse response, boolean mapped) throws IOException, URISyntaxException { String rawPath = request.prologue().uriPath().rawPath(); @@ -243,10 +246,10 @@ private Optional jarHandler(String requestedResource, URL url) { null)); } else { // we can cache this, as this is a jar record - Http.Header lastModifiedHeader = Http.Headers.create(Http.HeaderNames.LAST_MODIFIED, - true, - false, - formatLastModified(lastModified)); + Header lastModifiedHeader = HeaderValues.create(HeaderNames.LAST_MODIFIED, + true, + false, + formatLastModified(lastModified)); return Optional.of(new CachedHandlerJar(extrEntry.tempFile, detectType(extrEntry.entryName), extrEntry.lastModified(), diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/FileBasedContentHandler.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/FileBasedContentHandler.java index 196f646216f..68dc364ffdf 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/FileBasedContentHandler.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/FileBasedContentHandler.java @@ -34,8 +34,8 @@ import io.helidon.common.media.type.MediaType; import io.helidon.common.media.type.MediaTypes; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.ServerRequestHeaders; import io.helidon.http.ServerResponseHeaders; import io.helidon.webserver.http.ServerRequest; @@ -61,7 +61,7 @@ static String fileName(Path path) { } static void processContentLength(Path path, ServerResponseHeaders headers) { - headers.set(Http.Headers.create(HeaderNames.CONTENT_LENGTH, contentLength(path))); + headers.set(HeaderValues.create(HeaderNames.CONTENT_LENGTH, contentLength(path))); } static long contentLength(Path path) { @@ -78,7 +78,7 @@ static void send(ServerRequest request, ServerResponse response, Path path) thro long contentLength = contentLength(path); List ranges = ByteRangeRequest.parse(request, response, - headers.get(Http.HeaderNames.RANGE).values(), + headers.get(HeaderNames.RANGE).values(), contentLength); if (ranges.size() == 1) { // single response diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/FileSystemContentHandler.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/FileSystemContentHandler.java index aec4bf5a605..0fa1f5102ac 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/FileSystemContentHandler.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/FileSystemContentHandler.java @@ -25,7 +25,7 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.http.ServerResponseHeaders; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -67,7 +67,7 @@ void releaseCache() { } @Override - boolean doHandle(Http.Method method, String requestedPath, ServerRequest req, ServerResponse res, boolean mapped) + boolean doHandle(Method method, String requestedPath, ServerRequest req, ServerResponse res, boolean mapped) throws IOException { Path path = requestedPath(requestedPath); if (LOGGER.isLoggable(Level.DEBUG)) { @@ -99,7 +99,7 @@ boolean doHandle(Http.Method method, String requestedPath, ServerRequest req, Se return doHandle(method, requestedResource, req, res, rawPath, path); } - boolean doHandle(Http.Method method, + boolean doHandle(Method method, String requestedResource, ServerRequest req, ServerResponse res, diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/SingleFileContentHandler.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/SingleFileContentHandler.java index 9290dbd7004..b737bfdf670 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/SingleFileContentHandler.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/SingleFileContentHandler.java @@ -21,7 +21,7 @@ import java.nio.file.Path; import java.util.Optional; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.http.ServerResponseHeaders; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -57,7 +57,7 @@ public void beforeStart() { } @Override - boolean doHandle(Http.Method method, String requestedPath, ServerRequest req, ServerResponse res, boolean mapped) + boolean doHandle(Method method, String requestedPath, ServerRequest req, ServerResponse res, boolean mapped) throws IOException { if ("".equals(requestedPath) || "/".equals(requestedPath)) { Optional cachedHandler = cacheHandler("."); @@ -73,7 +73,7 @@ boolean doHandle(Http.Method method, String requestedPath, ServerRequest req, Se return false; } - private boolean doHandle(Http.Method method, ServerRequest req, ServerResponse res) throws IOException { + private boolean doHandle(Method method, ServerRequest req, ServerResponse res) throws IOException { return cacheFileHandler().handle(handlerCache(), method, req, res, "."); } diff --git a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/StaticContentHandler.java b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/StaticContentHandler.java index dfc9fef4fa5..7af5bca674c 100644 --- a/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/StaticContentHandler.java +++ b/webserver/static-content/src/main/java/io/helidon/webserver/staticcontent/StaticContentHandler.java @@ -33,14 +33,18 @@ import io.helidon.common.configurable.LruCache; import io.helidon.common.media.type.MediaType; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.DateTime; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.HttpException; import io.helidon.http.InternalServerException; +import io.helidon.http.Method; import io.helidon.http.NotFoundException; import io.helidon.http.PathMatchers; import io.helidon.http.ServerRequestHeaders; import io.helidon.http.ServerResponseHeaders; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -80,18 +84,18 @@ static void processEtag(String etag, ServerRequestHeaders requestHeaders, Server // Put ETag into the response responseHeaders.set(HeaderNames.ETAG, '"' + etag + '"'); // Process If-None-Match header - if (requestHeaders.contains(Http.HeaderNames.IF_NONE_MATCH)) { + if (requestHeaders.contains(HeaderNames.IF_NONE_MATCH)) { List ifNoneMatches = requestHeaders.get(HeaderNames.IF_NONE_MATCH).allValues(); for (String ifNoneMatch : ifNoneMatches) { ifNoneMatch = unquoteETag(ifNoneMatch); if ("*".equals(ifNoneMatch) || ifNoneMatch.equals(etag)) { // using exception to handle normal flow (same as in reactive static content) - throw new HttpException("Accepted by If-None-Match header", Http.Status.NOT_MODIFIED_304, true); + throw new HttpException("Accepted by If-None-Match header", Status.NOT_MODIFIED_304, true); } } } - if (requestHeaders.contains(Http.HeaderNames.IF_MATCH)) { + if (requestHeaders.contains(HeaderNames.IF_MATCH)) { // Process If-Match header List ifMatches = requestHeaders.get(HeaderNames.IF_MATCH).allValues(); if (!ifMatches.isEmpty()) { @@ -104,7 +108,7 @@ static void processEtag(String etag, ServerRequestHeaders requestHeaders, Server } } if (!ifMatchChecked) { - throw new HttpException("Not accepted by If-Match header", Http.Status.PRECONDITION_FAILED_412, true); + throw new HttpException("Not accepted by If-Match header", Status.PRECONDITION_FAILED_412, true); } } } @@ -125,14 +129,14 @@ static void processModifyHeaders(Instant modified, .ifModifiedSince() .map(ChronoZonedDateTime::toInstant); if (ifModSince.isPresent() && !ifModSince.get().isBefore(modified)) { - throw new HttpException("Not valid for If-Modified-Since header", Http.Status.NOT_MODIFIED_304, true); + throw new HttpException("Not valid for If-Modified-Since header", Status.NOT_MODIFIED_304, true); } // If-Unmodified-Since Optional ifUnmodSince = requestHeaders .ifUnmodifiedSince() .map(ChronoZonedDateTime::toInstant); if (ifUnmodSince.isPresent() && ifUnmodSince.get().isBefore(modified)) { - throw new HttpException("Not valid for If-Unmodified-Since header", Http.Status.PRECONDITION_FAILED_412, true); + throw new HttpException("Not valid for If-Unmodified-Since header", Status.PRECONDITION_FAILED_412, true); } } @@ -180,7 +184,7 @@ public void afterStop() { @Override public void routing(HttpRules rules) { - rules.route(Http.Method.predicate(Http.Method.GET, Http.Method.HEAD), + rules.route(Method.predicate(Method.GET, Method.HEAD), PathMatchers.any(), this::handle); } @@ -200,7 +204,7 @@ void releaseCache() { * @param response an HTTP response */ void handle(ServerRequest request, ServerResponse response) { - Http.Method method = request.prologue().method(); + Method method = request.prologue().method(); // Resolve path String requestPath = request.path().rawPathNoParams(); @@ -217,7 +221,7 @@ void handle(ServerRequest request, ServerResponse response) { response.next(); } } catch (HttpException httpException) { - if (httpException.status().code() == Http.Status.NOT_FOUND_404.code()) { + if (httpException.status().code() == Status.NOT_FOUND_404.code()) { // Prefer to next() before NOT_FOUND response.next(); } else { @@ -241,7 +245,7 @@ void handle(ServerRequest request, ServerResponse response) { * @throws java.io.IOException if resource is not acceptable * @throws io.helidon.http.RequestException if some known WEB error */ - abstract boolean doHandle(Http.Method method, + abstract boolean doHandle(Method method, String requestedPath, ServerRequest request, ServerResponse response, @@ -312,7 +316,7 @@ private static String unquoteETag(String etag) { void cacheInMemory(String resource, MediaType contentType, byte[] bytes, Optional lastModified) { int contentLength = bytes.length; - Http.Header contentLengthHeader = Http.Headers.create(HeaderNames.CONTENT_LENGTH, contentLength); + Header contentLengthHeader = HeaderValues.create(HeaderNames.CONTENT_LENGTH, contentLength); CachedHandlerInMemory inMemoryResource; if (lastModified.isEmpty()) { @@ -324,10 +328,10 @@ void cacheInMemory(String resource, MediaType contentType, byte[] bytes, Optiona contentLengthHeader); } else { // we can cache this, as this is a jar record - Http.Header lastModifiedHeader = Http.Headers.create(HeaderNames.LAST_MODIFIED, - true, - false, - formatLastModified(lastModified.get())); + Header lastModifiedHeader = HeaderValues.create(HeaderNames.LAST_MODIFIED, + true, + false, + formatLastModified(lastModified.get())); inMemoryResource = new CachedHandlerInMemory(contentType, lastModified.get(), @@ -342,6 +346,6 @@ void cacheInMemory(String resource, MediaType contentType, byte[] bytes, Optiona static String formatLastModified(Instant lastModified) { ZonedDateTime dt = ZonedDateTime.ofInstant(lastModified, ZoneId.systemDefault()); - return dt.format(Http.DateTime.RFC_1123_DATE_TIME); + return dt.format(DateTime.RFC_1123_DATE_TIME); } } diff --git a/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/ByteRangeRequestTest.java b/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/ByteRangeRequestTest.java index c0b6a2d7404..d05edb02205 100644 --- a/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/ByteRangeRequestTest.java +++ b/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/ByteRangeRequestTest.java @@ -18,9 +18,9 @@ import java.util.List; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -34,7 +34,7 @@ class ByteRangeRequestTest { @Test void testFromUntilEnd() { - Http.Header header = Http.Headers.create(HeaderNames.RANGE, "bytes=49-"); + Header header = HeaderValues.create(HeaderNames.RANGE, "bytes=49-"); ServerRequest req = Mockito.mock(ServerRequest.class); ServerResponse res = Mockito.mock(ServerResponse.class); @@ -49,7 +49,7 @@ void testFromUntilEnd() { @Test void testFromUntil() { - Http.Header header = Http.Headers.create(Http.HeaderNames.RANGE, "bytes=49-49"); + Header header = HeaderValues.create(HeaderNames.RANGE, "bytes=49-49"); ServerRequest req = Mockito.mock(ServerRequest.class); ServerResponse res = Mockito.mock(ServerResponse.class); @@ -64,7 +64,7 @@ void testFromUntil() { @Test void testLast() { - Header header = Http.Headers.create(Http.HeaderNames.RANGE, "bytes=-1"); + Header header = HeaderValues.create(HeaderNames.RANGE, "bytes=-1"); ServerRequest req = Mockito.mock(ServerRequest.class); ServerResponse res = Mockito.mock(ServerResponse.class); @@ -79,7 +79,7 @@ void testLast() { @Test void testMultiRangeMultiValue() { - Header header = Http.Headers.create(Http.HeaderNames.RANGE, "bytes=-1", "bytes=47-48", "bytes=0-"); + Header header = HeaderValues.create(HeaderNames.RANGE, "bytes=-1", "bytes=47-48", "bytes=0-"); ServerRequest req = Mockito.mock(ServerRequest.class); ServerResponse res = Mockito.mock(ServerResponse.class); @@ -104,7 +104,7 @@ void testMultiRangeMultiValue() { @Test void testMultiRangeSingleValue() { - Http.Header header = Http.Headers.create(Http.HeaderNames.RANGE, "bytes=-1, bytes=47-48, s bytes=0-"); + Header header = HeaderValues.create(HeaderNames.RANGE, "bytes=-1, bytes=47-48, s bytes=0-"); ServerRequest req = Mockito.mock(ServerRequest.class); ServerResponse res = Mockito.mock(ServerResponse.class); diff --git a/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/CachedHandlerTest.java b/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/CachedHandlerTest.java index 0bf7c1bef7b..a8b48feb129 100644 --- a/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/CachedHandlerTest.java +++ b/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/CachedHandlerTest.java @@ -23,13 +23,16 @@ import java.util.Optional; import io.helidon.common.buffers.BufferData; -import io.helidon.http.Http; -import io.helidon.http.HttpPrologue; -import io.helidon.http.ServerRequestHeaders; -import io.helidon.http.ServerResponseHeaders; import io.helidon.common.media.type.MediaType; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.uri.UriQuery; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.HttpPrologue; +import io.helidon.http.Method; +import io.helidon.http.ServerRequestHeaders; +import io.helidon.http.ServerResponseHeaders; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; @@ -48,8 +51,8 @@ class CachedHandlerTest { private static final MediaType MEDIA_TYPE_ICON = MediaTypes.create("image/x-icon"); - private static final Http.Header ICON_TYPE = Http.Headers.create(Http.HeaderNames.CONTENT_TYPE, MEDIA_TYPE_ICON.text()); - private static final Http.Header RESOURCE_CONTENT_LENGTH = Http.Headers.create(Http.HeaderNames.CONTENT_LENGTH, 7); + private static final Header ICON_TYPE = HeaderValues.create(HeaderNames.CONTENT_TYPE, MEDIA_TYPE_ICON.text()); + private static final Header RESOURCE_CONTENT_LENGTH = HeaderValues.create(HeaderNames.CONTENT_LENGTH, 7); private static ClassPathContentHandler classpathHandler; private static FileSystemContentHandler fsHandler; @@ -90,19 +93,19 @@ void testClasspathFromInMemory() throws IOException, URISyntaxException { when(req.prologue()).thenReturn(HttpPrologue.create("http/1.1", "http", "1.1", - Http.Method.GET, + Method.GET, "/favicon.ico", false)); ServerResponse res = mock(ServerResponse.class); when(res.headers()).thenReturn(responseHeaders); - boolean result = classpathHandler.doHandle(Http.Method.GET, "favicon.ico", req, res, false); + boolean result = classpathHandler.doHandle(Method.GET, "favicon.ico", req, res, false); assertThat("Handler should have found favicon.ico", result, is(true)); assertThat(responseHeaders, hasHeader(ICON_TYPE)); - assertThat(responseHeaders, hasHeader(Http.HeaderNames.ETAG)); - assertThat(responseHeaders, hasHeader(Http.HeaderNames.LAST_MODIFIED)); + assertThat(responseHeaders, hasHeader(HeaderNames.ETAG)); + assertThat(responseHeaders, hasHeader(HeaderNames.LAST_MODIFIED)); } @Test @@ -111,19 +114,19 @@ void testClasspathCacheFound() throws IOException, URISyntaxException { ServerRequest req = mock(ServerRequest.class); when(req.headers()).thenReturn(ServerRequestHeaders.create()); - when(req.prologue()).thenReturn(HttpPrologue.create("http/1.1", "http", "1.1", Http.Method.GET, "/resource.txt", false)); + when(req.prologue()).thenReturn(HttpPrologue.create("http/1.1", "http", "1.1", Method.GET, "/resource.txt", false)); ServerResponse res = mock(ServerResponse.class); when(res.headers()).thenReturn(responseHeaders); when(res.outputStream()).thenReturn(new ByteArrayOutputStream()); - boolean result = classpathHandler.doHandle(Http.Method.GET, "resource.txt", req, res, false); + boolean result = classpathHandler.doHandle(Method.GET, "resource.txt", req, res, false); assertThat("Handler should have found resource.txt", result, is(true)); - assertThat(responseHeaders, hasHeader(Http.Headers.CONTENT_TYPE_TEXT_PLAIN)); + assertThat(responseHeaders, hasHeader(HeaderValues.CONTENT_TYPE_TEXT_PLAIN)); assertThat(responseHeaders, hasHeader(RESOURCE_CONTENT_LENGTH)); - assertThat(responseHeaders, hasHeader(Http.HeaderNames.ETAG)); - assertThat(responseHeaders, hasHeader(Http.HeaderNames.LAST_MODIFIED)); + assertThat(responseHeaders, hasHeader(HeaderNames.ETAG)); + assertThat(responseHeaders, hasHeader(HeaderNames.LAST_MODIFIED)); // now make sure it is cached Optional cachedHandler = classpathHandler.cacheHandler("web/resource.txt"); @@ -143,17 +146,17 @@ void testClasspathCacheRedirectFound() throws IOException, URISyntaxException { ServerRequest req = mock(ServerRequest.class); when(req.headers()).thenReturn(ServerRequestHeaders.create()); - when(req.prologue()).thenReturn(HttpPrologue.create("http/1.1", "http", "1.1", Http.Method.GET, "/nested", false)); + when(req.prologue()).thenReturn(HttpPrologue.create("http/1.1", "http", "1.1", Method.GET, "/nested", false)); when(req.query()).thenReturn(UriQuery.empty()); ServerResponse res = mock(ServerResponse.class); when(res.headers()).thenReturn(responseHeaders); when(res.outputStream()).thenReturn(new ByteArrayOutputStream()); - boolean result = classpathHandler.doHandle(Http.Method.GET, "/nested", req, res, false); + boolean result = classpathHandler.doHandle(Method.GET, "/nested", req, res, false); assertThat("Handler should have redirected", result, is(true)); - assertThat(responseHeaders, hasHeader(Http.HeaderNames.LOCATION, "/nested/")); + assertThat(responseHeaders, hasHeader(HeaderNames.LOCATION, "/nested/")); // now make sure it is cached Optional cachedHandler = classpathHandler.cacheHandler("web/nested"); @@ -186,19 +189,19 @@ void testFsFromInMemory() throws IOException { when(req.prologue()).thenReturn(HttpPrologue.create("http/1.1", "http", "1.1", - Http.Method.GET, + Method.GET, "nested/resource.txt", false)); ServerResponse res = mock(ServerResponse.class); when(res.headers()).thenReturn(responseHeaders); - boolean result = fsHandler.doHandle(Http.Method.GET, "nested/resource.txt", req, res, false); + boolean result = fsHandler.doHandle(Method.GET, "nested/resource.txt", req, res, false); assertThat("Handler should have found nested/resource.txt", result, is(true)); - assertThat(responseHeaders, hasHeader(Http.Headers.CONTENT_TYPE_TEXT_PLAIN)); - assertThat(responseHeaders, hasHeader(Http.HeaderNames.ETAG)); - assertThat(responseHeaders, hasHeader(Http.HeaderNames.LAST_MODIFIED)); + assertThat(responseHeaders, hasHeader(HeaderValues.CONTENT_TYPE_TEXT_PLAIN)); + assertThat(responseHeaders, hasHeader(HeaderNames.ETAG)); + assertThat(responseHeaders, hasHeader(HeaderNames.LAST_MODIFIED)); } @Test @@ -207,19 +210,19 @@ void testFsCacheFound() throws IOException { ServerRequest req = mock(ServerRequest.class); when(req.headers()).thenReturn(ServerRequestHeaders.create()); - when(req.prologue()).thenReturn(HttpPrologue.create("http/1.1", "http", "1.1", Http.Method.GET, "/resource.txt", false)); + when(req.prologue()).thenReturn(HttpPrologue.create("http/1.1", "http", "1.1", Method.GET, "/resource.txt", false)); ServerResponse res = mock(ServerResponse.class); when(res.headers()).thenReturn(responseHeaders); when(res.outputStream()).thenReturn(new ByteArrayOutputStream()); - boolean result = fsHandler.doHandle(Http.Method.GET, "resource.txt", req, res, false); + boolean result = fsHandler.doHandle(Method.GET, "resource.txt", req, res, false); assertThat("Handler should have found resource.txt", result, is(true)); - assertThat(responseHeaders, hasHeader(Http.Headers.CONTENT_TYPE_TEXT_PLAIN)); + assertThat(responseHeaders, hasHeader(HeaderValues.CONTENT_TYPE_TEXT_PLAIN)); assertThat(responseHeaders, hasHeader(RESOURCE_CONTENT_LENGTH)); - assertThat(responseHeaders, hasHeader(Http.HeaderNames.ETAG)); - assertThat(responseHeaders, hasHeader(Http.HeaderNames.LAST_MODIFIED)); + assertThat(responseHeaders, hasHeader(HeaderNames.ETAG)); + assertThat(responseHeaders, hasHeader(HeaderNames.LAST_MODIFIED)); // now make sure it is cached Optional cachedHandler = fsHandler.cacheHandler("resource.txt"); @@ -239,17 +242,17 @@ void testFsCacheRedirectFound() throws IOException { ServerRequest req = mock(ServerRequest.class); when(req.headers()).thenReturn(ServerRequestHeaders.create()); - when(req.prologue()).thenReturn(HttpPrologue.create("http/1.1", "http", "1.1", Http.Method.GET, "/nested", false)); + when(req.prologue()).thenReturn(HttpPrologue.create("http/1.1", "http", "1.1", Method.GET, "/nested", false)); when(req.query()).thenReturn(UriQuery.empty()); ServerResponse res = mock(ServerResponse.class); when(res.headers()).thenReturn(responseHeaders); when(res.outputStream()).thenReturn(new ByteArrayOutputStream()); - boolean result = fsHandler.doHandle(Http.Method.GET, "nested", req, res, false); + boolean result = fsHandler.doHandle(Method.GET, "nested", req, res, false); assertThat("Handler should have redirected", result, is(true)); - assertThat(responseHeaders, hasHeader(Http.HeaderNames.LOCATION, "/nested/")); + assertThat(responseHeaders, hasHeader(HeaderNames.LOCATION, "/nested/")); // now make sure it is cached Optional cachedHandler = fsHandler.cacheHandler("nested"); diff --git a/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/StaticContentHandlerTest.java b/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/StaticContentHandlerTest.java index 7db1afe6105..3f3368064bc 100644 --- a/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/StaticContentHandlerTest.java +++ b/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/StaticContentHandlerTest.java @@ -29,22 +29,24 @@ import io.helidon.common.uri.UriFragment; import io.helidon.common.uri.UriPath; import io.helidon.common.uri.UriQuery; -import io.helidon.http.Http; +import io.helidon.http.HeaderValues; import io.helidon.http.HttpException; import io.helidon.http.HttpPrologue; +import io.helidon.http.Method; import io.helidon.http.RoutedPath; import io.helidon.http.ServerRequestHeaders; import io.helidon.http.ServerResponseHeaders; +import io.helidon.http.Status; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static io.helidon.http.Http.HeaderNames.ETAG; -import static io.helidon.http.Http.HeaderNames.IF_MATCH; -import static io.helidon.http.Http.HeaderNames.IF_NONE_MATCH; -import static io.helidon.http.Http.HeaderNames.LOCATION; +import static io.helidon.http.HeaderNames.ETAG; +import static io.helidon.http.HeaderNames.IF_MATCH; +import static io.helidon.http.HeaderNames.IF_NONE_MATCH; +import static io.helidon.http.HeaderNames.LOCATION; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; @@ -63,7 +65,7 @@ void etag_InNoneMatch_NotAccept() { ServerRequestHeaders req = mock(ServerRequestHeaders.class); when(req.contains(IF_NONE_MATCH)).thenReturn(true); when(req.contains(IF_MATCH)).thenReturn(false); - when(req.get(IF_NONE_MATCH)).thenReturn(Http.Headers.create(IF_NONE_MATCH, "\"ccc\"", "\"ddd\"")); + when(req.get(IF_NONE_MATCH)).thenReturn(HeaderValues.create(IF_NONE_MATCH, "\"ccc\"", "\"ddd\"")); ServerResponseHeaders res = mock(ServerResponseHeaders.class); StaticContentHandler.processEtag("aaa", req, res); verify(res).set(ETAG, ETAG_VALUE); @@ -74,9 +76,9 @@ void etag_InNoneMatch_Accept() { ServerRequestHeaders req = mock(ServerRequestHeaders.class); when(req.contains(IF_NONE_MATCH)).thenReturn(true); when(req.contains(IF_MATCH)).thenReturn(false); - when(req.get(IF_NONE_MATCH)).thenReturn(Http.Headers.create(IF_NONE_MATCH, "\"ccc\"", "W/\"aaa\"")); + when(req.get(IF_NONE_MATCH)).thenReturn(HeaderValues.create(IF_NONE_MATCH, "\"ccc\"", "W/\"aaa\"")); ServerResponseHeaders res = mock(ServerResponseHeaders.class); - assertHttpException(() -> StaticContentHandler.processEtag("aaa", req, res), Http.Status.NOT_MODIFIED_304); + assertHttpException(() -> StaticContentHandler.processEtag("aaa", req, res), Status.NOT_MODIFIED_304); verify(res).set(ETAG, ETAG_VALUE); } @@ -85,9 +87,9 @@ void etag_InMatch_NotAccept() { ServerRequestHeaders req = mock(ServerRequestHeaders.class); when(req.contains(IF_NONE_MATCH)).thenReturn(false); when(req.contains(IF_MATCH)).thenReturn(true); - when(req.get(IF_MATCH)).thenReturn(Http.Headers.create(IF_MATCH, "\"ccc\"", "\"ddd\"")); + when(req.get(IF_MATCH)).thenReturn(HeaderValues.create(IF_MATCH, "\"ccc\"", "\"ddd\"")); ServerResponseHeaders res = mock(ServerResponseHeaders.class); - assertHttpException(() -> StaticContentHandler.processEtag("aaa", req, res), Http.Status.PRECONDITION_FAILED_412); + assertHttpException(() -> StaticContentHandler.processEtag("aaa", req, res), Status.PRECONDITION_FAILED_412); verify(res).set(ETAG, ETAG_VALUE); } @@ -96,7 +98,7 @@ void etag_InMatch_Accept() { ServerRequestHeaders req = mock(ServerRequestHeaders.class); when(req.contains(IF_NONE_MATCH)).thenReturn(false); when(req.contains(IF_MATCH)).thenReturn(true); - when(req.get(IF_MATCH)).thenReturn(Http.Headers.create(IF_MATCH, "\"ccc\"", "\"aaa\"")); + when(req.get(IF_MATCH)).thenReturn(HeaderValues.create(IF_MATCH, "\"ccc\"", "\"aaa\"")); ServerResponseHeaders res = mock(ServerResponseHeaders.class); StaticContentHandler.processEtag("aaa", req, res); verify(res).set(ETAG, ETAG_VALUE); @@ -120,7 +122,7 @@ void ifModifySince_NotAccept() { Mockito.doReturn(Optional.empty()).when(req).ifUnmodifiedSince(); ServerResponseHeaders res = mock(ServerResponseHeaders.class); assertHttpException(() -> StaticContentHandler.processModifyHeaders(modified.toInstant(), req, res), - Http.Status.NOT_MODIFIED_304); + Status.NOT_MODIFIED_304); } @Test @@ -141,7 +143,7 @@ void ifUnmodifySince_NotAccept() { Mockito.doReturn(Optional.empty()).when(req).ifModifiedSince(); ServerResponseHeaders res = mock(ServerResponseHeaders.class); assertHttpException(() -> StaticContentHandler.processModifyHeaders(modified.toInstant(), req, res), - Http.Status.PRECONDITION_FAILED_412); + Status.PRECONDITION_FAILED_412); } @Test @@ -153,15 +155,15 @@ void redirect() throws IOException { when(req.query()).thenReturn(UriQuery.empty()); CachedHandlerRedirect redirectHandler = new CachedHandlerRedirect("/foo/"); - redirectHandler.handle(LruCache.create(), Http.Method.GET, req, res, "/foo"); - verify(res).status(Http.Status.MOVED_PERMANENTLY_301); + redirectHandler.handle(LruCache.create(), Method.GET, req, res, "/foo"); + verify(res).status(Status.MOVED_PERMANENTLY_301); verify(resh).set(LOCATION, "/foo/"); verify(res).send(); } @Test void handleRoot() { - ServerRequest request = mockRequestWithPath(Http.Method.GET, "/"); + ServerRequest request = mockRequestWithPath(Method.GET, "/"); ServerResponse response = mock(ServerResponse.class); TestContentHandler handler = TestContentHandler.create(true); handler.handle(request, response); @@ -171,7 +173,7 @@ void handleRoot() { @Test void handleValid() { - ServerRequest request = mockRequestWithPath(Http.Method.GET, "/foo/some.txt"); + ServerRequest request = mockRequestWithPath(Method.GET, "/foo/some.txt"); ServerResponse response = mock(ServerResponse.class); TestContentHandler handler = TestContentHandler.create(true); handler.handle(request, response); @@ -182,7 +184,7 @@ void handleValid() { @Test void handleOutside() { - ServerRequest request = mockRequestWithPath(Http.Method.GET, "/../foo/some.txt"); + ServerRequest request = mockRequestWithPath(Method.GET, "/../foo/some.txt"); ServerResponse response = mock(ServerResponse.class); TestContentHandler handler = TestContentHandler.create(true); handler.handle(request, response); @@ -192,7 +194,7 @@ void handleOutside() { @Test void handleNextOnFalse() { - ServerRequest request = mockRequestWithPath(Http.Method.GET, "/"); + ServerRequest request = mockRequestWithPath(Method.GET, "/"); ServerResponse response = mock(ServerResponse.class); TestContentHandler handler = TestContentHandler.create(false); handler.handle(request, response); @@ -202,7 +204,7 @@ void handleNextOnFalse() { @Test void classpathHandleSpaces() { - ServerRequest request = mockRequestWithPath(Http.Method.GET, "foo/I have spaces.txt"); + ServerRequest request = mockRequestWithPath(Method.GET, "foo/I have spaces.txt"); ServerResponse response = mock(ServerResponse.class); TestClassPathContentHandler handler = TestClassPathContentHandler.create(); handler.handle(request, response); @@ -210,7 +212,7 @@ void classpathHandleSpaces() { assertThat(handler.counter.get(), is(1)); } - private static void assertHttpException(Runnable runnable, Http.Status status) { + private static void assertHttpException(Runnable runnable, Status status) { try { runnable.run(); throw new AssertionError("Expected HttpException was not thrown!"); @@ -222,7 +224,7 @@ private static void assertHttpException(Runnable runnable, Http.Status status) { } } - private ServerRequest mockRequestWithPath(Http.Method method, String path) { + private ServerRequest mockRequestWithPath(Method method, String path) { UriPath uriPath = UriPath.create(path); HttpPrologue prologue = HttpPrologue.create("HTTP/1.1", "HTTP", @@ -287,7 +289,7 @@ static TestContentHandler create(boolean returnValue) { } @Override - boolean doHandle(Http.Method method, + boolean doHandle(Method method, String requestedResource, ServerRequest req, ServerResponse res, @@ -315,7 +317,7 @@ static TestClassPathContentHandler create() { } @Override - boolean doHandle(Http.Method method, String path, ServerRequest request, ServerResponse response, boolean mapped) + boolean doHandle(Method method, String path, ServerRequest request, ServerResponse response, boolean mapped) throws IOException, URISyntaxException { super.doHandle(method, path, request, response, mapped); this.counter.incrementAndGet(); diff --git a/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/StaticContentTest.java b/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/StaticContentTest.java index dfd4bcd7e0e..59ea7b2084d 100644 --- a/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/StaticContentTest.java +++ b/webserver/static-content/src/test/java/io/helidon/webserver/staticcontent/StaticContentTest.java @@ -19,14 +19,14 @@ import java.nio.file.Files; import java.nio.file.Path; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; import io.helidon.common.testing.http.junit5.HttpHeaderMatcher; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; +import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.testing.junit5.DirectClient; import io.helidon.webserver.testing.junit5.RoutingTest; import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webclient.http1.Http1ClientResponse; -import io.helidon.webserver.http.HttpRouting; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -68,7 +68,7 @@ void testClasspathFavicon() { try (Http1ClientResponse response = testClient.get("/classpath/favicon.ico") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "image/x-icon")); } } @@ -78,7 +78,7 @@ void testClasspathNested() { try (Http1ClientResponse response = testClient.get("/classpath/nested/resource.txt") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "text/plain")); assertThat(response.as(String.class), is("Nested content")); } @@ -89,7 +89,7 @@ void testClasspathSingleFile() { try (Http1ClientResponse response = testClient.get("/singleclasspath") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "text/plain")); assertThat(response.as(String.class), is("Content")); } @@ -100,7 +100,7 @@ void testFileSystemFavicon() { try (Http1ClientResponse response = testClient.get("/path/favicon.ico") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "image/x-icon")); } } @@ -110,7 +110,7 @@ void testFileSystemNested() { try (Http1ClientResponse response = testClient.get("/path/nested/resource.txt") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "text/plain")); assertThat(response.as(String.class), is("Nested content")); } @@ -121,7 +121,7 @@ void testFileSystemSingleFile() { try (Http1ClientResponse response = testClient.get("/singlepath") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "text/plain")); assertThat(response.as(String.class), is("Content")); } diff --git a/webserver/testing/junit5/http2/src/test/java/io/helidon/webserver/testing/junit5/http2/Http2AbstractTestingTest.java b/webserver/testing/junit5/http2/src/test/java/io/helidon/webserver/testing/junit5/http2/Http2AbstractTestingTest.java index 82979764670..a83dd98c11a 100644 --- a/webserver/testing/junit5/http2/src/test/java/io/helidon/webserver/testing/junit5/http2/Http2AbstractTestingTest.java +++ b/webserver/testing/junit5/http2/src/test/java/io/helidon/webserver/testing/junit5/http2/Http2AbstractTestingTest.java @@ -16,13 +16,14 @@ package io.helidon.webserver.testing.junit5.http2; -import io.helidon.http.Http; +import io.helidon.http.Method; +import io.helidon.http.Status; +import io.helidon.webclient.api.ClientResponseTyped; import io.helidon.webclient.http2.Http2Client; +import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http2.Http2Route; import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webserver.testing.junit5.Socket; -import io.helidon.webclient.api.ClientResponseTyped; -import io.helidon.webserver.http.HttpRules; import org.junit.jupiter.api.Test; @@ -38,12 +39,12 @@ abstract class Http2AbstractTestingTest { @SetUpRoute static void routing(HttpRules rules) { - rules.route(Http2Route.route(Http.Method.GET, "/greet", (req, res) -> res.send("hello"))); + rules.route(Http2Route.route(Method.GET, "/greet", (req, res) -> res.send("hello"))); } @SetUpRoute("custom") static void customRouting(HttpRules rules) { - rules.route(Http2Route.route(Http.Method.GET, "/greet", (req, res) -> res.send("custom"))); + rules.route(Http2Route.route(Method.GET, "/greet", (req, res) -> res.send("custom"))); } @Test @@ -51,7 +52,7 @@ void testDefaultPort() { ClientResponseTyped response = httpClient.get("/greet") .request(String.class); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity(), is("hello")); } @@ -60,7 +61,7 @@ void testCustomPort(@Socket("custom") Http2Client customClient) { ClientResponseTyped response = customClient.get("/greet") .request(String.class); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity(), is("custom")); } } diff --git a/webserver/testing/junit5/junit5/src/main/java/io/helidon/webserver/testing/junit5/DirectClient.java b/webserver/testing/junit5/junit5/src/main/java/io/helidon/webserver/testing/junit5/DirectClient.java index 977ccfc6743..2d4b122c8e9 100644 --- a/webserver/testing/junit5/junit5/src/main/java/io/helidon/webserver/testing/junit5/DirectClient.java +++ b/webserver/testing/junit5/junit5/src/main/java/io/helidon/webserver/testing/junit5/DirectClient.java @@ -23,7 +23,7 @@ import java.util.Optional; import io.helidon.common.socket.PeerInfo; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientConfig; import io.helidon.webclient.http1.Http1ClientRequest; @@ -67,7 +67,7 @@ public Http1ClientConfig prototype() { } @Override - public Http1ClientRequest method(Http.Method method) { + public Http1ClientRequest method(Method method) { if (clientHost == null) { clientHost = "localhost"; } diff --git a/webserver/testing/junit5/junit5/src/main/java/io/helidon/webserver/testing/junit5/DirectWebClient.java b/webserver/testing/junit5/junit5/src/main/java/io/helidon/webserver/testing/junit5/DirectWebClient.java index 70c68c9172f..774ddc92990 100644 --- a/webserver/testing/junit5/junit5/src/main/java/io/helidon/webserver/testing/junit5/DirectWebClient.java +++ b/webserver/testing/junit5/junit5/src/main/java/io/helidon/webserver/testing/junit5/DirectWebClient.java @@ -24,7 +24,7 @@ import io.helidon.common.socket.HelidonSocket; import io.helidon.common.socket.PeerInfo; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webclient.api.HttpClientRequest; import io.helidon.webclient.api.WebClient; import io.helidon.webclient.api.WebClientConfig; @@ -66,7 +66,7 @@ public DirectWebClient(HttpRouting routing) { } @Override - public HttpClientRequest method(Http.Method method) { + public HttpClientRequest method(Method method) { if (clientHost == null) { clientHost = "localhost"; } diff --git a/webserver/testing/junit5/junit5/src/test/java/io/helidon/webserver/testing/junit5/TestRoutingTest.java b/webserver/testing/junit5/junit5/src/test/java/io/helidon/webserver/testing/junit5/TestRoutingTest.java index 97d31853255..52160bcc302 100644 --- a/webserver/testing/junit5/junit5/src/test/java/io/helidon/webserver/testing/junit5/TestRoutingTest.java +++ b/webserver/testing/junit5/junit5/src/test/java/io/helidon/webserver/testing/junit5/TestRoutingTest.java @@ -22,7 +22,8 @@ import java.util.LinkedList; import java.util.List; -import io.helidon.http.Http; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; @@ -49,16 +50,16 @@ static void routing(HttpRouting.Builder router) { .post("/post", (req, res) -> { String requestEntity = req.content().as(String.class); if (ENTITY.equals(requestEntity)) { - res.status(Http.Status.CREATED_201); + res.status(Status.CREATED_201); } else { - res.status(Http.Status.INTERNAL_SERVER_ERROR_500); + res.status(Status.INTERNAL_SERVER_ERROR_500); } res.send(); }) .get("/name", (req, res) -> { String name = req.remotePeer().tlsPrincipal().map(Principal::getName).orElse(null); if (name == null) { - res.status(Http.Status.BAD_REQUEST_400).send("Expected client principal"); + res.status(Status.BAD_REQUEST_400).send("Expected client principal"); } else { res.send(name); } @@ -66,7 +67,7 @@ static void routing(HttpRouting.Builder router) { .get("/certs", (req, res) -> { Certificate[] certs = req.remotePeer().tlsCertificates().orElse(null); if (certs == null) { - res.status(Http.Status.BAD_REQUEST_400).send("Expected client certificate"); + res.status(Status.BAD_REQUEST_400).send("Expected client certificate"); } else { List certDefs = new LinkedList<>(); for (Certificate cert : certs) { @@ -116,22 +117,22 @@ void testInjectDefaultGet(@Socket("@default") DirectClient client) { @Test void testPost() { - Http1ClientResponse response = client.method(Http.Method.POST) + Http1ClientResponse response = client.method(Method.POST) .uri("/post") .submit(ENTITY); - assertThat(response.status(), is(Http.Status.CREATED_201)); + assertThat(response.status(), is(Status.CREATED_201)); } @Test void testMutualTlsPrincipal() { String principal = "Custom principal name"; client.clientTlsPrincipal(new TestPrincipal(principal)); - Http1ClientResponse response = client.method(Http.Method.GET) + Http1ClientResponse response = client.method(Method.GET) .uri("/name") .request(); - assertAll(() -> assertThat(response.status(), is(Http.Status.OK_200)), + assertAll(() -> assertThat(response.status(), is(Status.OK_200)), () -> assertThat(response.as(String.class), is(principal))); } diff --git a/webserver/testing/junit5/websocket/src/main/java/io/helidon/webserver/testing/junit5/websocket/DirectWsClient.java b/webserver/testing/junit5/websocket/src/main/java/io/helidon/webserver/testing/junit5/websocket/DirectWsClient.java index 981eb116f99..e61a5f7f5da 100644 --- a/webserver/testing/junit5/websocket/src/main/java/io/helidon/webserver/testing/junit5/websocket/DirectWsClient.java +++ b/webserver/testing/junit5/websocket/src/main/java/io/helidon/webserver/testing/junit5/websocket/DirectWsClient.java @@ -21,8 +21,8 @@ import java.util.ArrayList; import java.util.List; -import io.helidon.http.Http; import io.helidon.http.HttpPrologue; +import io.helidon.http.Method; import io.helidon.webclient.websocket.WsClient; import io.helidon.webclient.websocket.WsClientConfig; import io.helidon.webserver.websocket.WsRoute; @@ -54,7 +54,7 @@ public static DirectWsClient create(WsRouting routing) { @Override public void connect(URI uri, WsListener clientListener) { - HttpPrologue prologue = HttpPrologue.create("ws", "ws", "13", Http.Method.GET, uri.getRawPath(), false); + HttpPrologue prologue = HttpPrologue.create("ws", "ws", "13", Method.GET, uri.getRawPath(), false); WsRoute route = routing.findRoute(prologue); DirectWsConnection directWsConnection = DirectWsConnection.create(prologue, clientListener, route); directWsConnection.start(); diff --git a/webserver/tests/access-log/src/test/java/io/helidon/webserver/tests/accesslog/AccessLogTest.java b/webserver/tests/access-log/src/test/java/io/helidon/webserver/tests/accesslog/AccessLogTest.java index 7aca6fa1728..36a9fa8b418 100644 --- a/webserver/tests/access-log/src/test/java/io/helidon/webserver/tests/accesslog/AccessLogTest.java +++ b/webserver/tests/access-log/src/test/java/io/helidon/webserver/tests/accesslog/AccessLogTest.java @@ -27,10 +27,9 @@ import java.util.logging.LogRecord; import java.util.logging.StreamHandler; -import io.helidon.http.Http; import io.helidon.common.testing.http.junit5.SocketHttpClient; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.accesslog.AccessLogFeature; @@ -40,6 +39,8 @@ import io.helidon.webserver.accesslog.TimestampLogEntry; import io.helidon.webserver.accesslog.UserLogEntry; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -82,17 +83,17 @@ static void routing(HttpRouting.Builder router) { @Test void testRequestsAndValidateAccessLog() { Http1ClientResponse response = client.get("/access").request(); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity().as(String.class), is("Hello World!")); response = client.get("/wrong").request(); - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); - String socketResponse = socketClient.sendAndReceive(Http.Method.GET, + String socketResponse = socketClient.sendAndReceive(Method.GET, "/access", null, List.of("Content-Length: 47a")); - assertThat(socketResponse, startsWith("HTTP/1.1 " + Http.Status.BAD_REQUEST_400.text())); + assertThat(socketResponse, startsWith("HTTP/1.1 " + Status.BAD_REQUEST_400.text())); // Use retry since no happens-before relationship between log entry and assertion assertThatWithRetry("Check log entry for /access exist", diff --git a/webserver/tests/gh2631/src/test/java/io/helidon/webserver/tests/gh2631/Gh2631Test.java b/webserver/tests/gh2631/src/test/java/io/helidon/webserver/tests/gh2631/Gh2631Test.java index 5540975f319..386abb9448a 100644 --- a/webserver/tests/gh2631/src/test/java/io/helidon/webserver/tests/gh2631/Gh2631Test.java +++ b/webserver/tests/gh2631/src/test/java/io/helidon/webserver/tests/gh2631/Gh2631Test.java @@ -16,14 +16,14 @@ package io.helidon.webserver.tests.gh2631; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -58,7 +58,7 @@ void testClasspathNoFallback() { @Test void testClasspathNoFallbackMissing() { Http1ClientResponse response = getResponse("/simple/second/"); - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } @Test @@ -95,7 +95,7 @@ void testFileNoFallback() { @Test void testFileNoFallbackMissing() { HttpClientResponse response = getResponse("/simpleFile/second/"); - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } @Test diff --git a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/ConsumeTest.java b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/ConsumeTest.java index 142783a18fb..55bc30cb75e 100644 --- a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/ConsumeTest.java +++ b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/ConsumeTest.java @@ -31,8 +31,8 @@ import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; -import static io.helidon.http.Http.Method.PUT; +import static io.helidon.http.Method.GET; +import static io.helidon.http.Method.PUT; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.fail; diff --git a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/CutConnectionTest.java b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/CutConnectionTest.java index 097af9acd5e..a8ba6800532 100644 --- a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/CutConnectionTest.java +++ b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/CutConnectionTest.java @@ -16,14 +16,6 @@ package io.helidon.webserver.tests.http2; -import io.helidon.http.Http; -import io.helidon.logging.common.LogConfig; -import io.helidon.webserver.http2.Http2Route; -import io.helidon.webserver.WebServer; -import io.helidon.webserver.http.ServerRequest; -import io.helidon.webserver.http.ServerResponse; -import org.junit.jupiter.api.Test; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -42,6 +34,15 @@ import java.util.logging.LogRecord; import java.util.logging.Logger; +import io.helidon.http.Method; +import io.helidon.logging.common.LogConfig; +import io.helidon.webserver.WebServer; +import io.helidon.webserver.http.ServerRequest; +import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.http2.Http2Route; + +import org.junit.jupiter.api.Test; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -85,7 +86,7 @@ void testStringRoute() throws Exception { WEBSERVER_LOGGER.addHandler(ASSERTING_HANDLER); WebServer server = WebServer.builder() .host("localhost") - .routing(r -> r.route(Http2Route.route(Http.Method.GET, "/stream", CutConnectionTest::stream))) + .routing(r -> r.route(Http2Route.route(Method.GET, "/stream", CutConnectionTest::stream))) .build(); server.start(); diff --git a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/FlowControlTest.java b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/FlowControlTest.java index 61ab66cad53..c21a668835f 100644 --- a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/FlowControlTest.java +++ b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/FlowControlTest.java @@ -36,19 +36,19 @@ import io.helidon.common.reactive.Multi; import io.helidon.http.http2.WindowSize; import io.helidon.webclient.http2.Http2Client; +import io.helidon.webserver.WebServer; +import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http2.Http2Config; import io.helidon.webserver.http2.Http2ConnectionSelector; import io.helidon.webserver.http2.Http2Route; import io.helidon.webserver.testing.junit5.ServerTest; import io.helidon.webserver.testing.junit5.SetUpServer; -import io.helidon.webserver.WebServer; -import io.helidon.webserver.WebServerConfig; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; -import static io.helidon.http.Http.Method.PUT; +import static io.helidon.http.Method.GET; +import static io.helidon.http.Method.PUT; import static java.lang.System.Logger.Level.DEBUG; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; diff --git a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/GetTest.java b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/GetTest.java index e2778c48c13..73aceb24a61 100644 --- a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/GetTest.java +++ b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/GetTest.java @@ -28,13 +28,17 @@ import java.util.OptionalLong; import java.util.Random; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -44,12 +48,12 @@ @ServerTest class GetTest { private static final byte[] BYTES = new byte[256]; - private static final HeaderName REQUEST_HEADER_NAME = Http.HeaderNames.create("X-ReQUEst-header"); + private static final HeaderName REQUEST_HEADER_NAME = HeaderNames.create("X-ReQUEst-header"); private static final String REQUEST_HEADER_VALUE = "some nice value"; - private static final HeaderName RESPONSE_HEADER_NAME = Http.HeaderNames.create("X-REsponSE-HeADER"); + private static final HeaderName RESPONSE_HEADER_NAME = HeaderNames.create("X-REsponSE-HeADER"); private static final String RESPONSE_HEADER_VALUE_STRING = "another nice value"; - private static final Http.Header RESPONSE_HEADER_VALUE = Http.Headers.create(RESPONSE_HEADER_NAME, - RESPONSE_HEADER_VALUE_STRING); + private static final Header RESPONSE_HEADER_VALUE = HeaderValues.create(RESPONSE_HEADER_NAME, + RESPONSE_HEADER_VALUE_STRING); static { Random random = new Random(); @@ -69,10 +73,10 @@ class GetTest { @SetUpRoute static void routing(HttpRouting.Builder router) { - router.route(Http.Method.GET, "/string", Routes::string) - .route(Http.Method.GET, "/bytes", Routes::bytes) - .route(Http.Method.GET, "/stream", Routes::outputStream) - .route(Http.Method.GET, "/headers", Routes::headers); + router.route(Method.GET, "/string", Routes::string) + .route(Method.GET, "/bytes", Routes::bytes) + .route(Method.GET, "/stream", Routes::outputStream) + .route(Method.GET, "/headers", Routes::headers); } @Test @@ -83,7 +87,7 @@ void testStringRoute() throws IOException, InterruptedException { .GET() .build(), HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); String entity = response.body(); assertThat(entity, is("Hello")); java.net.http.HttpHeaders headers = response.headers(); @@ -99,7 +103,7 @@ void testByteRoute() throws IOException, InterruptedException { .GET() .build(), HttpResponse.BodyHandlers.ofByteArray()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); byte[] entity = response.body(); assertThat(entity, is(BYTES)); java.net.http.HttpHeaders headers = response.headers(); @@ -115,7 +119,7 @@ void testStreamRoute() throws IOException, InterruptedException { .GET() .build(), HttpResponse.BodyHandlers.ofByteArray()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); byte[] entity = response.body(); assertThat(entity, is(BYTES)); java.net.http.HttpHeaders headers = response.headers(); @@ -133,7 +137,7 @@ void testHeadersRoute() throws IOException, InterruptedException { .GET() .build(), HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); String entity = response.body(); assertThat(entity, is("Hello")); java.net.http.HttpHeaders headers = response.headers(); diff --git a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/HalfClosedStreamsTest.java b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/HalfClosedStreamsTest.java index 4bc780e5f8d..4885b7cd21f 100644 --- a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/HalfClosedStreamsTest.java +++ b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/HalfClosedStreamsTest.java @@ -34,8 +34,8 @@ import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; -import static io.helidon.http.Http.Method.POST; +import static io.helidon.http.Method.GET; +import static io.helidon.http.Method.POST; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertTrue; diff --git a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/HeadersTest.java b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/HeadersTest.java index 24d829771cc..eadfa783170 100644 --- a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/HeadersTest.java +++ b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/HeadersTest.java @@ -27,6 +27,11 @@ import java.util.Set; import java.util.stream.Collectors; +import io.helidon.webserver.WebServer; +import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.http1.Http1Config; +import io.helidon.webserver.http1.Http1ConnectionSelector; import io.helidon.webserver.http2.Http2Config; import io.helidon.webserver.http2.Http2ConnectionSelector; import io.helidon.webserver.http2.Http2Route; @@ -34,17 +39,12 @@ import io.helidon.webserver.testing.junit5.ServerTest; import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webserver.testing.junit5.SetUpServer; -import io.helidon.webserver.WebServerConfig; -import io.helidon.webserver.WebServer; -import io.helidon.webserver.http.HttpRouting; -import io.helidon.webserver.http1.Http1Config; -import io.helidon.webserver.http1.Http1ConnectionSelector; import org.hamcrest.Matchers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; +import static io.helidon.http.Method.GET; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/Http2ErrorHandlingWithOutputStreamTest.java b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/Http2ErrorHandlingWithOutputStreamTest.java index 5976a0af7d5..c1c0eea8022 100644 --- a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/Http2ErrorHandlingWithOutputStreamTest.java +++ b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/Http2ErrorHandlingWithOutputStreamTest.java @@ -27,26 +27,28 @@ import java.util.Optional; import io.helidon.common.configurable.Resource; -import io.helidon.http.Http; import io.helidon.common.pki.Keys; import io.helidon.common.tls.Tls; -import io.helidon.webserver.http2.Http2Route; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.ErrorHandler; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.http2.Http2Route; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; +import static io.helidon.http.Method.GET; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; @@ -57,8 +59,8 @@ @ServerTest class Http2ErrorHandlingWithOutputStreamTest { - private static final Http.HeaderName MAIN_HEADER_NAME = Http.HeaderNames.create("main-handler"); - private static final Http.HeaderName ERROR_HEADER_NAME = Http.HeaderNames.create("error-handler"); + private static final HeaderName MAIN_HEADER_NAME = HeaderNames.create("main-handler"); + private static final HeaderName ERROR_HEADER_NAME = HeaderNames.create("error-handler"); private static HttpClient httpClient; private final int plainPort; private final int tlsPort; @@ -95,20 +97,20 @@ static void router(HttpRouting.Builder router) { // explicitly on HTTP/2 only, to make sure we do upgrade router.error(CustomException.class, new CustomRoutingHandler()) .route(Http2Route.route(GET, "get-outputStream", (req, res) -> { - res.status(Http.Status.OK_200); + res.status(Status.OK_200); res.header(MAIN_HEADER_NAME, "x"); res.outputStream(); throw new CustomException(); })) .route(Http2Route.route(GET, "get-outputStream-writeOnceThenError", (req, res) -> { - res.status(Http.Status.OK_200); + res.status(Status.OK_200); res.header(MAIN_HEADER_NAME, "x"); OutputStream os = res.outputStream(); os.write("writeOnceOnly".getBytes(StandardCharsets.UTF_8)); throw new CustomException(); })) .route(Http2Route.route(GET, "get-outputStream-writeTwiceThenError", (req, res) -> { - res.status(Http.Status.OK_200); + res.status(Status.OK_200); res.header(MAIN_HEADER_NAME, "x"); OutputStream os = res.outputStream(); os.write("writeOnce".getBytes(StandardCharsets.UTF_8)); @@ -116,7 +118,7 @@ static void router(HttpRouting.Builder router) { throw new CustomException(); })) .route(Http2Route.route(GET, "get-outputStream-writeFlushThenError", (req, res) -> { - res.status(Http.Status.OK_200); + res.status(Status.OK_200); res.header(MAIN_HEADER_NAME, "x"); OutputStream os = res.outputStream(); os.write("writeOnce".getBytes(StandardCharsets.UTF_8)); @@ -215,7 +217,7 @@ private HttpRequest httpRequest(String uriSuffix) { private static class CustomRoutingHandler implements ErrorHandler { @Override public void handle(ServerRequest req, ServerResponse res, CustomException throwable) { - res.status(Http.Status.I_AM_A_TEAPOT_418); + res.status(Status.I_AM_A_TEAPOT_418); res.header(ERROR_HEADER_NAME, "err"); res.send("TeaPotIAm"); } diff --git a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/Http2ServerTest.java b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/Http2ServerTest.java index b6df509b018..44777b5d87b 100644 --- a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/Http2ServerTest.java +++ b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/Http2ServerTest.java @@ -27,9 +27,10 @@ import io.helidon.common.configurable.Resource; import io.helidon.common.pki.Keys; import io.helidon.common.tls.Tls; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServer; @@ -44,7 +45,7 @@ import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; +import static io.helidon.http.Method.GET; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -53,7 +54,7 @@ class Http2ServerTest { public static final String MESSAGE = "Hello World!"; private static final String TEST_HEADER_NAME = "custom_header"; private static final String TEST_HEADER_VALUE = "as!fd"; - private static final Header TEST_HEADER = Http.Headers.create(HeaderNames.create(TEST_HEADER_NAME), TEST_HEADER_VALUE); + private static final Header TEST_HEADER = HeaderValues.create(HeaderNames.create(TEST_HEADER_NAME), TEST_HEADER_VALUE); private final int plainPort; private final int tlsPort; private final Http1Client http1Client; @@ -100,7 +101,7 @@ void testHttp1() { Http1ClientResponse response = http1Client.get("/") .request(); - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } @Test diff --git a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/PostTest.java b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/PostTest.java index f50542ed13d..f695f29e0a3 100644 --- a/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/PostTest.java +++ b/webserver/tests/http2/src/test/java/io/helidon/webserver/tests/http2/PostTest.java @@ -29,14 +29,18 @@ import java.util.OptionalLong; import java.util.Random; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webserver.http.Handler; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -46,13 +50,13 @@ @ServerTest class PostTest { private static final byte[] BYTES = new byte[256]; - private static final HeaderName REQUEST_HEADER_NAME = Http.HeaderNames.create("X-REquEst-HEADeR"); + private static final HeaderName REQUEST_HEADER_NAME = HeaderNames.create("X-REquEst-HEADeR"); private static final String REQUEST_HEADER_VALUE_STRING = "some nice value"; - private static final Http.Header REQUEST_HEADER_VALUE = Http.Headers.create(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); - private static final HeaderName RESPONSE_HEADER_NAME = Http.HeaderNames.create("X-REsponSE-HeADER"); + private static final Header REQUEST_HEADER_VALUE = HeaderValues.create(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); + private static final HeaderName RESPONSE_HEADER_NAME = HeaderNames.create("X-REsponSE-HeADER"); private static final String RESPONSE_HEADER_VALUE_STRING = "another nice value"; - private static final Http.Header RESPONSE_HEADER_VALUE = Http.Headers.create(RESPONSE_HEADER_NAME, - RESPONSE_HEADER_VALUE_STRING); + private static final Header RESPONSE_HEADER_VALUE = HeaderValues.create(RESPONSE_HEADER_NAME, + RESPONSE_HEADER_VALUE_STRING); static { Random random = new Random(); @@ -72,11 +76,11 @@ class PostTest { @SetUpRoute static void routing(HttpRouting.Builder router) { - router.route(Http.Method.POST, "/string", Handler.create(String.class, Routes::string)) - .route(Http.Method.POST, "/bytes", Handler.create(byte[].class, Routes::bytes)) - .route(Http.Method.POST, "/streamed", Routes::streamed) - .route(Http.Method.POST, "/headers", Routes::headers) - .route(Http.Method.POST, "/nocontent", Routes::noContent); + router.route(Method.POST, "/string", Handler.create(String.class, Routes::string)) + .route(Method.POST, "/bytes", Handler.create(byte[].class, Routes::bytes)) + .route(Method.POST, "/streamed", Routes::streamed) + .route(Method.POST, "/headers", Routes::headers) + .route(Method.POST, "/nocontent", Routes::noContent); } @Test @@ -93,7 +97,7 @@ void testStringRoute() throws IOException, InterruptedException { .POST(HttpRequest.BodyPublishers.ofString("Hello")) .build(), HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); String entity = response.body(); assertThat(entity, is("Hello")); java.net.http.HttpHeaders headers = response.headers(); @@ -115,7 +119,7 @@ void testByteRoute() throws IOException, InterruptedException { .POST(HttpRequest.BodyPublishers.ofByteArray(BYTES)) .build(), HttpResponse.BodyHandlers.ofByteArray()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); byte[] entity = response.body(); assertThat(entity, is(BYTES)); java.net.http.HttpHeaders headers = response.headers(); @@ -137,7 +141,7 @@ void testStreamedRoute() throws IOException, InterruptedException { .POST(HttpRequest.BodyPublishers.ofByteArray(BYTES)) .build(), HttpResponse.BodyHandlers.ofByteArray()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); byte[] entity = response.body(); assertThat(entity, is(BYTES)); java.net.http.HttpHeaders headers = response.headers(); @@ -161,7 +165,7 @@ void testHeadersRoute() throws IOException, InterruptedException { .POST(HttpRequest.BodyPublishers.ofString("Hello")) .build(), HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode(), is(Http.Status.OK_200.code())); + assertThat(response.statusCode(), is(Status.OK_200.code())); String entity = response.body(); assertThat(entity, is("Hello")); java.net.http.HttpHeaders headers = response.headers(); @@ -191,12 +195,12 @@ void testNoContentRoute() throws IOException, InterruptedException { .POST(HttpRequest.BodyPublishers.ofString("Hello")) .build(), HttpResponse.BodyHandlers.ofString()); - assertThat(response.statusCode(), is(Http.Status.NO_CONTENT_204.code())); + assertThat(response.statusCode(), is(Status.NO_CONTENT_204.code())); } private static class Routes { public static void noContent(ServerRequest req, ServerResponse res) { - res.status(Http.Status.NO_CONTENT_204); + res.status(Status.NO_CONTENT_204); res.send(); } diff --git a/webserver/tests/imperative/src/main/java/io/helidon/webserver/tests/imperative/ImperativeMain.java b/webserver/tests/imperative/src/main/java/io/helidon/webserver/tests/imperative/ImperativeMain.java index e48afb5fc82..8a513f760a7 100644 --- a/webserver/tests/imperative/src/main/java/io/helidon/webserver/tests/imperative/ImperativeMain.java +++ b/webserver/tests/imperative/src/main/java/io/helidon/webserver/tests/imperative/ImperativeMain.java @@ -18,7 +18,7 @@ import io.helidon.common.config.Config; import io.helidon.common.config.GlobalConfig; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.HttpRouting; @@ -45,7 +45,7 @@ public static void main(String[] args) { } static void routing(HttpRouting.Builder routing) { - Http.Method list = Http.Method.create("LIST"); + Method list = Method.create("LIST"); routing.get("/", (req, res) -> res.send("Hello World!")) .route(list, "/", (req, res) -> res.send("lll")) diff --git a/webserver/tests/mtls/src/test/java/io/helidon/webserver/tests/mtls/MtlsTest.java b/webserver/tests/mtls/src/test/java/io/helidon/webserver/tests/mtls/MtlsTest.java index cd4fdb55aab..4d8ba24479e 100644 --- a/webserver/tests/mtls/src/test/java/io/helidon/webserver/tests/mtls/MtlsTest.java +++ b/webserver/tests/mtls/src/test/java/io/helidon/webserver/tests/mtls/MtlsTest.java @@ -23,19 +23,20 @@ import java.util.List; import io.helidon.common.configurable.Resource; -import io.helidon.http.Http; import io.helidon.common.pki.Keys; import io.helidon.common.tls.Tls; import io.helidon.common.tls.TlsClientAuth; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.ClientResponseTyped; import io.helidon.webclient.api.WebClient; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -77,7 +78,7 @@ static void routing(HttpRouting.Builder routing) { routing.get("/name", (req, res) -> { String name = req.remotePeer().tlsPrincipal().map(Principal::getName).orElse(null); if (name == null) { - res.status(Http.Status.BAD_REQUEST_400).send("Expected client principal"); + res.status(Status.BAD_REQUEST_400).send("Expected client principal"); } else { res.send(name); } @@ -103,7 +104,7 @@ static void routing(HttpRouting.Builder routing) { .build(); server.reloadTls(tls); - res.status(Http.Status.OK_200).send(); + res.status(Status.OK_200).send(); }) .get("/serverCert", (req, res) -> { Certificate[] certs = req.localPeer().tlsCertificates().orElse(null); @@ -133,50 +134,50 @@ static void server(WebServerConfig.Builder builder) { @Test void testMutualTlsPrincipal() { - ClientResponseTyped response = client.method(Http.Method.GET) + ClientResponseTyped response = client.method(Method.GET) .uri("/name") .request(String.class); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity(), is("CN=Helidon-Test-Client")); } @Test void testMutualTlsCertificates() { - ClientResponseTyped response = client.method(Http.Method.GET) + ClientResponseTyped response = client.method(Method.GET) .uri("/certs") .request(String.class); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity(), is("X.509:CN=Helidon-Test-Client|X.509:CN=Helidon-Test-CA")); } @Test void testTlsReload() { - ClientResponseTyped response = client.method(Http.Method.GET) + ClientResponseTyped response = client.method(Method.GET) .uri("/serverCert") .request(String.class); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity(), is("X.509:CN=Helidon-Test-Server|X.509:CN=Helidon-Test-CA")); - response = client.method(Http.Method.GET) + response = client.method(Method.GET) .uri("/reload") .request(String.class); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); - response = client.method(Http.Method.GET) + response = client.method(Method.GET) .uri("/serverCert") .request(String.class); - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity(), is("X.509:CN=Helidon-Test-Server-Secondary|X.509:CN=Helidon-Test-CA")); } private static void sendCertificateString(Certificate[] certs, ServerResponse res) { if (certs == null) { - res.status(Http.Status.BAD_REQUEST_400).send("Expected client certificate"); + res.status(Status.BAD_REQUEST_400).send("Expected client certificate"); } else { List certDefs = new LinkedList<>(); for (Certificate cert : certs) { diff --git a/webserver/tests/observe/health/src/test/java/io/helidon/webserver/tests/observe/health/ObserveHealthDetailsTest.java b/webserver/tests/observe/health/src/test/java/io/helidon/webserver/tests/observe/health/ObserveHealthDetailsTest.java index 08202de95b2..8382b5c1e93 100644 --- a/webserver/tests/observe/health/src/test/java/io/helidon/webserver/tests/observe/health/ObserveHealthDetailsTest.java +++ b/webserver/tests/observe/health/src/test/java/io/helidon/webserver/tests/observe/health/ObserveHealthDetailsTest.java @@ -18,16 +18,17 @@ import java.io.IOException; -import io.helidon.http.Http; import io.helidon.health.HealthCheckResponse; +import io.helidon.http.Method; +import io.helidon.http.Status; +import io.helidon.webclient.http1.Http1Client; +import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.observe.ObserveFeature; import io.helidon.webserver.observe.health.HealthFeature; import io.helidon.webserver.observe.health.HealthObserveProvider; import io.helidon.webserver.testing.junit5.ServerTest; import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webclient.http1.Http1Client; -import io.helidon.webclient.http1.Http1ClientResponse; -import io.helidon.webserver.http.HttpRouting; import jakarta.json.JsonArray; import jakarta.json.JsonObject; @@ -70,7 +71,7 @@ void testHealthAll() { try (Http1ClientResponse response = httpClient.get("/observe/health") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("UP")); JsonArray checks = json.getJsonArray("checks"); @@ -78,11 +79,11 @@ void testHealthAll() { assertThat(checks, hasSize(1)); } - try (Http1ClientResponse response = httpClient.method(Http.Method.HEAD) + try (Http1ClientResponse response = httpClient.method(Method.HEAD) .path("/observe/health") .request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); assertThat("Content returned", response.entity().inputStream().read(), is(-1)); } catch (IOException e) { throw new RuntimeException(e); @@ -91,7 +92,7 @@ void testHealthAll() { healthCheck.status(DOWN); try (Http1ClientResponse response = httpClient.get("/observe/health") .request()) { - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("DOWN")); JsonArray checks = json.getJsonArray("checks"); @@ -99,11 +100,11 @@ void testHealthAll() { assertThat(checks, hasSize(1)); } - try (Http1ClientResponse response = httpClient.method(Http.Method.HEAD) + try (Http1ClientResponse response = httpClient.method(Method.HEAD) .path("/observe/health") .request()) { - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); assertThat("Content returned", response.entity().inputStream().read(), is(-1)); } catch (IOException e) { throw new RuntimeException(e); @@ -116,7 +117,7 @@ void testHealthLive() { try (Http1ClientResponse response = httpClient.get("/observe/health/live") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("UP")); JsonArray checks = json.getJsonArray("checks"); @@ -128,7 +129,7 @@ void testHealthLive() { try (Http1ClientResponse response = httpClient.get("/observe/health/live") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("UP")); JsonArray checks = json.getJsonArray("checks"); @@ -142,7 +143,7 @@ void testHealthStart() { try (Http1ClientResponse response = httpClient.get("/observe/health/started") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("UP")); JsonArray checks = json.getJsonArray("checks"); @@ -154,7 +155,7 @@ void testHealthStart() { try (Http1ClientResponse response = httpClient.get("/observe/health/started") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("UP")); JsonArray checks = json.getJsonArray("checks"); @@ -168,7 +169,7 @@ void testHealthReady() { try (Http1ClientResponse response = httpClient.get("/observe/health/ready") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("UP")); JsonArray checks = json.getJsonArray("checks"); @@ -179,7 +180,7 @@ void testHealthReady() { healthCheck.status(DOWN); try (Http1ClientResponse response = httpClient.get("/observe/health/ready") .request()) { - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("DOWN")); JsonArray checks = json.getJsonArray("checks"); @@ -193,7 +194,7 @@ void testHealthReadyOne() { try (Http1ClientResponse response = httpClient.get("/observe/health/ready/mine1") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("UP")); assertThat(json.getString("name"), is("ready-1")); @@ -204,7 +205,7 @@ void testHealthReadyOne() { healthCheck.status(DOWN); try (Http1ClientResponse response = httpClient.get("/observe/health/ready/mine1") .request()) { - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("DOWN")); assertThat(json.getString("name"), is("ready-1")); @@ -218,7 +219,7 @@ void testHealthRootOne() { try (Http1ClientResponse response = httpClient.get("/observe/health/check/mine1") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("UP")); assertThat(json.getString("name"), is("ready-1")); @@ -229,7 +230,7 @@ void testHealthRootOne() { healthCheck.status(DOWN); try (Http1ClientResponse response = httpClient.get("/observe/health/ready/mine1") .request()) { - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); JsonObject json = response.as(JsonObject.class); assertThat(json.getString("status"), is("DOWN")); assertThat(json.getString("name"), is("ready-1")); diff --git a/webserver/tests/observe/health/src/test/java/io/helidon/webserver/tests/observe/health/ObserveHealthTest.java b/webserver/tests/observe/health/src/test/java/io/helidon/webserver/tests/observe/health/ObserveHealthTest.java index 600cf1a8639..36e9cd8f043 100644 --- a/webserver/tests/observe/health/src/test/java/io/helidon/webserver/tests/observe/health/ObserveHealthTest.java +++ b/webserver/tests/observe/health/src/test/java/io/helidon/webserver/tests/observe/health/ObserveHealthTest.java @@ -16,16 +16,16 @@ package io.helidon.webserver.tests.observe.health; -import io.helidon.http.Http; -import io.helidon.http.Http.Headers; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; +import io.helidon.webclient.http1.Http1Client; +import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.observe.ObserveFeature; import io.helidon.webserver.observe.health.HealthFeature; import io.helidon.webserver.observe.health.HealthObserveProvider; import io.helidon.webserver.testing.junit5.ServerTest; import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webclient.http1.Http1Client; -import io.helidon.webclient.http1.Http1ClientResponse; -import io.helidon.webserver.http.HttpRouting; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -62,15 +62,15 @@ void testHealthAll() { try (Http1ClientResponse response = httpClient.get("/observe/health") .request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(Http.Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } healthCheck.status(DOWN); try (Http1ClientResponse response = httpClient.get("/observe/health") .request()) { - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); - assertThat(response.headers(), hasHeader(Http.Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } } @@ -79,16 +79,16 @@ void testHealthLive() { try (Http1ClientResponse response = httpClient.get("/observe/health/live") .request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(Http.Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } healthCheck.status(DOWN); try (Http1ClientResponse response = httpClient.get("/observe/health/live") .request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(Http.Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } } @@ -97,16 +97,16 @@ void testHealthStart() { try (Http1ClientResponse response = httpClient.get("/observe/health/started") .request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } healthCheck.status(DOWN); try (Http1ClientResponse response = httpClient.get("/observe/health/started") .request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } } @@ -115,15 +115,15 @@ void testHealthReady() { try (Http1ClientResponse response = httpClient.get("/observe/health/ready") .request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } healthCheck.status(DOWN); try (Http1ClientResponse response = httpClient.get("/observe/health/ready") .request()) { - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); - assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } } @@ -132,15 +132,15 @@ void testHealthReadyOne() { try (Http1ClientResponse response = httpClient.get("/observe/health/ready/mine1") .request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(Http.Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } healthCheck.status(DOWN); try (Http1ClientResponse response = httpClient.get("/observe/health/ready/mine1") .request()) { - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); - assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } } @@ -149,15 +149,15 @@ void testHealthRootOne() { try (Http1ClientResponse response = httpClient.get("/observe/health/check/mine1") .request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } healthCheck.status(DOWN); try (Http1ClientResponse response = httpClient.get("/observe/health/ready/mine1") .request()) { - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); - assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } } @@ -166,7 +166,7 @@ void testHealthRootOneNotFound() { try (Http1ClientResponse response = httpClient.get("/observe/health/check/mine2") .request()) { - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } } @@ -175,7 +175,7 @@ void testHealthRootReadyNotFound() { try (Http1ClientResponse response = httpClient.get("/observe/health/ready/mine2") .request()) { - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } } @@ -184,7 +184,7 @@ void testHealthLiveOneNotFound() { try (Http1ClientResponse response = httpClient.get("/observe/health/live/mine2") .request()) { - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } } @@ -193,7 +193,7 @@ void testHealthStartOneNotFound() { try (Http1ClientResponse response = httpClient.get("/observe/health/startup/mine2") .request()) { - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } } } diff --git a/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/IdleTimeoutTest.java b/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/IdleTimeoutTest.java index 031ff6893d5..2d46b9f53f8 100644 --- a/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/IdleTimeoutTest.java +++ b/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/IdleTimeoutTest.java @@ -19,13 +19,13 @@ import java.time.Duration; import java.util.List; -import io.helidon.http.Http; import io.helidon.common.testing.http.junit5.SocketHttpClient; +import io.helidon.http.Method; +import io.helidon.webserver.WebServerConfig; +import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.testing.junit5.ServerTest; import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webserver.testing.junit5.SetUpServer; -import io.helidon.webserver.WebServerConfig; -import io.helidon.webserver.http.HttpRules; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -57,7 +57,7 @@ static void routeSetup(HttpRules rules) { void testNoTimeout() throws InterruptedException { // the timer is using second precision, we must run for longer than 3 seconds to make sure for (int i = 0; i < 20; i++) { - String response = client.sendAndReceive(Http.Method.GET, "/greet", null, List.of("Connection: keep-alive")); + String response = client.sendAndReceive(Method.GET, "/greet", null, List.of("Connection: keep-alive")); assertThat(response, containsString("200 OK")); // we sleep for 50, timeout is 250, it should be ok Thread.sleep(150); @@ -67,7 +67,7 @@ void testNoTimeout() throws InterruptedException { @Test void testTimeout() throws InterruptedException { // the timer is using second precision, we must run for longer than 3 seconds to make sure - String response = client.sendAndReceive(Http.Method.GET, "/greet", null, List.of("Connection: keep-alive")); + String response = client.sendAndReceive(Method.GET, "/greet", null, List.of("Connection: keep-alive")); assertThat(response, containsString("200 OK")); // this should be triggered correctly through the timer Thread.sleep(3000); diff --git a/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/MaxConcurrentRequestsTest.java b/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/MaxConcurrentRequestsTest.java index d2a707cb00c..8a60aa76fdc 100644 --- a/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/MaxConcurrentRequestsTest.java +++ b/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/MaxConcurrentRequestsTest.java @@ -19,16 +19,17 @@ import java.util.List; import java.util.concurrent.CountDownLatch; -import io.helidon.http.Http; import io.helidon.common.testing.http.junit5.SocketHttpClient; -import io.helidon.webclient.http2.Http2Client; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.ClientResponseTyped; import io.helidon.webclient.api.WebClient; +import io.helidon.webclient.http2.Http2Client; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -73,15 +74,15 @@ void beforeEach() { @Test void testConcurrentRequests() throws InterruptedException { - client.request(Http.Method.GET, "/greet", null, List.of("Connection: keep-alive")); + client.request(Method.GET, "/greet", null, List.of("Connection: keep-alive")); serverCountDown.await(); // need to make sure we are in the server request // now that we have request in progress, any other should fail ClientResponseTyped response = webClient.get("/greet") .request(String.class); - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); response = http2Client.get("/greet") .request(String.class); - assertThat(response.status(), is(Http.Status.SERVICE_UNAVAILABLE_503)); + assertThat(response.status(), is(Status.SERVICE_UNAVAILABLE_503)); clientCountDown.countDown(); assertThat(client.receive(), containsString("200 OK")); } diff --git a/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/MaxTcpConnectionsTest.java b/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/MaxTcpConnectionsTest.java index a921a8d726b..17bc98b1c5a 100644 --- a/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/MaxTcpConnectionsTest.java +++ b/webserver/tests/resource-limits/src/test/java/io/helidon/webserver/tests/resourcelimit/MaxTcpConnectionsTest.java @@ -20,15 +20,15 @@ import java.time.Duration; import java.util.List; -import io.helidon.http.Http; import io.helidon.common.testing.http.junit5.SocketHttpClient; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Method; import io.helidon.webclient.api.ClientResponseTyped; import io.helidon.webclient.api.WebClient; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.RepeatedTest; @@ -59,7 +59,7 @@ static void routeSetup(HttpRules rules) { @RepeatedTest(100) void testConcurrentRequests() throws Exception { - String response = client.sendAndReceive(Http.Method.GET, "/greet", null, List.of("Connection: keep-alive")); + String response = client.sendAndReceive(Method.GET, "/greet", null, List.of("Connection: keep-alive")); assertThat(response, containsString("200 OK")); // we have a connection established with keep alive, we should not create a new one diff --git a/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseClientTest.java b/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseClientTest.java index 771193fcf0c..a812b102841 100644 --- a/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseClientTest.java +++ b/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseClientTest.java @@ -21,20 +21,20 @@ import io.helidon.common.media.type.MediaTypes; import io.helidon.http.sse.SseEvent; -import io.helidon.webclient.sse.SseSource; -import io.helidon.webserver.sse.SseSink; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; +import io.helidon.webclient.sse.SseSource; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.sse.SseSink; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import jakarta.json.JsonObject; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Headers.ACCEPT_EVENT_STREAM; +import static io.helidon.http.HeaderValues.ACCEPT_EVENT_STREAM; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseServerMediaTest.java b/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseServerMediaTest.java index 0702ba806a4..0ee68a6bc8c 100644 --- a/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseServerMediaTest.java +++ b/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseServerMediaTest.java @@ -25,26 +25,26 @@ import io.helidon.common.Weighted; import io.helidon.common.config.Config; import io.helidon.http.Headers; -import io.helidon.http.Http; import io.helidon.http.HttpMediaType; +import io.helidon.http.Status; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityWriter; import io.helidon.http.media.MediaSupport; import io.helidon.http.media.StringSupport; import io.helidon.http.media.spi.MediaSupportProvider; import io.helidon.http.sse.SseEvent; -import io.helidon.webserver.sse.SseSink; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.sse.SseSink; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Headers.ACCEPT_EVENT_STREAM; +import static io.helidon.http.HeaderValues.ACCEPT_EVENT_STREAM; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -83,7 +83,7 @@ private static void sse(ServerRequest req, ServerResponse res) { private void testSse(String path, String result) { try (Http1ClientResponse response = client.get(path).header(ACCEPT_EVENT_STREAM).request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is(result)); } } diff --git a/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseServerTest.java b/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseServerTest.java index 4dbf54ea613..cf49ddbe2d8 100644 --- a/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseServerTest.java +++ b/webserver/tests/sse/src/test/java/io/helidon/webserver/tests/sse/SseServerTest.java @@ -16,17 +16,17 @@ package io.helidon.webserver.tests.sse; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Headers.ACCEPT_EVENT_STREAM; -import static io.helidon.http.Http.Headers.ACCEPT_JSON; +import static io.helidon.http.HeaderValues.ACCEPT_EVENT_STREAM; +import static io.helidon.http.HeaderValues.ACCEPT_JSON; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -85,13 +85,13 @@ void testIdComment() { @Test void testWrongAcceptType() { try (Http1ClientResponse response = client.get("/sseString1").header(ACCEPT_JSON).request()) { - assertThat(response.status(), is(Http.Status.NOT_ACCEPTABLE_406)); + assertThat(response.status(), is(Status.NOT_ACCEPTABLE_406)); } } private void testSse(String path, String result) { try (Http1ClientResponse response = client.get(path).header(ACCEPT_EVENT_STREAM).request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is(result)); } } diff --git a/webserver/tests/static-content/src/test/java/io/helidon/webserver/tests/staticcontent/StaticContentTest.java b/webserver/tests/static-content/src/test/java/io/helidon/webserver/tests/staticcontent/StaticContentTest.java index d016ede09ad..f752126bef2 100644 --- a/webserver/tests/static-content/src/test/java/io/helidon/webserver/tests/staticcontent/StaticContentTest.java +++ b/webserver/tests/static-content/src/test/java/io/helidon/webserver/tests/staticcontent/StaticContentTest.java @@ -16,13 +16,13 @@ package io.helidon.webserver.tests.staticcontent; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.staticcontent.StaticContentService; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -70,7 +70,7 @@ void testNexted() { void testNotFound() { try (Http1ClientResponse response = client.get("/files/notThere") .request()) { - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } } @@ -78,7 +78,7 @@ void testNotFound() { void testOutOfDirectory() { try (Http1ClientResponse response = client.get("/files/../logging-test.properties") .request()) { - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); } } } diff --git a/webserver/tests/upgrade/src/main/java/io/helidon/webserver/tests/upgrade/Main.java b/webserver/tests/upgrade/src/main/java/io/helidon/webserver/tests/upgrade/Main.java index 635533c195f..edf710a912d 100644 --- a/webserver/tests/upgrade/src/main/java/io/helidon/webserver/tests/upgrade/Main.java +++ b/webserver/tests/upgrade/src/main/java/io/helidon/webserver/tests/upgrade/Main.java @@ -17,18 +17,18 @@ package io.helidon.webserver.tests.upgrade; import io.helidon.common.configurable.Resource; -import io.helidon.http.Http; -import io.helidon.http.PathMatchers; import io.helidon.common.pki.Keys; +import io.helidon.http.Method; +import io.helidon.http.PathMatchers; import io.helidon.logging.common.LogConfig; -import io.helidon.webserver.http2.Http2Route; import io.helidon.webserver.WebServer; import io.helidon.webserver.http1.Http1Route; +import io.helidon.webserver.http2.Http2Route; import io.helidon.webserver.websocket.WsRouting; -import static io.helidon.http.Http.Method.GET; -import static io.helidon.http.Http.Method.POST; -import static io.helidon.http.Http.Method.PUT; +import static io.helidon.http.Method.GET; +import static io.helidon.http.Method.POST; +import static io.helidon.http.Method.PUT; public class Main { @@ -58,11 +58,11 @@ public static WebServer startServer(boolean ssl) { .route(Http2Route.route(GET, "/versionspecific", (req, res) -> res.send("HTTP/2.0 route\n"))) .route(Http1Route.route(GET, "/versionspecific1", (req, res) -> res.send("HTTP/1.1 route\n"))) .route(Http2Route.route(GET, "/versionspecific2", (req, res) -> res.send("HTTP/2.0 route\n"))) - .route(Http.Method.predicate(GET), + .route(Method.predicate(GET), PathMatchers.create("/multi*"), (req, res) -> res.send("HTTP/" + req.prologue().protocolVersion() + " route " + req.prologue().method() + "\n")) - .route(Http.Method.predicate(POST, PUT), + .route(Method.predicate(POST, PUT), PathMatchers.create("/multi*"), (req, res) -> { diff --git a/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/CompressionTest.java b/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/CompressionTest.java index 7163c64b1de..d542fa83f74 100644 --- a/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/CompressionTest.java +++ b/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/CompressionTest.java @@ -16,14 +16,15 @@ package io.helidon.integration.webserver.upgrade.test; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientRequest; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -36,8 +37,8 @@ */ @ServerTest public class CompressionTest { - private static final Http.Header CONTENT_ENCODING_GZIP = Http.Headers.create(Http.HeaderNames.CONTENT_ENCODING, "gzip"); - private static final Http.Header CONTENT_ENCODING_DEFLATE = Http.Headers.create(Http.HeaderNames.CONTENT_ENCODING, "deflate"); + private static final Header CONTENT_ENCODING_GZIP = HeaderValues.create(HeaderNames.CONTENT_ENCODING, "gzip"); + private static final Header CONTENT_ENCODING_DEFLATE = HeaderValues.create(HeaderNames.CONTENT_ENCODING, "deflate"); private final Http1Client webClient; @@ -56,7 +57,7 @@ public static void routing(HttpRules rules) { @Test public void testGzip() { Http1ClientRequest request = webClient.get(); - request.header(Http.Headers.create(Http.HeaderNames.ACCEPT_ENCODING, "gzip")); + request.header(HeaderValues.create(HeaderNames.ACCEPT_ENCODING, "gzip")); try (Http1ClientResponse response = request.path("/compressed").request()) { assertThat(response.entity().as(String.class), equalTo("It works!")); assertThat(response.headers(), hasHeader(CONTENT_ENCODING_GZIP)); @@ -69,7 +70,7 @@ public void testGzip() { @Test public void testDeflateContent() { Http1ClientRequest builder = webClient.get(); - builder.header(Http.Headers.create(HeaderNames.ACCEPT_ENCODING, "deflate")); + builder.header(HeaderValues.create(HeaderNames.ACCEPT_ENCODING, "deflate")); try (Http1ClientResponse response = builder.path("/compressed").request()) { assertThat(response.entity().as(String.class), equalTo("It works!")); assertThat(response.headers(), hasHeader(CONTENT_ENCODING_DEFLATE)); diff --git a/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/SharedHttp2CacheTest.java b/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/SharedHttp2CacheTest.java index 488f811c9a7..9b382043321 100644 --- a/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/SharedHttp2CacheTest.java +++ b/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/SharedHttp2CacheTest.java @@ -16,7 +16,9 @@ package io.helidon.webserver.tests.upgrade.test; -import io.helidon.http.Http; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.Status; import io.helidon.logging.common.LogConfig; import io.helidon.webclient.http2.Http2Client; import io.helidon.webclient.http2.Http2ClientProtocolConfig; @@ -27,7 +29,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; -import static io.helidon.http.Http.Method.POST; +import static io.helidon.http.Method.POST; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -50,7 +52,7 @@ static Param[] params() { @MethodSource("params") void cacheHttp2WithServerRestart(Param param) { LogConfig.configureRuntime(); - Http.HeaderName clientPortHeader = Http.HeaderNames.create("client-port"); + HeaderName clientPortHeader = HeaderNames.create("client-port"); WebServer webServer = null; try { HttpRouting routing = HttpRouting.builder() @@ -79,7 +81,7 @@ void cacheHttp2WithServerRestart(Param param) { Integer firstReqClientPort; try (var res = webClient.post().submit("WHATEVER")) { firstReqClientPort = res.headers().get(clientPortHeader).get(Integer.TYPE); - assertThat(res.status(), is(Http.Status.OK_200)); + assertThat(res.status(), is(Status.OK_200)); } if (param.restart()) { @@ -95,7 +97,7 @@ void cacheHttp2WithServerRestart(Param param) { Integer secondReqClientPort; try (var res = webClient.post().submit("WHATEVER")) { secondReqClientPort = res.headers().get(clientPortHeader).get(Integer.TYPE); - assertThat(res.status(), is(Http.Status.OK_200)); + assertThat(res.status(), is(Status.OK_200)); } if (!param.restart()) { diff --git a/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/UpgradeCodecsCompositionTest.java b/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/UpgradeCodecsCompositionTest.java index b2efaf7d03f..cac006cdc4f 100644 --- a/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/UpgradeCodecsCompositionTest.java +++ b/webserver/tests/upgrade/src/test/java/io/helidon/webserver/tests/upgrade/test/UpgradeCodecsCompositionTest.java @@ -38,14 +38,14 @@ import javax.net.ssl.X509TrustManager; import io.helidon.common.configurable.Resource; -import io.helidon.http.Http; -import io.helidon.webserver.tests.upgrade.Main; -import io.helidon.logging.common.LogConfig; import io.helidon.common.tls.Tls; -import io.helidon.webclient.http2.Http2Client; +import io.helidon.http.Method; +import io.helidon.logging.common.LogConfig; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; +import io.helidon.webclient.http2.Http2Client; import io.helidon.webserver.WebServer; +import io.helidon.webserver.tests.upgrade.Main; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterAll; @@ -53,8 +53,8 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; -import static io.helidon.http.Http.Method.GET; -import static io.helidon.http.Http.Method.HEAD; +import static io.helidon.http.Method.GET; +import static io.helidon.http.Method.HEAD; import static java.net.http.HttpClient.Version.HTTP_1_1; import static java.net.http.HttpClient.Version.HTTP_2; import static org.hamcrest.MatcherAssert.assertThat; @@ -219,10 +219,10 @@ void versionSpecificHttp20MultipleMethods(String param) throws IOException, Inte String expectedResponse = version + " route " + method + "\n"; - assertThat(httpClient(Http.Method.create(method), url, version.contains("2") ? HTTP_2 : HTTP_1_1).body(), + assertThat(httpClient(Method.create(method), url, version.contains("2") ? HTTP_2 : HTTP_1_1).body(), is(expectedResponse)); var client = version.contains("2") ? webClient2 : webClient1; - try (HttpClientResponse response = doRequest(client, Http.Method.create(method), url)) { + try (HttpClientResponse response = doRequest(client, Method.create(method), url)) { assertThat(response.entity().as(String.class), is(expectedResponse)); } } @@ -250,7 +250,7 @@ public X509Certificate[] getAcceptedIssuers() { } } - private HttpResponse httpClient(Http.Method method, + private HttpResponse httpClient(Method method, String url, HttpClient.Version version) throws IOException, InterruptedException { HttpRequest.BodyPublisher body; @@ -268,7 +268,7 @@ private HttpResponse httpClient(Http.Method method, } private HttpClientResponse doRequest(io.helidon.webclient.api.HttpClient client, - Http.Method method, + Method method, String url) { return client.method(method) .uri(resolveUri(url)) diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/BadRequestTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/BadRequestTest.java index dc1091a34e6..e1e0d9eb080 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/BadRequestTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/BadRequestTest.java @@ -18,20 +18,23 @@ import java.util.List; +import io.helidon.common.testing.http.junit5.SocketHttpClient; import io.helidon.http.ClientResponseHeaders; import io.helidon.http.DirectHandler; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; import io.helidon.http.ServerResponseHeaders; -import io.helidon.common.testing.http.junit5.SocketHttpClient; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.DirectHandlers; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http1.Http1Route; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -44,7 +47,7 @@ class BadRequestTest { public static final String CUSTOM_REASON_PHRASE = "Custom-bad-request"; public static final String CUSTOM_ENTITY = "There we go"; - private static final Http.Header LOCATION_ERROR_PAGE = Http.Headers.create(Http.HeaderNames.LOCATION, "/errorPage"); + private static final Header LOCATION_ERROR_PAGE = HeaderValues.create(HeaderNames.LOCATION, "/errorPage"); private final Http1Client client; private final SocketHttpClient socketClient; @@ -56,7 +59,7 @@ class BadRequestTest { @SetUpRoute static void routing(HttpRules builder) { - builder.route(Http1Route.route(Http.Method.GET, + builder.route(Http1Route.route(Method.GET, "/", (req, res) -> res.send("Hi"))); } @@ -72,7 +75,7 @@ static void setUpServer(WebServerConfig.Builder builder) { @SuppressWarnings("resource") @Test void testOk() { - String response = client.method(Http.Method.GET) + String response = client.method(Method.GET) .request() .as(String.class); @@ -82,7 +85,7 @@ void testOk() { @Test void testInvalidRequest() { // wrong content length - String response = socketClient.sendAndReceive(Http.Method.GET, + String response = socketClient.sendAndReceive(Method.GET, "/", null, List.of("Content-Length: 47a")); @@ -94,12 +97,12 @@ void testInvalidRequest() { @Test void testInvalidRequestWithRedirect() { // wrong content length - String response = socketClient.sendAndReceive(Http.Method.GET, + String response = socketClient.sendAndReceive(Method.GET, "/redirect", null, List.of("Content-Length: 47a")); - assertThat(SocketHttpClient.statusFromResponse(response), is(Http.Status.TEMPORARY_REDIRECT_307)); + assertThat(SocketHttpClient.statusFromResponse(response), is(Status.TEMPORARY_REDIRECT_307)); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(response); assertThat(headers, hasHeader(LOCATION_ERROR_PAGE)); @@ -108,7 +111,7 @@ void testInvalidRequestWithRedirect() { @Test void testInvalidUri() { // must fail on creation of bare request impl (URI.create()) - String response = socketClient.sendAndReceive(Http.Method.GET, + String response = socketClient.sendAndReceive(Method.GET, "/bad{", null); @@ -147,18 +150,18 @@ void testBadHeaderWhitespace() { private static DirectHandler.TransportResponse badRequestHandler(DirectHandler.TransportRequest request, DirectHandler.EventType eventType, - Http.Status httpStatus, + Status httpStatus, ServerResponseHeaders responseHeaders, String message) { if (request.path().equals("/redirect")) { return DirectHandler.TransportResponse.builder() - .status(Http.Status.TEMPORARY_REDIRECT_307) + .status(Status.TEMPORARY_REDIRECT_307) .header(HeaderNames.LOCATION, "/errorPage") .build(); } return DirectHandler.TransportResponse.builder() - .status(Http.Status.create(Http.Status.BAD_REQUEST_400.code(), - CUSTOM_REASON_PHRASE)) + .status(Status.create(Status.BAD_REQUEST_400.code(), + CUSTOM_REASON_PHRASE)) .headers(responseHeaders) .entity(CUSTOM_ENTITY) .build(); diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ConfiguredLimitsTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ConfiguredLimitsTest.java index 108e6184869..83a66eb30f8 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ConfiguredLimitsTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ConfiguredLimitsTest.java @@ -16,13 +16,11 @@ package io.helidon.webserver.tests; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderName; -import io.helidon.http.Http.HeaderNames; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.ServerRequestHeaders; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; @@ -33,6 +31,9 @@ import io.helidon.webserver.http1.Http1Config; import io.helidon.webserver.http1.Http1ConnectionSelector; import io.helidon.webserver.spi.ServerConnectionSelector; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -111,14 +112,14 @@ void testInitialLine(int size, boolean success) { if (success) { assertThat("Initial line of size " + size + " should have passed", response.status(), - is(Http.Status.OK_200)); + is(Status.OK_200)); assertThat("This request should return what is configured in routing", response.entity().as(String.class), is("any")); } else { assertThat("Initial line of size " + size + " should have failed", response.status(), - is(Http.Status.BAD_REQUEST_400)); + is(Status.BAD_REQUEST_400)); } } } @@ -129,19 +130,19 @@ void testHeader(int size, boolean success) { String headerValue = "m".repeat(size); try (Http1ClientResponse response = client.get("any") - .header(Http.Headers.create(CUSTOM_HEADER, headerValue)) + .header(HeaderValues.create(CUSTOM_HEADER, headerValue)) .request()) { if (success) { assertThat("Header of size " + size + " should have passed", response.status(), - is(Http.Status.OK_200)); + is(Status.OK_200)); assertThat("This request should return content of " + CUSTOM_HEADER + " header", response.entity().as(String.class), is(headerValue)); } else { assertThat("Header of size " + size + " should have failed", response.status(), - is(Http.Status.BAD_REQUEST_400)); + is(Status.BAD_REQUEST_400)); } } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingContextTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingContextTest.java index 04aaab681f7..539d6b9d63e 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingContextTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingContextTest.java @@ -18,19 +18,20 @@ import java.util.NoSuchElementException; +import io.helidon.http.HeaderNames; import io.helidon.http.Headers; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.http.encoding.ContentDecoder; import io.helidon.http.encoding.ContentEncoder; import io.helidon.http.encoding.ContentEncodingContext; import io.helidon.http.encoding.ContentEncodingContextConfig; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -61,7 +62,7 @@ static void routing(HttpRules rules) { @Test void testCustomizeContentEncodingContext() { - try (Http1ClientResponse response = client.method(Http.Method.GET).uri("/hello").request()) { + try (Http1ClientResponse response = client.method(Method.GET).uri("/hello").request()) { assertThat(response.entity().as(String.class), equalTo("hello webserver")); assertThat(encodingContext.NO_ACCEPT_ENCODING_COUNT, greaterThan(0)); } @@ -112,7 +113,7 @@ public ContentDecoder decoder(String encodingId) throws NoSuchElementException { @Override public ContentEncoder encoder(Headers headers) { - if (headers.contains(Http.HeaderNames.ACCEPT_ENCODING)) { + if (headers.contains(HeaderNames.ACCEPT_ENCODING)) { ACCEPT_ENCODING_COUNT++; } else { NO_ACCEPT_ENCODING_COUNT++; diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingDisabledNoValidationTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingDisabledNoValidationTest.java index 3163a6fd368..262ac29958d 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingDisabledNoValidationTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingDisabledNoValidationTest.java @@ -15,14 +15,16 @@ */ package io.helidon.webserver.tests; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http1.Http1ConnectionSelector; import io.helidon.webserver.spi.ServerConnectionSelector; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -61,10 +63,10 @@ static void server(WebServerConfig.Builder server) { @Test void testContentEncodingHeader() { - try (Http1ClientResponse response = client().method(Http.Method.POST) - .header(Http.HeaderNames.CONTENT_ENCODING, "data") + try (Http1ClientResponse response = client().method(Method.POST) + .header(HeaderNames.CONTENT_ENCODING, "data") .submit("any")) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is("response")); } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingDisabledTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingDisabledTest.java index b7a4259d6f4..3b1a1279c1f 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingDisabledTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ContentEncodingDisabledTest.java @@ -15,15 +15,17 @@ */ package io.helidon.webserver.tests; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http1.Http1Config; import io.helidon.webserver.http1.Http1ConnectionSelector; import io.helidon.webserver.spi.ServerConnectionSelector; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -60,10 +62,10 @@ static void server(WebServerConfig.Builder server) { @Test void testContentEncodingHeader() { - try (Http1ClientResponse response = client().method(Http.Method.POST) - .header(Http.HeaderNames.CONTENT_ENCODING, "data") + try (Http1ClientResponse response = client().method(Method.POST) + .header(HeaderNames.CONTENT_ENCODING, "data") .submit("any")) { - assertThat(response.status(), is(Http.Status.BAD_REQUEST_400)); + assertThat(response.status(), is(Status.BAD_REQUEST_400)); assertThat(response.as(String.class), is("Content-Encoding header present when content encoding is disabled")); } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/Continue100ImmediatelyTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/Continue100ImmediatelyTest.java index 434eb0ab3a8..26e9379a746 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/Continue100ImmediatelyTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/Continue100ImmediatelyTest.java @@ -24,12 +24,11 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; -import io.helidon.http.Http; -import io.helidon.http.PathMatchers; import io.helidon.common.testing.http.junit5.SocketHttpClient; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.PathMatchers; +import io.helidon.http.Status; import io.helidon.webserver.WebServer; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.Handler; @@ -37,6 +36,9 @@ import io.helidon.webserver.http1.Http1Config; import io.helidon.webserver.http1.Http1ConnectionSelector; import io.helidon.webserver.spi.ServerConnectionSelector; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -53,20 +55,20 @@ class Continue100ImmediatelyTest { private static final Handler ANY_HANDLER = (req, res) -> { if (Boolean.parseBoolean(req.headers() - .first(Http.HeaderNames.create("test-fail-before-read")) + .first(HeaderNames.create("test-fail-before-read")) .orElse("false"))) { - res.status(Http.Status.EXPECTATION_FAILED_417).send(); + res.status(Status.EXPECTATION_FAILED_417).send(); return; } if (Boolean.parseBoolean(req.headers() - .first(Http.HeaderNames.create("test-throw-before-read")) + .first(HeaderNames.create("test-throw-before-read")) .orElse("false"))) { throw new RuntimeException("BOOM!!!"); } Optional blockId = req.headers() - .first(Http.HeaderNames.create("test-block-id")); + .first(HeaderNames.create("test-block-id")); // Block request content dump if blocker assigned blockId.map(BLOCKER_MAP::get) .orElse(CompletableFuture.completedFuture("")) @@ -76,7 +78,7 @@ class Continue100ImmediatelyTest { String s = req.content().as(String.class); if (Boolean.parseBoolean(req.headers() - .first(Http.HeaderNames.create("test-throw-after-read")) + .first(HeaderNames.create("test-throw-after-read")) .orElse("false"))) { throw new RuntimeException("BOOM!!!"); } @@ -101,20 +103,20 @@ static void server(WebServerConfig.Builder wsb) { @SetUpRoute static void routing(HttpRouting.Builder router) { - router.route(Http.Method.predicate(Http.Method.PUT, Http.Method.POST), + router.route(Method.predicate(Method.PUT, Method.POST), PathMatchers.exact("/redirect"), (req, res) -> - res.status(Http.Status.MOVED_PERMANENTLY_301) - .header(Http.HeaderNames.LOCATION, "/") + res.status(Status.MOVED_PERMANENTLY_301) + .header(HeaderNames.LOCATION, "/") // force 301 to not use chunked encoding // https://github.com/helidon-io/helidon/issues/5713 - .header(Http.HeaderNames.CONTENT_LENGTH, "0") + .header(HeaderNames.CONTENT_LENGTH, "0") .send() ) - .route(Http.Method.predicate(Http.Method.PUT, Http.Method.POST), + .route(Method.predicate(Method.PUT, Method.POST), PathMatchers.exact("/"), ANY_HANDLER) - .route(Http.Method.predicate(Http.Method.GET), - PathMatchers.exact("/"), (req, res) -> res.status(Http.Status.OK_200).send("GET TEST")); + .route(Method.predicate(Method.GET), + PathMatchers.exact("/"), (req, res) -> res.status(Status.OK_200).send("GET TEST")); } @Test diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/Continue100Test.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/Continue100Test.java index 6c18f444395..addfb43912e 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/Continue100Test.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/Continue100Test.java @@ -26,14 +26,16 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; -import io.helidon.http.Http; -import io.helidon.http.PathMatchers; import io.helidon.common.testing.http.junit5.SocketHttpClient; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.PathMatchers; +import io.helidon.http.Status; import io.helidon.webserver.WebServer; import io.helidon.webserver.http.Handler; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -50,20 +52,20 @@ class Continue100Test { private static Handler anyHandler = (req, res) -> { if (Boolean.parseBoolean(req.headers() - .first(Http.HeaderNames.create("test-fail-before-read")) + .first(HeaderNames.create("test-fail-before-read")) .orElse("false"))) { - res.status(Http.Status.EXPECTATION_FAILED_417).send(); + res.status(Status.EXPECTATION_FAILED_417).send(); return; } if (Boolean.parseBoolean(req.headers() - .first(Http.HeaderNames.create("test-throw-before-read")) + .first(HeaderNames.create("test-throw-before-read")) .orElse("false"))) { throw new RuntimeException("BOOM!!!"); } Optional blockId = req.headers() - .first(Http.HeaderNames.create("test-block-id")); + .first(HeaderNames.create("test-block-id")); // Block request content dump if blocker assigned blockId.map(BLOCKER_MAP::get) .orElse(CompletableFuture.completedFuture("")) @@ -73,7 +75,7 @@ class Continue100Test { String s = req.content().as(String.class); if (Boolean.parseBoolean(req.headers() - .first(Http.HeaderNames.create("test-throw-after-read")) + .first(HeaderNames.create("test-throw-after-read")) .orElse("false"))) { throw new RuntimeException("BOOM!!!"); } @@ -83,27 +85,27 @@ class Continue100Test { @SetUpRoute static void routing(HttpRouting.Builder router) { - router.route(Http.Method.predicate(Http.Method.PUT, Http.Method.POST), - PathMatchers.exact("/redirect"), (req, res) -> + router.route(Method.predicate(Method.PUT, Method.POST), + PathMatchers.exact("/redirect"), (req, res) -> - res.status(Http.Status.MOVED_PERMANENTLY_301) - .header(Http.HeaderNames.LOCATION, "/") + res.status(Status.MOVED_PERMANENTLY_301) + .header(HeaderNames.LOCATION, "/") // force 301 to not use chunked encoding // https://github.com/helidon-io/helidon/issues/5713 - .header(Http.HeaderNames.CONTENT_LENGTH, "0") + .header(HeaderNames.CONTENT_LENGTH, "0") .send() ) - .route(Http.Method.predicate(Http.Method.PUT, Http.Method.POST), - PathMatchers.exact("/"), anyHandler) - .route(Http.Method.predicate(Http.Method.PUT), + .route(Method.predicate(Method.PUT, Method.POST), + PathMatchers.exact("/"), anyHandler) + .route(Method.predicate(Method.PUT), PathMatchers.exact("/chunked"), (req, res) -> { try (InputStream is = req.content().inputStream(); OutputStream os = res.outputStream()) { new ByteArrayInputStream(is.readAllBytes()).transferTo(os); } }) - .route(Http.Method.predicate(Http.Method.GET), - PathMatchers.exact("/"), (req, res) -> res.status(Http.Status.OK_200).send("GET TEST")); + .route(Method.predicate(Method.GET), + PathMatchers.exact("/"), (req, res) -> res.status(Status.OK_200).send("GET TEST")); } public Continue100Test(WebServer server) { diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/DisableValidateHeadersTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/DisableValidateHeadersTest.java index 0b127b80e1f..2019299a261 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/DisableValidateHeadersTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/DisableValidateHeadersTest.java @@ -18,14 +18,13 @@ import java.util.stream.Stream; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.ServerRequestHeaders; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientRequest; -import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.ServerRequest; @@ -37,13 +36,11 @@ import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webserver.testing.junit5.SetUpServer; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.params.provider.Arguments.arguments; @@ -83,11 +80,11 @@ static void routing(HttpRules rules) { @MethodSource("customHeaders") void testHeaders(String headerName, String headerValue, boolean expectsValid) { Http1ClientRequest request = client.get("/test"); - request.header(Http.Headers.create(Http.HeaderNames.create(headerName), headerValue)); + request.header(HeaderValues.create(HeaderNames.create(headerName), headerValue)); if (expectsValid) { HttpClientResponse response = request.request(); - assertThat(response.status(), is(Http.Status.OK_200)); - String responseHeaderValue = response.headers().get(Http.HeaderNames.create(headerName)).values(); + assertThat(response.status(), is(Status.OK_200)); + String responseHeaderValue = response.headers().get(HeaderNames.create(headerName)).values(); assertThat(responseHeaderValue, is(headerValue.trim())); } else { assertThrows(IllegalArgumentException.class, () -> request.request()); @@ -98,7 +95,7 @@ private static void disabledHeaderValidationHandler(ServerRequest request, Serve ServerRequestHeaders headers = request.headers(); request.headers().toMap().forEach((k, v) -> { if (k.contains("Header")) { - response.headers().add(Http.Headers.create(Http.HeaderNames.create(k), v)); + response.headers().add(HeaderValues.create(HeaderNames.create(k), v)); } }); response.send("any"); diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ErrorHandlingTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ErrorHandlingTest.java index 61e3668655f..fe7d39bdc4b 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ErrorHandlingTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ErrorHandlingTest.java @@ -16,10 +16,11 @@ package io.helidon.webserver.tests; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.DirectClient; -import io.helidon.webserver.testing.junit5.RoutingTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.ErrorHandler; @@ -30,6 +31,9 @@ import io.helidon.webserver.http.RoutingResponse; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.DirectClient; +import io.helidon.webserver.testing.junit5.RoutingTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -39,11 +43,11 @@ @RoutingTest class ErrorHandlingTest { - private static final Http.HeaderName CONTROL_HEADER = Http.HeaderNames.create("X-HELIDON-JUNIT"); - private static final Http.Header FIRST = Http.Headers.create(CONTROL_HEADER, "first"); - private static final Http.Header SECOND = Http.Headers.create(CONTROL_HEADER, "second"); - private static final Http.Header ROUTING = Http.Headers.create(CONTROL_HEADER, "routing"); - private static final Http.Header CUSTOM = Http.Headers.create(CONTROL_HEADER, "custom"); + private static final HeaderName CONTROL_HEADER = HeaderNames.create("X-HELIDON-JUNIT"); + private static final Header FIRST = HeaderValues.create(CONTROL_HEADER, "first"); + private static final Header SECOND = HeaderValues.create(CONTROL_HEADER, "second"); + private static final Header ROUTING = HeaderValues.create(CONTROL_HEADER, "routing"); + private static final Header CUSTOM = HeaderValues.create(CONTROL_HEADER, "custom"); private final Http1Client client; @@ -97,8 +101,8 @@ void testUnhandled() { try (Http1ClientResponse response = client.get() .header(ROUTING) .request()) { - assertThat(response.status(), is(Http.Status.INTERNAL_SERVER_ERROR_500)); - assertThat(response.headers(), hasHeader(Http.Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.INTERNAL_SERVER_ERROR_500)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ErrorHandlingWithOutputStreamTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ErrorHandlingWithOutputStreamTest.java index 540c2a316b4..7e679a9f61f 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ErrorHandlingWithOutputStreamTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ErrorHandlingWithOutputStreamTest.java @@ -20,15 +20,18 @@ import java.nio.charset.StandardCharsets; import io.helidon.common.buffers.DataReader; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.ErrorHandler; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -39,8 +42,8 @@ @ServerTest class ErrorHandlingWithOutputStreamTest { - private static final Http.HeaderName MAIN_HEADER_NAME = Http.HeaderNames.create("main-handler"); - private static final Http.HeaderName ERROR_HEADER_NAME = Http.HeaderNames.create("error-handler"); + private static final HeaderName MAIN_HEADER_NAME = HeaderNames.create("main-handler"); + private static final HeaderName ERROR_HEADER_NAME = HeaderNames.create("error-handler"); private final Http1Client client; @@ -90,7 +93,7 @@ static void router(HttpRouting.Builder router) { @Test void testOk() { try (var response = client.get().request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity().as(String.class), is("ok")); } } @@ -98,7 +101,7 @@ void testOk() { @Test void testGetOutputStreamThenError_expect_CustomErrorHandlerMessage() { try (var response = client.get("/get-outputStream").request()) { - assertThat(response.status(), is(Http.Status.I_AM_A_TEAPOT_418)); + assertThat(response.status(), is(Status.I_AM_A_TEAPOT_418)); assertThat(response.entity().as(String.class), is("CustomErrorContent")); assertThat(response.headers().contains(ERROR_HEADER_NAME), is(true)); assertThat(response.headers().contains(MAIN_HEADER_NAME), is(false)); @@ -108,7 +111,7 @@ void testGetOutputStreamThenError_expect_CustomErrorHandlerMessage() { @Test void testGetOutputStreamWriteOnceThenError_expect_CustomErrorHandlerMessage() { try (var response = client.get("/get-outputStream-writeOnceThenError").request()) { - assertThat(response.status(), is(Http.Status.I_AM_A_TEAPOT_418)); + assertThat(response.status(), is(Status.I_AM_A_TEAPOT_418)); assertThat(response.entity().as(String.class), is("CustomErrorContent")); assertThat(response.headers().contains(ERROR_HEADER_NAME), is(true)); assertThat(response.headers().contains(MAIN_HEADER_NAME), is(false)); @@ -117,32 +120,32 @@ void testGetOutputStreamWriteOnceThenError_expect_CustomErrorHandlerMessage() { @Test void testGetOutputStreamWriteTwiceThenError_expect_invalidResponse() { - try (Http1ClientResponse response = client.method(Http.Method.GET) + try (Http1ClientResponse response = client.method(Method.GET) .uri("/get-outputStream-writeTwiceThenError") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThrows(DataReader.InsufficientDataAvailableException.class, () -> response.entity().as(String.class)); } } @Test void testGetOutputStreamWriteFlushThenError_expect_invalidResponse() { - try (Http1ClientResponse response = client.method(Http.Method.GET) + try (Http1ClientResponse response = client.method(Method.GET) .uri("/get-outputStream-writeFlushThenError") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThrows(DataReader.InsufficientDataAvailableException.class, () -> response.entity().as(String.class)); } } @Test void testGetOutputStreamTryWithResourcesThenError_expect_CustomErrorHandlerMessage() { - try (Http1ClientResponse response = client.method(Http.Method.GET) + try (Http1ClientResponse response = client.method(Method.GET) .uri("/get-outputStream-tryWithResources") .request()) { - assertThat(response.status(), is(Http.Status.I_AM_A_TEAPOT_418)); + assertThat(response.status(), is(Status.I_AM_A_TEAPOT_418)); assertThat(response.entity().as(String.class), is("CustomErrorContent")); assertThat(response.headers().contains(ERROR_HEADER_NAME), is(true)); assertThat(response.headers().contains(MAIN_HEADER_NAME), is(false)); @@ -152,7 +155,7 @@ void testGetOutputStreamTryWithResourcesThenError_expect_CustomErrorHandlerMessa private static class CustomRoutingHandler implements ErrorHandler { @Override public void handle(ServerRequest req, ServerResponse res, CustomException throwable) { - res.status(Http.Status.I_AM_A_TEAPOT_418); + res.status(Status.I_AM_A_TEAPOT_418); res.header(ERROR_HEADER_NAME, "z"); res.send("CustomErrorContent"); } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ExceptionMessageTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ExceptionMessageTest.java index baef93a8b45..7393bba6b9b 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ExceptionMessageTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ExceptionMessageTest.java @@ -18,9 +18,11 @@ import java.util.Collections; -import io.helidon.http.Http; import io.helidon.common.testing.http.junit5.SocketHttpClient; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webserver.testing.junit5.ServerTest; + import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.containsString; @@ -46,25 +48,25 @@ void testNoUrlReflect() { String path = "/anyjavascript%3a/*%3c/script%3e%3cimg/onerror%3d'\\''" + "-/%22/-/%20onmouseover%d1/-/[%60*/[]/[(new(Image)).src%3d(/%3b/%2b/255t6qeelp23xlr08hn1uv" + "vnkeqae02stgk87yvnX%3b.oastifycom/).replace(/.%3b/g%2c[])]//'\\''src%3d%3e"; - String response = socketClient.sendAndReceive(Http.Method.GET, + String response = socketClient.sendAndReceive(Method.GET, path, ""); - Http.Status status = SocketHttpClient.statusFromResponse(response); + Status status = SocketHttpClient.statusFromResponse(response); String entity = SocketHttpClient.entityFromResponse(response, false); - assertThat(status, is(Http.Status.BAD_REQUEST_400)); + assertThat(status, is(Status.BAD_REQUEST_400)); assertThat(entity, containsString("see server log")); assertThat(entity, not(containsString("javascript"))); } @Test void testNoHeaderReflect() { - String response = socketClient.sendAndReceive(Http.Method.GET, + String response = socketClient.sendAndReceive(Method.GET, "/", "", Collections.singletonList(": ")); - Http.Status status = SocketHttpClient.statusFromResponse(response); + Status status = SocketHttpClient.statusFromResponse(response); String entity = SocketHttpClient.entityFromResponse(response, false); - assertThat(status, is(Http.Status.BAD_REQUEST_400)); + assertThat(status, is(Status.BAD_REQUEST_400)); assertThat(entity, not(containsString("javascript"))); } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/FollowRedirectTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/FollowRedirectTest.java index e93c4953c19..f2e561c71c9 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/FollowRedirectTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/FollowRedirectTest.java @@ -23,7 +23,9 @@ import java.time.Duration; import java.util.concurrent.TimeUnit; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.ClientResponseTyped; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; @@ -34,7 +36,7 @@ import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Status.INTERNAL_SERVER_ERROR_500; +import static io.helidon.http.Status.INTERNAL_SERVER_ERROR_500; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -50,23 +52,23 @@ class FollowRedirectTest { @SetUpRoute static void router(HttpRouting.Builder router) { - router.route(Http.Method.PUT, "/infiniteRedirect", (req, res) -> { - res.status(Http.Status.TEMPORARY_REDIRECT_307) - .header(Http.HeaderNames.LOCATION, "/infiniteRedirect2") + router.route(Method.PUT, "/infiniteRedirect", (req, res) -> { + res.status(Status.TEMPORARY_REDIRECT_307) + .header(HeaderNames.LOCATION, "/infiniteRedirect2") .send(); - }).route(Http.Method.PUT, "/infiniteRedirect2", (req, res) -> { - res.status(Http.Status.TEMPORARY_REDIRECT_307) - .header(Http.HeaderNames.LOCATION, "/infiniteRedirect") + }).route(Method.PUT, "/infiniteRedirect2", (req, res) -> { + res.status(Status.TEMPORARY_REDIRECT_307) + .header(HeaderNames.LOCATION, "/infiniteRedirect") .send(); - }).route(Http.Method.PUT, "/redirect", (req, res) -> { - res.status(Http.Status.TEMPORARY_REDIRECT_307) - .header(Http.HeaderNames.LOCATION, "/plain") + }).route(Method.PUT, "/redirect", (req, res) -> { + res.status(Status.TEMPORARY_REDIRECT_307) + .header(HeaderNames.LOCATION, "/plain") .send(); - }).route(Http.Method.PUT, "/redirectNoEntity", (req, res) -> { - res.status(Http.Status.FOUND_302) - .header(Http.HeaderNames.LOCATION, "/plain") + }).route(Method.PUT, "/redirectNoEntity", (req, res) -> { + res.status(Status.FOUND_302) + .header(HeaderNames.LOCATION, "/plain") .send(); - }).route(Http.Method.PUT, "/plain", (req, res) -> { + }).route(Method.PUT, "/plain", (req, res) -> { try (InputStream in = req.content().inputStream()) { byte[] buffer = new byte[128]; int read; @@ -78,25 +80,25 @@ static void router(HttpRouting.Builder router) { res.status(INTERNAL_SERVER_ERROR_500) .send(e.getMessage()); } - }).route(Http.Method.PUT, "/redirectAfterUpload", (req, res) -> { + }).route(Method.PUT, "/redirectAfterUpload", (req, res) -> { try (InputStream in = req.content().inputStream()) { byte[] buffer = new byte[128]; int read; while ((read = in.read(buffer)) > 0) { BUFFER.append("\n").append(new String(buffer, 0, read)); } - res.status(Http.Status.SEE_OTHER_303) - .header(Http.HeaderNames.LOCATION, "/afterUpload") + res.status(Status.SEE_OTHER_303) + .header(HeaderNames.LOCATION, "/afterUpload") .send(); } catch (Exception e) { res.status(INTERNAL_SERVER_ERROR_500) .send(e.getMessage()); } - }).route(Http.Method.GET, "/afterUpload", (req, res) -> { + }).route(Method.GET, "/afterUpload", (req, res) -> { res.send("Upload completed!" + BUFFER); - }).route(Http.Method.GET, "/plain", (req, res) -> { + }).route(Method.GET, "/plain", (req, res) -> { res.send("GET plain endpoint reached"); - }).route(Http.Method.PUT, "/close", (req, res) -> { + }).route(Method.PUT, "/close", (req, res) -> { byte[] buffer = new byte[10]; try (InputStream in = req.content().inputStream()) { in.read(buffer); @@ -105,7 +107,7 @@ static void router(HttpRouting.Builder router) { res.status(INTERNAL_SERVER_ERROR_500) .send(e.getMessage()); } - }).route(Http.Method.PUT, "/wait", (req, res) -> { + }).route(Method.PUT, "/wait", (req, res) -> { TimeUnit.MILLISECONDS.sleep(500); try (InputStream in = req.content().inputStream()) { byte[] buffer = new byte[128]; diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/FormParamsSupportTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/FormParamsSupportTest.java index 9681442b773..8a72e340f2f 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/FormParamsSupportTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/FormParamsSupportTest.java @@ -20,14 +20,15 @@ import java.util.List; import java.util.Map; -import io.helidon.http.Http; -import io.helidon.http.Http.HeaderNames; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.parameters.Parameters; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; import io.helidon.webclient.http1.Http1Client; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -60,7 +61,7 @@ static void routing(HttpRules rules) { @Test void urlEncodedTest() { - String result = client.method(Http.Method.PUT) + String result = client.method(Method.PUT) .path("/params") .header(HeaderNames.CONTENT_TYPE, MediaTypes.APPLICATION_FORM_URLENCODED.text()) .submit("key1=val+1&key2=val2_1&key2=val2_2") @@ -72,9 +73,9 @@ void urlEncodedTest() { @Test void plainTextTest() { - String result = client.method(Http.Method.PUT) + String result = client.method(Method.PUT) .path("/params") - .header(Http.Headers.CONTENT_TYPE_TEXT_PLAIN) + .header(HeaderValues.CONTENT_TYPE_TEXT_PLAIN) .submit("key1=val 1\nkey2=val2_1\nkey2=val2_2") .as(String.class); assertThat(result, containsString("key1=[val 1]")); diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/GetTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/GetTest.java index e957dd259a3..d15d3b7d7c6 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/GetTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/GetTest.java @@ -22,38 +22,39 @@ import java.util.Optional; import java.util.Random; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderName; -import io.helidon.http.Http.Headers; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.CONTENT_LENGTH; -import static io.helidon.http.Http.Method.GET; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; +import static io.helidon.http.HeaderNames.CONTENT_LENGTH; +import static io.helidon.http.Method.GET; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @ServerTest class GetTest { private static final byte[] BYTES = new byte[256]; - private static final HeaderName REQUEST_HEADER_NAME = Http.HeaderNames.create("X-REquEst-HEADeR"); + private static final HeaderName REQUEST_HEADER_NAME = HeaderNames.create("X-REquEst-HEADeR"); private static final String REQUEST_HEADER_VALUE_STRING = "some nice value"; - private static final Header REQUEST_HEADER_VALUE = Headers.create(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); - private static final HeaderName RESPONSE_HEADER_NAME = Http.HeaderNames.create("X-REsponSE-HeADER"); + private static final Header REQUEST_HEADER_VALUE = HeaderValues.create(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); + private static final HeaderName RESPONSE_HEADER_NAME = HeaderNames.create("X-REsponSE-HeADER"); private static final String RESPONSE_HEADER_VALUE_STRING = "another nice value"; - private static final Http.Header RESPONSE_HEADER_VALUE = Headers.create(RESPONSE_HEADER_NAME, + private static final Header RESPONSE_HEADER_VALUE = HeaderValues.create(RESPONSE_HEADER_NAME, RESPONSE_HEADER_VALUE_STRING); - public static final Header CONTENT_LENGTH_5 = Headers.create(CONTENT_LENGTH, "5"); + public static final Header CONTENT_LENGTH_5 = HeaderValues.create(CONTENT_LENGTH, "5"); static { Random random = new Random(); @@ -81,12 +82,12 @@ void testStringRoute() { try (Http1ClientResponse response = client.get("/string") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); io.helidon.http.Headers headers = response.headers(); assertThat(headers, hasHeader(CONTENT_LENGTH_5)); - assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } } @@ -95,12 +96,12 @@ void testByteRoute() { try (Http1ClientResponse response = client.get("/bytes") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); byte[] entity = response.entity().as(byte[].class); assertThat(entity, is(BYTES)); io.helidon.http.Headers headers = response.headers(); - assertThat(headers, hasHeader(Headers.create(CONTENT_LENGTH, String.valueOf(BYTES.length)))); - assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(HeaderValues.create(CONTENT_LENGTH, String.valueOf(BYTES.length)))); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } } @@ -110,12 +111,12 @@ void testChunkedRoute() { try (Http1ClientResponse response = client.get("/chunked") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); byte[] entity = response.entity().as(byte[].class); assertThat(entity, is(BYTES)); io.helidon.http.Headers headers = response.headers(); - assertThat(headers, hasHeader(Http.Headers.TRANSFER_ENCODING_CHUNKED)); - assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(HeaderValues.TRANSFER_ENCODING_CHUNKED)); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } } @@ -126,7 +127,7 @@ void testHeadersRoute() { .header(REQUEST_HEADER_VALUE) .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); io.helidon.http.Headers headers = response.headers(); @@ -134,7 +135,7 @@ void testHeadersRoute() { assertThat("Should contain echoed request header", headers, hasHeader(REQUEST_HEADER_VALUE)); assertThat("Should contain configured response header", headers, hasHeader(RESPONSE_HEADER_VALUE)); assertThat(headers, hasHeader(CONTENT_LENGTH_5)); - assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } } @@ -143,12 +144,12 @@ void testCloseRoute() { try (Http1ClientResponse response = client.get("/close") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); io.helidon.http.Headers headers = response.headers(); assertThat(headers, hasHeader(CONTENT_LENGTH_5)); - assertThat(headers, hasHeader(Http.Headers.CONNECTION_CLOSE)); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_CLOSE)); } } @@ -157,7 +158,7 @@ void testOptionalResponseWithValue() { try (Http1ClientResponse response = client.get("/optional") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("return value")); } @@ -169,8 +170,8 @@ void testOptionalResponseEmpty() { .queryParam("empty", "true") .request()) { - assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); - assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); + assertThat(response.status(), is(Status.NOT_FOUND_404)); + assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } } @@ -186,7 +187,7 @@ public static void optional(ServerRequest req, ServerResponse res) { } private static void close(ServerRequest req, ServerResponse res) { - res.header(Http.Headers.CONNECTION_CLOSE); + res.header(HeaderValues.CONNECTION_CLOSE); res.send("Hello"); } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/HttpPipelineTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/HttpPipelineTest.java index 15f34ebb198..4091a67b06a 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/HttpPipelineTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/HttpPipelineTest.java @@ -18,11 +18,11 @@ import java.util.concurrent.atomic.AtomicInteger; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.common.testing.http.junit5.SocketHttpClient; +import io.helidon.http.Method; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.notNullValue; @@ -72,9 +72,9 @@ static void routing(HttpRules rules) { */ //@RepeatedTest(10) void testPipelining() { - socketHttpClient.request(Http.Method.PUT, "/"); // reset server - socketHttpClient.request(Http.Method.GET, null); // request_0 - socketHttpClient.request(Http.Method.GET, null); // request_1 + socketHttpClient.request(Method.PUT, "/"); // reset server + socketHttpClient.request(Method.GET, null); // request_0 + socketHttpClient.request(Method.GET, null); // request_1 log("put client"); String reset = socketHttpClient.receive(); assertThat(reset, notNullValue()); diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/KeepAliveTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/KeepAliveTest.java index 196b9277f39..e709d9db85e 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/KeepAliveTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/KeepAliveTest.java @@ -20,21 +20,22 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; -import io.helidon.http.Http; -import io.helidon.http.Http.Headers; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientRequest; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.RepeatedTest; -import static io.helidon.http.Http.Status.INTERNAL_SERVER_ERROR_500; -import static io.helidon.http.Http.Status.OK_200; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; +import static io.helidon.http.Status.INTERNAL_SERVER_ERROR_500; +import static io.helidon.http.Status.OK_200; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; @@ -49,7 +50,7 @@ class KeepAliveTest { @SetUpRoute static void router(HttpRouting.Builder router) { - router.route(Http.Method.PUT, "/plain", (req, res) -> { + router.route(Method.PUT, "/plain", (req, res) -> { try (InputStream in = req.content().inputStream()) { byte[] buffer = new byte[128]; while (in.read(buffer) > 0) { @@ -60,7 +61,7 @@ static void router(HttpRouting.Builder router) { res.status(INTERNAL_SERVER_ERROR_500) .send(e.getMessage()); } - }).route(Http.Method.PUT, "/close", (req, res) -> { + }).route(Method.PUT, "/close", (req, res) -> { byte[] buffer = new byte[10]; try (InputStream in = req.content().inputStream()) { in.read(buffer); @@ -75,7 +76,7 @@ static void router(HttpRouting.Builder router) { @RepeatedTest(100) void sendWithKeepAlive() { try (HttpClientResponse response = testCall(webClient, true, "/plain", OK_200)) { - assertThat(response.headers(), hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); + assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } } @@ -83,7 +84,7 @@ void sendWithKeepAlive() { @RepeatedTest(100) void sendWithoutKeepAlive() { try (HttpClientResponse response = testCall(webClient, false, "/plain", OK_200)) { - assertThat(response.headers(), not(hasHeader(Headers.CONNECTION_KEEP_ALIVE))); + assertThat(response.headers(), not(hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE))); } } @@ -91,20 +92,20 @@ void sendWithoutKeepAlive() { void sendWithKeepAliveExpectKeepAlive() { // we attempt to fully consume request entity, if succeeded, we keep connection keep-alive try (HttpClientResponse response = testCall(webClient, true, "/close", INTERNAL_SERVER_ERROR_500)) { - assertThat(response.headers(), hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); + assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } } private static HttpClientResponse testCall(Http1Client client, boolean keepAlive, String path, - Http.Status expectedStatus) { + Status expectedStatus) { - Http1ClientRequest request = client.method(Http.Method.PUT) + Http1ClientRequest request = client.method(Method.PUT) .uri(path); if (!keepAlive) { - request.header(Http.Headers.CONNECTION_CLOSE); + request.header(HeaderValues.CONNECTION_CLOSE); } Http1ClientResponse response = request diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MaxPayloadSizeTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MaxPayloadSizeTest.java index e1af15408b0..76f9cedc893 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MaxPayloadSizeTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MaxPayloadSizeTest.java @@ -21,15 +21,16 @@ import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; -import io.helidon.http.Http; -import io.helidon.http.Http.Headers; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -75,12 +76,12 @@ static void setupRoute(HttpRules rules) { */ @Test void testContentLengthExceeded() { - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .path("/maxpayload") - .header(Http.Headers.CONTENT_TYPE_OCTET_STREAM) + .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) .submit(new byte[512])) { - assertThat(response.status(), is(Http.Status.REQUEST_ENTITY_TOO_LARGE_413)); - assertThat(response.headers(), hasHeader(Headers.CONNECTION_CLOSE)); + assertThat(response.status(), is(Status.REQUEST_ENTITY_TOO_LARGE_413)); + assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_CLOSE)); } } @@ -89,12 +90,12 @@ void testContentLengthExceeded() { */ @Test void testContentLengthExceededWithPayload() { - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .path("/maxpayload") - .header(Http.Headers.CONTENT_TYPE_OCTET_STREAM) + .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) .submit(PAYLOAD)) { - assertThat(response.status(), is(Http.Status.REQUEST_ENTITY_TOO_LARGE_413)); - assertThat(response.headers(), hasHeader(Headers.CONNECTION_CLOSE)); + assertThat(response.status(), is(Status.REQUEST_ENTITY_TOO_LARGE_413)); + assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_CLOSE)); } } @@ -105,18 +106,18 @@ void testContentLengthExceededWithPayload() { */ @Test void testActualLengthExceededWithPayload() { - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .path("/maxpayload") - .header(Headers.CONTENT_TYPE_OCTET_STREAM) - .header(Headers.TRANSFER_ENCODING_CHUNKED) + .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) + .header(HeaderValues.TRANSFER_ENCODING_CHUNKED) .outputStream(it -> { it.write(PAYLOAD_BYTES); it.write(PAYLOAD_BYTES); it.write(PAYLOAD_BYTES); it.close(); })) { - assertThat(response.status(), is(Http.Status.REQUEST_ENTITY_TOO_LARGE_413)); - assertThat(response.headers(), hasHeader(Http.Headers.CONNECTION_CLOSE)); + assertThat(response.status(), is(Status.REQUEST_ENTITY_TOO_LARGE_413)); + assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_CLOSE)); } } @@ -125,28 +126,28 @@ void testActualLengthExceededWithPayload() { */ @Test void testMixedGoodAndBadPayloads() { - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .path("/maxpayload") - .header(Http.Headers.CONTENT_TYPE_OCTET_STREAM) + .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) .submit(PAYLOAD.substring(0, 100))) { - assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers(), hasHeader(Headers.CONNECTION_KEEP_ALIVE)); + assertThat(response.status(), is(Status.OK_200)); + assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .path("/maxpayload") - .header(Http.Headers.CONTENT_TYPE_OCTET_STREAM) + .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) .submit(PAYLOAD)) { - assertThat(response.status(), is(Http.Status.REQUEST_ENTITY_TOO_LARGE_413)); - assertThat(response.headers(), hasHeader(Http.Headers.CONNECTION_CLOSE)); + assertThat(response.status(), is(Status.REQUEST_ENTITY_TOO_LARGE_413)); + assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_CLOSE)); } - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .path("/maxpayload") - .header(Http.Headers.CONTENT_TYPE_OCTET_STREAM) + .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) .submit(PAYLOAD.substring(0, (int) MAX_PAYLOAD_SIZE))) { - assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers(), hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); + assertThat(response.status(), is(Status.OK_200)); + assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MediaContextTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MediaContextTest.java index 1c24db290f1..7434284be61 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MediaContextTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MediaContextTest.java @@ -20,19 +20,19 @@ import io.helidon.common.GenericType; import io.helidon.http.Headers; -import io.helidon.http.Http; +import io.helidon.http.Method; import io.helidon.http.WritableHeaders; import io.helidon.http.media.EntityReader; import io.helidon.http.media.EntityWriter; import io.helidon.http.media.MediaContext; import io.helidon.http.media.MediaContextConfig; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.testing.junit5.SetUpServer; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.webserver.testing.junit5.SetUpServer; import org.junit.jupiter.api.Test; @@ -62,7 +62,7 @@ static void routing(HttpRules rules) { @Test void testCustomizeMediaContext() { - try (Http1ClientResponse response = client.method(Http.Method.GET).uri("/hello").request()) { + try (Http1ClientResponse response = client.method(Method.GET).uri("/hello").request()) { String responseEntityString = response.entity().as(String.class); assertThat(responseEntityString.length(), equalTo(5)); assertThat(responseEntityString, is("hello")); diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MultiPortTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MultiPortTest.java index 80a6c8ee403..fd7df44cdd9 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MultiPortTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/MultiPortTest.java @@ -16,7 +16,9 @@ package io.helidon.webserver.tests; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.api.WebClient; import io.helidon.webserver.WebServer; @@ -148,8 +150,8 @@ void compositeRedirectServer() { .putSocket("redirect", listener -> { listener.routing(routing -> routing .any((req, res) -> { - res.status(Http.Status.MOVED_PERMANENTLY_301) - .header(Http.HeaderNames.LOCATION, + res.status(Status.MOVED_PERMANENTLY_301) + .header(HeaderNames.LOCATION, String.format("http://%s:%s%s", host(req.authority()), server.port(), @@ -164,9 +166,9 @@ void compositeRedirectServer() { try (HttpClientResponse response = CLIENT.get("http://localhost:" + server.port("redirect") + "/foo") .request()) { - assertThat(response.status(), is(Http.Status.MOVED_PERMANENTLY_301)); + assertThat(response.status(), is(Status.MOVED_PERMANENTLY_301)); assertThat(response.headers(), - hasHeader(Http.Headers.create(Http.HeaderNames.LOCATION, "http://localhost:" + server.port() + "/foo"))); + hasHeader(HeaderValues.create(HeaderNames.LOCATION, "http://localhost:" + server.port() + "/foo"))); } } @@ -184,7 +186,7 @@ private void assertResponse(int port, String path, Matcher matcher) { .path(path) .request()) { - assertAll(() -> assertThat(response.status(), is(Http.Status.OK_200)), + assertAll(() -> assertThat(response.status(), is(Status.OK_200)), () -> assertThat(response.as(String.class), matcher)); } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/OutputStreamTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/OutputStreamTest.java index d94ba26a383..2411e420644 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/OutputStreamTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/OutputStreamTest.java @@ -21,17 +21,18 @@ import java.io.InputStream; import java.nio.charset.StandardCharsets; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; + import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.Method.GET; +import static io.helidon.http.Method.GET; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -52,7 +53,7 @@ static void routing(HttpRouting.Builder router) { @Test void verifyAutoFlush() { try (Http1ClientResponse response = client.get("/outputStream").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello World")); } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/PostTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/PostTest.java index 898c2a87dd6..3a02ed4009f 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/PostTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/PostTest.java @@ -22,25 +22,26 @@ import java.io.UncheckedIOException; import java.util.Random; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderName; -import io.helidon.http.Http.HeaderNames; -import io.helidon.http.Http.Headers; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Header; +import io.helidon.http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.Handler; import io.helidon.webserver.http.HttpRouting; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import static io.helidon.http.Http.HeaderNames.CONTENT_LENGTH; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; +import static io.helidon.http.HeaderNames.CONTENT_LENGTH; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -48,12 +49,12 @@ @ServerTest class PostTest { private static final byte[] BYTES = new byte[256]; - private static final HeaderName REQUEST_HEADER_NAME = Http.HeaderNames.create("X-REquEst-HEADeR"); + private static final HeaderName REQUEST_HEADER_NAME = HeaderNames.create("X-REquEst-HEADeR"); private static final String REQUEST_HEADER_VALUE_STRING = "some nice value"; - private static final Header REQUEST_HEADER_VALUE = Headers.create(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); + private static final Header REQUEST_HEADER_VALUE = HeaderValues.create(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); private static final HeaderName RESPONSE_HEADER_NAME = HeaderNames.create("X-REsponSE-HeADER"); private static final String RESPONSE_HEADER_VALUE_STRING = "another nice value"; - private static final Http.Header RESPONSE_HEADER_VALUE = Headers.create(RESPONSE_HEADER_NAME, + private static final Header RESPONSE_HEADER_VALUE = HeaderValues.create(RESPONSE_HEADER_NAME, RESPONSE_HEADER_VALUE_STRING); static { @@ -69,80 +70,80 @@ class PostTest { @SetUpRoute static void routing(HttpRouting.Builder router) { - router.route(Http.Method.POST, "/string", Handler.create(String.class, Routes::string)) - .route(Http.Method.POST, "/bytes", Handler.create(byte[].class, Routes::bytes)) - .route(Http.Method.POST, "/chunked", Routes::chunked) - .route(Http.Method.POST, "/headers", Routes::headers) - .route(Http.Method.POST, "/close", Routes::close); + router.route(Method.POST, "/string", Handler.create(String.class, Routes::string)) + .route(Method.POST, "/bytes", Handler.create(byte[].class, Routes::bytes)) + .route(Method.POST, "/chunked", Routes::chunked) + .route(Method.POST, "/headers", Routes::headers) + .route(Method.POST, "/close", Routes::close); } @Test void testStringRoute() { io.helidon.http.Headers headers; - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .uri("/string") .submit("Hello")) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); headers = response.headers(); } - assertThat(headers, hasHeader(Headers.create(CONTENT_LENGTH, "5"))); - assertThat(headers, hasHeader(Headers.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(HeaderValues.create(CONTENT_LENGTH, "5"))); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } @Test void testByteRoute() { io.helidon.http.Headers headers; - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .uri("/bytes") .submit(BYTES)) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); byte[] entity = response.entity().as(byte[].class); assertThat(entity, is(BYTES)); headers = response.headers(); } - assertThat(headers, hasHeader(Headers.create(CONTENT_LENGTH, String.valueOf(BYTES.length)))); - assertThat(headers, hasHeader(Headers.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(HeaderValues.create(CONTENT_LENGTH, String.valueOf(BYTES.length)))); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } @Test @Disabled("Optimization kicks in") void testChunkedRoute() { io.helidon.http.Headers headers; - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .uri("/chunked") .outputStream(outputStream -> { outputStream.write(BYTES); outputStream.close(); })) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); byte[] entity = response.entity().as(byte[].class); assertThat(entity, is(BYTES)); headers = response.headers(); } - assertThat(headers, hasHeader(Http.Headers.TRANSFER_ENCODING_CHUNKED)); - assertThat(headers, hasHeader(Headers.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(HeaderValues.TRANSFER_ENCODING_CHUNKED)); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } @Test void testHeadersRoute() { io.helidon.http.Headers headers; - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .uri("/headers") .header(REQUEST_HEADER_VALUE) .submit("Hello")) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); headers = response.headers(); } - assertThat(headers, hasHeader(Headers.create(CONTENT_LENGTH, "5"))); - assertThat(headers, hasHeader(Headers.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(HeaderValues.create(CONTENT_LENGTH, "5"))); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); assertThat(headers, hasHeader(REQUEST_HEADER_VALUE)); assertThat(headers, hasHeader(RESPONSE_HEADER_VALUE)); } @@ -150,21 +151,21 @@ void testHeadersRoute() { @Test void testCloseRoute() { io.helidon.http.Headers headers; - try (Http1ClientResponse response = client.method(Http.Method.POST) + try (Http1ClientResponse response = client.method(Method.POST) .uri("/close") .submit("Hello")) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); assertThrows(IllegalStateException.class, () -> response.entity().as(String.class)); headers = response.headers(); } - assertThat(headers, hasHeader(Headers.CONNECTION_CLOSE)); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_CLOSE)); } private static class Routes { public static void close(ServerRequest req, ServerResponse res) { - res.header(Headers.CONNECTION_CLOSE); - res.status(Http.Status.NO_CONTENT_204); + res.header(HeaderValues.CONNECTION_CLOSE); + res.status(Status.NO_CONTENT_204); res.send(); } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ReasonPhraseTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ReasonPhraseTest.java index aca5fbd4bd8..468925aefc6 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ReasonPhraseTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ReasonPhraseTest.java @@ -16,12 +16,12 @@ package io.helidon.webserver.tests; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -31,7 +31,7 @@ @ServerTest class ReasonPhraseTest { private static final String CUSTOM_PHRASE = "Custom error"; - private static final Http.Status CUSTOM_STATUS = Http.Status.create(400, CUSTOM_PHRASE); + private static final Status CUSTOM_STATUS = Status.create(400, CUSTOM_PHRASE); private final Http1Client client; @@ -41,7 +41,7 @@ class ReasonPhraseTest { @SetUpRoute static void routing(HttpRules routing) { - routing.get("/default", (req, res) -> res.status(Http.Status.BAD_REQUEST_400).send()) + routing.get("/default", (req, res) -> res.status(Status.BAD_REQUEST_400).send()) .get("/custom", (req, res) -> res.status(CUSTOM_STATUS).send()); } @@ -49,7 +49,7 @@ static void routing(HttpRules routing) { void testDefaultPhrase() { try (Http1ClientResponse response = client.get("/default") .request()) { - assertThat(response.status(), is(Http.Status.BAD_REQUEST_400)); + assertThat(response.status(), is(Status.BAD_REQUEST_400)); } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/RequestedUriTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/RequestedUriTest.java index 6aa4b35d03c..3cf8dccf2c2 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/RequestedUriTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/RequestedUriTest.java @@ -16,7 +16,7 @@ package io.helidon.webserver.tests; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webclient.api.ClientResponseTyped; import io.helidon.webclient.api.WebClient; import io.helidon.webserver.WebServer; @@ -53,7 +53,7 @@ static void routing(HttpRules rules) { res.send(req.requestedUri().toUri().toString()); } catch (Exception e) { e.printStackTrace(); - res.status(Http.Status.INTERNAL_SERVER_ERROR_500) + res.status(Status.INTERNAL_SERVER_ERROR_500) .send(e.getClass().getName() + ":" + e.getMessage()); } }); @@ -72,7 +72,7 @@ void ipV6Test() { assertAll( () -> assertThat(response.entity(), is("http://[::1]:" + port + "/uri")), - () -> assertThat(response.status(), is(Http.Status.OK_200)) + () -> assertThat(response.status(), is(Status.OK_200)) ); } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ReroutingAndNextingTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ReroutingAndNextingTest.java index 175464ffad2..73509b231f6 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ReroutingAndNextingTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ReroutingAndNextingTest.java @@ -16,13 +16,14 @@ package io.helidon.webserver.tests; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Header; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.HttpRouting; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -31,7 +32,7 @@ @ServerTest class ReroutingAndNextingTest { - private static final Header NEXTED_HEADER = Http.Headers.create("NEXTED", "yes"); + private static final Header NEXTED_HEADER = HeaderValues.create("NEXTED", "yes"); private final Http1Client client; @@ -60,7 +61,7 @@ void testReroute() { try (Http1ClientResponse response = client.get("/reroute") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.headers().contains(NEXTED_HEADER), is(true)); assertThat(response.as(String.class), is("Direct")); } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ResponseOrderingTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ResponseOrderingTest.java index 54d89f43077..d3fdfb63861 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ResponseOrderingTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ResponseOrderingTest.java @@ -23,7 +23,8 @@ import java.util.ArrayList; import java.util.concurrent.ConcurrentLinkedQueue; -import io.helidon.http.Http; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.testing.junit5.ServerTest; @@ -58,7 +59,7 @@ static void routing(HttpRules rules) { rules.any("/multi", (req, res) -> { long requestId = Long.parseLong(req.query().get("id")); queue.add(requestId); - res.status(Http.Status.CREATED_201) + res.status(Status.CREATED_201) .send("" + requestId); }) .any("/stream", (req, res) -> { @@ -92,7 +93,7 @@ void testContentOrdering() { .append("\n"); } - String response = client.method(Http.Method.POST) + String response = client.method(Method.POST) .path("/stream") .submit(sb.toString().getBytes()) .as(String.class); diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/RoutingTestBase.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/RoutingTestBase.java index c073fcc977a..106bca990eb 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/RoutingTestBase.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/RoutingTestBase.java @@ -19,7 +19,10 @@ import java.util.function.Function; import java.util.stream.Stream; -import io.helidon.http.Http; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientRequest; import io.helidon.webclient.http1.Http1ClientResponse; @@ -38,8 +41,8 @@ // Use by both RoutingTest and RulesTest to share the same test methods class RoutingTestBase { - private static final Http.Header MULTI_HANDLER = Http.Headers.createCached( - Http.HeaderNames.create("X-Multi-Handler"), "true"); + private static final Header MULTI_HANDLER = HeaderValues.createCached( + HeaderNames.create("X-Multi-Handler"), "true"); static Http1Client client; // Functions that will be used to execute http webclient shortcut methods private static Function get = x -> client.get(x); @@ -61,7 +64,7 @@ static void multiHandler(ServerRequest req, ServerResponse res) { void testRouteWithSpace() { try (Http1ClientResponse response = client.get("/my path").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String message = response.as(String.class); assertThat(message, is("done")); @@ -72,7 +75,7 @@ void testRouteWithSpace() { void testRouteWithUtf8() { try (Http1ClientResponse response = client.get("/českáCesta").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); String message = response.as(String.class); assertThat(message, is("done")); @@ -83,7 +86,7 @@ void testRouteWithUtf8() { @MethodSource("basic") void testHttpShortcutMethods(Function request, String path, String responseMessage) { try (Http1ClientResponse response = request.apply(path).request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is(responseMessage)); } } @@ -94,7 +97,7 @@ void testHttpShortcutMethodsWithoutPathPattern(Function String path, String responseMessage) { try (Http1ClientResponse response = request.apply(path).request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.as(String.class), is(responseMessage)); } } @@ -116,7 +119,7 @@ void testHttpShortcutMethodsWithMultiHandlers(Function res.send("test")) .put("/", (req, res) -> { String ignored = req.content().as(String.class); - res.status(Http.Status.NO_CONTENT_204).send(); + res.status(Status.NO_CONTENT_204).send(); }); } @Test void callPutAndGet() { - try (HttpClientResponse response = client.method(Http.Method.PUT) + try (HttpClientResponse response = client.method(Method.PUT) .submit("test call")) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + assertThat(response.status(), is(Status.NO_CONTENT_204)); } assertThat(client.get().requestEntity(String.class), is("test")); diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/StatusCodeTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/StatusCodeTest.java index 6a89cd19083..4269a028960 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/StatusCodeTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/StatusCodeTest.java @@ -16,12 +16,14 @@ package io.helidon.webserver.tests; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.ServerTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Method; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; import io.helidon.webserver.http.HttpRules; +import io.helidon.webserver.testing.junit5.ServerTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; + import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; @@ -46,8 +48,8 @@ static void routing(HttpRules rules) { @Test void testCode() { - try (HttpClientResponse response = client.method(Http.Method.GET).request()) { - assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); + try (HttpClientResponse response = client.method(Method.GET).request()) { + assertThat(response.status(), is(Status.NO_CONTENT_204)); } } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/TransferEncodingTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/TransferEncodingTest.java index 16a908a8f5d..ec19fb57173 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/TransferEncodingTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/TransferEncodingTest.java @@ -16,13 +16,15 @@ package io.helidon.webserver.tests; -import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; -import io.helidon.http.Http.Headers; import io.helidon.common.testing.http.junit5.SocketHttpClient; +import io.helidon.http.ClientResponseHeaders; +import io.helidon.http.Header; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; +import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.testing.junit5.ServerTest; import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.http.HttpRules; import org.junit.jupiter.api.Test; @@ -38,7 +40,7 @@ */ @ServerTest class TransferEncodingTest { - private static final Http.Header CONTENT_LENGTH_NINE = Headers.create(Http.HeaderNames.CONTENT_LENGTH, "9"); + private static final Header CONTENT_LENGTH_NINE = HeaderValues.create(HeaderNames.CONTENT_LENGTH, "9"); private final SocketHttpClient socketHttpClient; TransferEncodingTest(SocketHttpClient socketHttpClient) { @@ -54,7 +56,7 @@ static void routing(HttpRules rules) { }) .get("/chunked", (req, res) -> { String payload = "It works!"; - res.headers().add(Headers.TRANSFER_ENCODING_CHUNKED); + res.headers().add(HeaderValues.TRANSFER_ENCODING_CHUNKED); res.send(payload); }) .get("/optimized", (req, res) -> { @@ -65,7 +67,7 @@ static void routing(HttpRules rules) { res.send(); }) .get("/emptychunked", (req, res) -> { - res.headers().add(Headers.TRANSFER_ENCODING_CHUNKED); + res.headers().add(HeaderValues.TRANSFER_ENCODING_CHUNKED); res.send(); }); } @@ -75,10 +77,10 @@ static void routing(HttpRules rules) { */ @Test void testEmptyContentLength() { - String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/empty", null); + String s = socketHttpClient.sendAndReceive(Method.GET, "/empty", null); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); - assertThat(headers, hasHeader(Headers.CONTENT_LENGTH_ZERO)); + assertThat(headers, hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); } /** @@ -86,9 +88,9 @@ void testEmptyContentLength() { */ @Test void testEmptyChunked() { - String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/emptychunked", null); + String s = socketHttpClient.sendAndReceive(Method.GET, "/emptychunked", null); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); - assertThat(headers, hasHeader(Headers.TRANSFER_ENCODING_CHUNKED)); + assertThat(headers, hasHeader(HeaderValues.TRANSFER_ENCODING_CHUNKED)); } /** @@ -96,7 +98,7 @@ void testEmptyChunked() { */ @Test void testContentLength() { - String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/length", null); + String s = socketHttpClient.sendAndReceive(Method.GET, "/length", null); assertThat(cutPayloadAndCheckHeadersFormat(s), is("It works!")); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); assertThat(headers, hasHeader(CONTENT_LENGTH_NINE)); @@ -107,10 +109,10 @@ void testContentLength() { */ @Test void testChunkedEncoding() { - String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/chunked", null); + String s = socketHttpClient.sendAndReceive(Method.GET, "/chunked", null); assertThat(cutPayloadAndCheckHeadersFormat(s), is("9\nIt works!\n0\n\n")); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); - assertThat(headers, hasHeader(Headers.TRANSFER_ENCODING_CHUNKED)); + assertThat(headers, hasHeader(HeaderValues.TRANSFER_ENCODING_CHUNKED)); } /** @@ -118,7 +120,7 @@ void testChunkedEncoding() { */ @Test void testOptimized() { - String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/optimized", null); + String s = socketHttpClient.sendAndReceive(Method.GET, "/optimized", null); assertThat(cutPayloadAndCheckHeadersFormat(s), is("It works!")); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); assertThat(headers, hasHeader(CONTENT_LENGTH_NINE)); diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/UnsentResponseTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/UnsentResponseTest.java index 2ca1e8289e5..0821622432a 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/UnsentResponseTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/UnsentResponseTest.java @@ -16,15 +16,15 @@ package io.helidon.webserver.tests; -import io.helidon.http.Http; -import io.helidon.webserver.testing.junit5.DirectClient; -import io.helidon.webserver.testing.junit5.RoutingTest; -import io.helidon.webserver.testing.junit5.SetUpRoute; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.http.Handler; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.ServerRequest; import io.helidon.webserver.http.ServerResponse; +import io.helidon.webserver.testing.junit5.DirectClient; +import io.helidon.webserver.testing.junit5.RoutingTest; +import io.helidon.webserver.testing.junit5.SetUpRoute; import org.junit.jupiter.api.Test; @@ -46,7 +46,7 @@ void testUnsentResponseThrowsException(DirectClient client) { try (Http1ClientResponse response = client.get("/no-response") .request()) { - assertThat(response.status(), is(Http.Status.INTERNAL_SERVER_ERROR_500)); + assertThat(response.status(), is(Status.INTERNAL_SERVER_ERROR_500)); assertThat(response.entity().as(String.class), is("Internal Server Error")); } } @@ -56,7 +56,7 @@ void testNormalResponse(DirectClient client) { try (Http1ClientResponse response = client.get("/response") .request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/UriEncodingTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/UriEncodingTest.java index d1e9ed828fe..f0a9283d645 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/UriEncodingTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/UriEncodingTest.java @@ -18,7 +18,8 @@ import io.helidon.common.testing.http.junit5.SocketHttpClient; import io.helidon.http.ClientResponseHeaders; -import io.helidon.http.Http; +import io.helidon.http.HeaderValues; +import io.helidon.http.Method; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.testing.junit5.ServerTest; import io.helidon.webserver.testing.junit5.SetUpRoute; @@ -48,10 +49,10 @@ static void routing(HttpRules rules) { */ @Test void testEncodedUrl() { - String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/f%6F%6F", null); + String s = socketHttpClient.sendAndReceive(Method.GET, "/f%6F%6F", null); assertThat(SocketHttpClient.entityFromResponse(s, true), is("It works!")); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); - assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } /** @@ -59,9 +60,9 @@ void testEncodedUrl() { */ @Test void testEncodedUrlParams() { - String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/f%6F%6F/b%61%72", null); + String s = socketHttpClient.sendAndReceive(Method.GET, "/f%6F%6F/b%61%72", null); assertThat(SocketHttpClient.entityFromResponse(s, true), is("bar")); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); - assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ValidateRequestHeadersTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ValidateRequestHeadersTest.java index 42287d449e3..960e0df8d45 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ValidateRequestHeadersTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ValidateRequestHeadersTest.java @@ -18,14 +18,13 @@ import java.util.stream.Stream; -import io.helidon.http.Http; -import io.helidon.http.Http.Header; -import io.helidon.http.Http.HeaderName; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; import io.helidon.http.ServerRequestHeaders; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientRequest; -import io.helidon.webclient.http1.Http1ClientResponse; import io.helidon.webserver.WebServerConfig; import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.http.ServerRequest; @@ -37,7 +36,6 @@ import io.helidon.webserver.testing.junit5.SetUpRoute; import io.helidon.webserver.testing.junit5.SetUpServer; -import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -45,7 +43,6 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.params.provider.Arguments.arguments; /** @@ -82,12 +79,12 @@ static void routing(HttpRules rules) { @MethodSource("requestHeaders") void testHeadersFromResponse(String headerName, String headerValue, boolean expectsValid) { Http1ClientRequest request = client.get("/test"); - request.header(Http.Headers.create(Http.HeaderNames.create(headerName), headerValue)); + request.header(HeaderValues.create(HeaderNames.create(headerName), headerValue)); HttpClientResponse response = request.submit("any"); if (expectsValid) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); } else { - assertThat(response.status(), not(Http.Status.OK_200)); + assertThat(response.status(), not(Status.OK_200)); } } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ValidateResponseHeadersTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ValidateResponseHeadersTest.java index 1abda763c4e..d045bce81b5 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ValidateResponseHeadersTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/ValidateResponseHeadersTest.java @@ -21,7 +21,9 @@ import java.io.UncheckedIOException; import java.util.stream.Stream; -import io.helidon.http.Http; +import io.helidon.http.HeaderNames; +import io.helidon.http.HeaderValues; +import io.helidon.http.Status; import io.helidon.webclient.api.HttpClientResponse; import io.helidon.webclient.http1.Http1Client; import io.helidon.webclient.http1.Http1ClientRequest; @@ -84,11 +86,11 @@ void testHeadersFromResponse(String headerName, String headerValue, boolean expe Http1ClientRequest request = client.get("/test"); HttpClientResponse response = request.submit(headerNameAndValue); if (expectsValid) { - assertThat(response.status(), is(Http.Status.OK_200)); - String responseHeaderValue = response.headers().get(Http.HeaderNames.create(headerName)).values(); + assertThat(response.status(), is(Status.OK_200)); + String responseHeaderValue = response.headers().get(HeaderNames.create(headerName)).values(); assertThat(responseHeaderValue, is(headerValue.trim())); } else { - assertThat(response.status(), not(Http.Status.OK_200)); + assertThat(response.status(), not(Status.OK_200)); } } @@ -99,11 +101,11 @@ void testHeadersFromResponseOutputStream(String headerName, String headerValue, Http1ClientRequest request = client.get("/testOutputStream"); HttpClientResponse response = request.submit(headerNameAndValue); if (expectsValid) { - assertThat(response.status(), is(Http.Status.OK_200)); - String responseHeaderValue = response.headers().get(Http.HeaderNames.create(headerName)).values(); + assertThat(response.status(), is(Status.OK_200)); + String responseHeaderValue = response.headers().get(HeaderNames.create(headerName)).values(); assertThat(responseHeaderValue, is(headerValue.trim())); } else { - assertThat(response.status(), not(Http.Status.OK_200)); + assertThat(response.status(), not(Status.OK_200)); } } @@ -123,7 +125,7 @@ private static void responseHandlerForOutputStream(ServerRequest request, Server private static void setHeader(ServerRequest request, ServerResponse response) { String[] header = request.content().as(String.class).split(HEADER_NAME_VALUE_DELIMETER); - response.headers().add(Http.Headers.create(header[0], header[1])); + response.headers().add(HeaderValues.create(header[0], header[1])); } private static Stream responseHeaders() { diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/WebServerStopIdleTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/WebServerStopIdleTest.java index 2c0cf8df8dc..d389c50c6d7 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/WebServerStopIdleTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/WebServerStopIdleTest.java @@ -16,9 +16,10 @@ package io.helidon.webserver.tests; -import io.helidon.http.Http; +import io.helidon.http.Status; import io.helidon.webclient.http1.Http1Client; import io.helidon.webserver.WebServer; + import org.junit.jupiter.api.Test; import static org.hamcrest.CoreMatchers.is; @@ -38,7 +39,7 @@ void stopWhenIdleExpectTimelyStop() { .baseUri("http://localhost:" + webServer.port()) .build(); try (var response = client.get("/ok").request()) { - assertThat(response.status(), is(Http.Status.OK_200)); + assertThat(response.status(), is(Status.OK_200)); assertThat(response.entity().as(String.class), is("ok")); } diff --git a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/XssServerTest.java b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/XssServerTest.java index fe7500affbf..ea7a5a8f6f8 100644 --- a/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/XssServerTest.java +++ b/webserver/tests/webserver/src/test/java/io/helidon/webserver/tests/XssServerTest.java @@ -18,12 +18,12 @@ import java.util.List; -import io.helidon.http.HtmlEncoder; -import io.helidon.http.Http; import io.helidon.common.testing.http.junit5.SocketHttpClient; +import io.helidon.http.HtmlEncoder; +import io.helidon.http.Method; +import io.helidon.webserver.http.HttpRules; import io.helidon.webserver.testing.junit5.ServerTest; import io.helidon.webserver.testing.junit5.SetUpRoute; -import io.helidon.webserver.http.HttpRules; import org.junit.jupiter.api.Test; @@ -46,7 +46,7 @@ static void routing(HttpRules rules) { @Test void testScriptInjection() { - String s = socketHttpClient.sendAndReceive(Http.Method.GET, + String s = socketHttpClient.sendAndReceive(Method.GET, "/bar%3cscript%3eevil%3c%2fscript%3e", null); assertThat(s, not(containsString("", null); assertThat(s, not(containsString(""); - String s = socketHttpClient.sendAndReceive(Http.Method.GET, + String s = socketHttpClient.sendAndReceive(Method.GET, "/foo", null, requestHeaders); @@ -75,7 +75,7 @@ void testScriptInjectionContentType() { @Test void testResponseEncoding() { - String s = socketHttpClient.sendAndReceive(Http.Method.GET, + String s = socketHttpClient.sendAndReceive(Method.GET, "/foo", null); assertThat(s, not(containsString("