From 03daf27f0e188b9d05f0a91013ee5bb07702bbbc Mon Sep 17 00:00:00 2001 From: Tomas Langer Date: Fri, 11 Aug 2023 11:23:50 +0200 Subject: [PATCH] Header and Media type API consistency (#7351) * Rename `Header` to `HeaderNames` * Rename `HeaderValue` to `Header` * Rename `HeaderValues` to `Headers` * Added `from(Headers)` method * HttpMediaTypes now hosts only constants with parameters * Removed Http.Version, as it is no longer needed (it is a String, not an enum) * Fixes in archetypes to use new Header API * Fixes in HTTP template for APT to use new Header API --- .../src/main/archetype/common/media.xml | 2 +- .../test/java/__pkg__/TestCORS.java.mustache | 24 +- .../FileService.java.multipart.mustache | 2 +- common/http/README.md | 49 ++ .../common/http/ClientRequestHeaders.java | 2 +- .../common/http/ClientRequestHeadersImpl.java | 28 +- .../common/http/ClientResponseHeaders.java | 21 +- .../http/ClientResponseHeadersImpl.java | 10 +- .../common/http/ContentDisposition.java | 8 +- .../io/helidon/common/http/CookieParser.java | 4 +- .../io/helidon/common/http/DirectHandler.java | 8 +- .../io/helidon/common/http/Forwarded.java | 4 +- .../{HeaderEnum.java => HeaderNameEnum.java} | 12 +- .../{HeaderImpl.java => HeaderNameImpl.java} | 11 +- .../helidon/common/http/HeaderValueCopy.java | 6 +- .../helidon/common/http/HeaderValueList.java | 7 +- .../java/io/helidon/common/http/Headers.java | 56 +- .../io/helidon/common/http/HeadersImpl.java | 68 ++- .../java/io/helidon/common/http/Http.java | 556 ++++++++++-------- .../common/http/Http1HeadersParser.java | 20 +- .../io/helidon/common/http/HttpMediaType.java | 46 +- .../helidon/common/http/HttpMediaTypes.java | 59 ++ .../helidon/common/http/RequestException.java | 2 +- .../http/RequestedUriDiscoveryContext.java | 16 +- .../common/http/ServerRequestHeaders.java | 58 +- .../common/http/ServerRequestHeadersImpl.java | 10 +- .../common/http/ServerResponseHeaders.java | 52 +- .../http/ServerResponseHeadersImpl.java | 10 +- .../helidon/common/http/WritableHeaders.java | 103 +++- .../helidon/common/http/CookieParserTest.java | 13 +- .../io/helidon/common/http/ForwardedTest.java | 6 +- .../helidon/common/http/HeaderNamesTest.java | 48 +- .../common/http/Http1HeadersParserTest.java | 6 +- .../java/io/helidon/common/http/HttpTest.java | 2 +- .../io/helidon/common/http/MediaTypeTest.java | 12 +- .../http/junit5/HttpHeaderMatcher.java | 12 +- .../testing/http/junit5/SocketHttpClient.java | 2 +- .../io/helidon/cors/CorsSupportHelper.java | 47 +- .../main/java/io/helidon/cors/LogHelper.java | 32 +- .../io/helidon/examples/cors/MainTest.java | 24 +- .../cdi/ObjectStorageResource.java | 4 +- .../objecstorage/ObjectStorageService.java | 4 +- .../examples/media/multipart/FileService.java | 2 +- .../examples/media/multipart/Main.java | 2 +- .../media/multipart/FileServiceTest.java | 2 +- .../se/httpstatuscount/StatusTest.java | 6 +- .../microprofile/examples/cors/TestCORS.java | 41 +- .../examples/nima/echo/EchoClient.java | 8 +- .../helidon/examples/nima/echo/EchoMain.java | 4 +- .../nima/faulttolerance/GreetEndpoint.java | 2 +- .../examples/nima/media/FileService.java | 7 +- .../examples/nima/media/MediaMain.java | 4 +- .../basic/BasicExampleBuilderMain.java | 4 +- .../basic/BasicExampleConfigMain.java | 4 +- .../webserver/basic/BasicExampleTest.java | 2 +- .../examples/google/GoogleBuilderMain.java | 4 +- .../examples/google/GoogleConfigMain.java | 4 +- .../examples/google/GoogleMainTest.java | 2 +- .../examples/idcs/IdcsBuilderMain.java | 4 +- .../security/examples/idcs/IdcsMain.java | 4 +- .../outbound/OutboundOverrideJwtExample.java | 2 +- .../digest/DigestExampleBuilderMain.java | 4 +- .../digest/DigestExampleConfigMain.java | 4 +- .../webserver/digest/DigestExampleTest.java | 2 +- .../WebClientAuthenticationService.java | 4 +- .../examples/signatures/Service1.java | 4 +- .../examples/signatures/Service2.java | 4 +- .../demo/todos/backend/BackendTests.java | 10 +- .../demo/todos/frontend/FrontendTest.java | 11 +- .../webclient/standalone/GreetService.java | 2 +- .../webserver/examples/basics/Main.java | 7 +- .../webserver/examples/basics/MainTest.java | 13 +- .../examples/comments/CommentsService.java | 4 +- .../webserver/examples/comments/Main.java | 2 +- .../comments/CommentsServiceTest.java | 4 +- .../webserver/examples/comments/MainTest.java | 4 +- .../examples/mtls/SecureService.java | 2 +- .../examples/staticcontent/Main.java | 2 +- .../examples/tutorial/CommentService.java | 4 +- .../webserver/examples/tutorial/Main.java | 4 +- .../examples/tutorial/CommentServiceTest.java | 7 +- .../examples/tutorial/UserFilterTest.java | 2 +- .../integrations/common/rest/RestApiBase.java | 2 +- .../MicrometerSimplePrometheusTest.java | 41 +- .../vault/auths/approle/AppRoleRestApi.java | 2 +- .../vault/auths/approle/AppRoleVaultAuth.java | 2 +- .../vault/auths/common/NoVaultAuth.java | 2 +- .../vault/auths/k8s/K8sRestApi.java | 2 +- .../vault/auths/k8s/K8sVaultAuth.java | 2 +- .../vault/auths/token/TokenVaultAuth.java | 4 +- .../jersey/connector/HelidonConnector.java | 4 +- .../client/narayana/NarayanaClient.java | 14 +- .../lra/coordinator/CoordinatorService.java | 8 +- .../java/io/helidon/lra/coordinator/Lra.java | 8 +- .../prometheus/PrometheusSupportTest.java | 4 +- .../microprofile/cors/CorsSupportMp.java | 5 +- .../microprofile/cors/CorsDisabledTest.java | 7 +- .../microprofile/cors/CrossOriginTest.java | 18 +- .../microprofile/cors/ErrorResponseTest.java | 9 +- .../jwt/auth/JwtAuthProvider.java | 8 +- .../microprofile/lra/NonJaxRsResource.java | 10 +- .../lra/CoordinatorHeaderPropagationTest.java | 2 +- .../microprofile/server/JaxRsService.java | 10 +- .../server/ServerCdiExtension.java | 2 +- .../server/ProducedRouteTest.java | 10 +- .../microprofile/tyrus/TyrusUpgrader.java | 8 +- .../nima/graphql/server/GraphQlService.java | 4 +- .../grpc/webserver/GrpcProtocolHandler.java | 6 +- .../grpc/webserver/GrpcProtocolSelector.java | 4 +- .../nima/grpc/webserver/GrpcStatus.java | 46 +- .../encoding/deflate/DeflateEncoding.java | 12 +- .../encoding/ContentEncodingSupportImpl.java | 4 +- .../nima/http/encoding/gzip/GzipEncoding.java | 11 +- .../http/media/jackson/JacksonSupport.java | 4 +- .../http/media/jackson/JacksonWriter.java | 4 +- .../http/media/jackson/JacksonMediaTest.java | 4 +- .../nima/http/media/jsonb/JsonbSupport.java | 4 +- .../nima/http/media/jsonb/JsonbWriter.java | 6 +- .../nima/http/media/jsonb/JsonbMediaTest.java | 4 +- .../nima/http/media/jsonp/JsonpWriter.java | 6 +- .../nima/http/media/jsonp/JsonpMediaTest.java | 4 +- .../nima/http/media/FormParamsSupport.java | 20 +- .../helidon/nima/http/media/PathSupport.java | 4 +- .../nima/http/media/StringSupport.java | 9 +- .../http/media/multipart/MultiPartImpl.java | 6 +- .../http/media/multipart/MultiPartWriter.java | 6 +- .../media/multipart/ReadablePartAbstract.java | 9 +- .../http/media/multipart/WriteablePart.java | 5 +- .../multipart/WriteablePartAbstract.java | 18 +- .../inject/nima/http-method.java.hbs | 2 +- .../io/helidon/nima/http2/Http2Headers.java | 128 ++-- .../helidon/nima/http2/DynamicTableTest.java | 11 +- .../helidon/nima/http2/Http2HeadersTest.java | 20 +- .../http2/webclient/Http2CallChainBase.java | 10 +- .../http2/webclient/Http2CallEntityChain.java | 2 +- .../Http2ClientConnectionHandler.java | 8 +- .../webclient/Http2ClientRequestImpl.java | 6 +- .../http2/webclient/Http2WebClientTest.java | 10 +- .../nima/http2/webserver/Http2Connection.java | 10 +- .../http2/webserver/Http2ServerRequest.java | 4 +- .../http2/webserver/Http2ServerResponse.java | 30 +- .../nima/http2/webserver/Http2Stream.java | 12 +- .../nima/http2/webserver/Http2Upgrader.java | 6 +- .../helidon/nima/observe/log/LogService.java | 9 +- .../nima/observe/metrics/MetricsFeature.java | 4 +- .../java/io/helidon/nima/sse/SseEvent.java | 2 +- .../helidon/nima/sse/webserver/SseSink.java | 2 +- .../benchmark/jmh/Http1ParsingJmhTest.java | 8 +- .../nima/tests/benchmark/jmh/HttpJmhTest.java | 11 +- .../encoding/deflate/DeflateEncodingTest.java | 4 +- .../encoding/gzip/GzipEncodingTest.java | 4 +- .../integration/http2/client/GetTest.java | 19 +- .../integration/http2/client/HeadersTest.java | 10 +- .../http2/client/Http2ClientTest.java | 4 +- .../integration/http2/client/PostTest.java | 13 +- .../integration/http2/webserver/GetTest.java | 12 +- ...ttp2ErrorHandlingWithOutputStreamTest.java | 6 +- .../http2/webserver/Http2ServerTest.java | 6 +- .../integration/http2/webserver/PostTest.java | 14 +- .../integration/media/string/StringTest.java | 14 +- .../observe/health/ObserveHealthTest.java | 28 +- .../sse/webserver/SseClientTest.java | 2 +- .../sse/webserver/SseServerMediaTest.java | 2 +- .../sse/webserver/SseServerTest.java | 5 +- .../integration/webclient/CookieTest.java | 10 +- .../integration/webclient/HeadersTest.java | 10 +- .../http1/ClientRequestImplTest.java | 28 +- .../integration/server/BadRequestTest.java | 6 +- .../server/ConfiguredLimitsTest.java | 6 +- .../server/ContentEncodingContextTest.java | 2 +- ...ntentEncodingDisabledNoValidationTest.java | 2 +- .../server/ContentEncodingDisabledTest.java | 2 +- .../server/Continue100ImmediatelyTest.java | 14 +- .../integration/server/Continue100Test.java | 33 +- .../integration/server/ErrorHandlingTest.java | 12 +- .../ErrorHandlingWithOutputStreamTest.java | 4 +- .../server/FormParamsSupportTest.java | 10 +- .../tests/integration/server/GetTest.java | 48 +- .../integration/server/KeepAliveTest.java | 10 +- .../server/MaxPayloadSizeTest.java | 28 +- .../integration/server/MultiPortTest.java | 5 +- .../tests/integration/server/PostTest.java | 49 +- .../server/ReroutingAndNextingTest.java | 5 +- .../integration/server/RoutingTestBase.java | 9 +- .../server/TransferEncodingTest.java | 15 +- .../integration/server/UriEncodingTest.java | 4 +- .../nima/webclient/api/ClientRequest.java | 6 +- .../nima/webclient/api/ClientRequestBase.java | 8 +- .../api/HttpClientConfigBlueprint.java | 2 +- .../api/HttpClientConfigSupport.java | 65 +- .../io/helidon/nima/webclient/api/Proxy.java | 15 +- .../webclient/api/WebClientCookieManager.java | 18 +- .../nima/webclient/api/HttpClientTest.java | 2 +- .../webclient/http1/Http1CallChainBase.java | 22 +- .../webclient/http1/Http1CallEntityChain.java | 2 +- .../http1/Http1CallOutputStreamChain.java | 18 +- .../http1/Http1ClientRequestImpl.java | 12 +- .../http1/Http1ClientResponseImpl.java | 16 +- .../webclient/http1/Http1ConnectionCache.java | 8 +- .../http1/ClientRequestImplTest.java | 101 ++-- .../webclient/security/WebClientSecurity.java | 2 +- .../webclient/tracing/WebClientTracing.java | 15 +- .../webserver/accesslog/HeaderLogEntry.java | 5 +- .../accesslog/AccessLogFeatureTest.java | 6 +- .../nima/webserver/cors/AbstractCorsTest.java | 25 +- .../helidon/nima/webserver/cors/CorsTest.java | 8 +- .../cors/TestDefaultCorsSupport.java | 13 +- .../cors/TestHandlerRegistration.java | 12 +- .../staticcontent/ByteRangeRequest.java | 12 +- .../staticcontent/CachedHandlerInMemory.java | 8 +- .../staticcontent/CachedHandlerRedirect.java | 4 +- .../ClassPathContentHandler.java | 8 +- .../FileBasedContentHandler.java | 9 +- .../staticcontent/StaticContentHandler.java | 22 +- .../staticcontent/ByteRangeRequestTest.java | 15 +- .../staticcontent/CachedHandlerTest.java | 30 +- .../StaticContentHandlerTest.java | 17 +- .../staticcontent/StaticContentTest.java | 14 +- .../webserver/tracing/TracingFeature.java | 8 +- .../webserver/ListenerConfigBlueprint.java | 4 +- .../nima/webserver/http/DirectHandlers.java | 2 +- .../nima/webserver/http/ErrorHandlers.java | 2 +- .../nima/webserver/http/HttpRequest.java | 8 +- .../nima/webserver/http/ServerResponse.java | 14 +- .../nima/webserver/http1/Http1Connection.java | 32 +- .../webserver/http1/Http1ServerRequest.java | 4 +- .../webserver/http1/Http1ServerResponse.java | 56 +- .../nima/websocket/client/WsClientImpl.java | 17 +- .../nima/websocket/webserver/WsUpgrader.java | 16 +- .../io/helidon/openapi/OpenApiFeature.java | 2 +- .../io/helidon/openapi/OpenApiUiBase.java | 2 +- .../integration/nima/SecurityHandler.java | 6 +- .../WebSecurityBuilderGateDefaultsTest.java | 8 +- .../nima/WebSecurityFromConfigTest.java | 4 +- .../nima/WebSecurityProgrammaticTest.java | 4 +- .../integration/nima/WebSecurityTests.java | 8 +- .../idcs/mapper/IdcsMtRoleMapperProvider.java | 2 +- .../idcs/mapper/IdcsRoleMapperProvider.java | 2 +- .../mapper/IdcsRoleMapperProviderBase.java | 2 +- .../providers/oidc/common/IdcsSupport.java | 4 +- .../providers/oidc/common/Tenant.java | 2 +- .../security/providers/oidc/OidcFeature.java | 8 +- .../oidc/TenantAuthenticationHandler.java | 10 +- .../io/helidon/tests/bookstore/MainTest.java | 8 +- .../requestscope/TenantContext.java | 2 +- .../dbclient/app/tools/ExitService.java | 4 +- .../tests/integration/harness/TestClient.java | 4 +- .../tests/integration/gh3246/Gh3246Test.java | 4 +- .../nativeimage/nima1/WebClientService.java | 6 +- .../integration/webclient/GreetService.java | 10 +- .../tests/integration/webclient/FormTest.java | 3 +- .../integration/webclient/HeaderTest.java | 12 +- .../integration/webclient/MutualTlsTest.java | 2 +- .../upgrade/test/CompressionTest.java | 10 +- .../test/UpgradeCodecsCompositionTest.java | 37 +- 255 files changed, 1962 insertions(+), 1695 deletions(-) create mode 100644 common/http/README.md rename common/http/src/main/java/io/helidon/common/http/{HeaderEnum.java => HeaderNameEnum.java} (92%) rename common/http/src/main/java/io/helidon/common/http/{HeaderImpl.java => HeaderNameImpl.java} (69%) create mode 100644 common/http/src/main/java/io/helidon/common/http/HttpMediaTypes.java diff --git a/archetypes/helidon/src/main/archetype/common/media.xml b/archetypes/helidon/src/main/archetype/common/media.xml index 4b4f0e0aabc..66b98253ab9 100644 --- a/archetypes/helidon/src/main/archetype/common/media.xml +++ b/archetypes/helidon/src/main/archetype/common/media.xml @@ -180,7 +180,7 @@ { res.status(Http.Status.MOVED_PERMANENTLY_301); - res.header(Header.createCached(Header.LOCATION, "/ui")); + res.header(Http.Headers.createCached(Http.HeaderNames.LOCATION, "/ui")); res.send(); }) .register("/ui", StaticContentService.builder("WEB") 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 a625be7211f..3a7d165a909 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 @@ -29,15 +29,15 @@ class TestCORS { void testAnonymousGreetWithCors() { Response r = target.path("/simple-greet") .request() - .header(Http.Header.ORIGIN.defaultCase(), "http://foo.com") - .header(Http.Header.HOST.defaultCase(), "here.com") + .header(Http.HeaderNames.ORIGIN.defaultCase(), "http://foo.com") + .header(Http.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.Header.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()), + r.getHeaders().getFirst(Http.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.Header.ORIGIN.defaultCase(), "http://foo.com") - .header(Http.Header.HOST.defaultCase(), "here.com") + .header(Http.HeaderNames.ORIGIN.defaultCase(), "http://foo.com") + .header(Http.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.Header.ACCESS_CONTROL_ALLOW_METHODS.defaultCase()), + r.getHeaders().getFirst(Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS.defaultCase()), is("PUT")); assertThat( "Header " + CrossOriginConfig.ACCESS_CONTROL_ALLOW_ORIGIN, - r.getHeaders().getFirst(Http.Header.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()), + r.getHeaders().getFirst(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()), is("http://foo.com")); Invocation.Builder builder = target.path("/simple-greet") .request() .headers(responseHeaders) - .header(Http.Header.ORIGIN.defaultCase(), "http://foo.com") - .header(Http.Header.HOST.defaultCase(), "here.com"); + .header(Http.HeaderNames.ORIGIN.defaultCase(), "http://foo.com") + .header(Http.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.Header.ACCESS_CONTROL_ALLOW_ORIGIN.defaultCase()), + r.getHeaders().getFirst(Http.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.Header.ORIGIN.defaultCase(), "http://other.com") - .header(Http.Header.HOST.defaultCase(), "here.com"); + .header(Http.HeaderNames.ORIGIN.defaultCase(), "http://other.com") + .header(Http.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/nima/custom/files/src/main/java/__pkg__/FileService.java.multipart.mustache b/archetypes/helidon/src/main/archetype/nima/custom/files/src/main/java/__pkg__/FileService.java.multipart.mustache index 5698c020523..6775dbc694c 100644 --- a/archetypes/helidon/src/main/archetype/nima/custom/files/src/main/java/__pkg__/FileService.java.multipart.mustache +++ b/archetypes/helidon/src/main/archetype/nima/custom/files/src/main/java/__pkg__/FileService.java.multipart.mustache @@ -33,7 +33,7 @@ import static io.helidon.common.http.Http.Status.NOT_FOUND_404; * File service. */ final class FileService implements HttpService { - private static final Http.HeaderValue UI_LOCATION = Header.createCached(Header.LOCATION, "/ui"); + private static final Http.Header UI_LOCATION = Http.Headers.createCached(Http.HeaderNames.LOCATION, "/ui"); private final JsonBuilderFactory jsonFactory; private final Path storage; diff --git a/common/http/README.md b/common/http/README.md new file mode 100644 index 00000000000..f0f1dfa85ae --- /dev/null +++ b/common/http/README.md @@ -0,0 +1,49 @@ +HTTP +---- + +# HTTP Header name and value + +Abstraction of a single header name (`Connection`), or a header value (`Connection: keep-alive`). + + +## Types + +- `Http.HeaderName` - abstraction of a name of a header (such as `Content-Length`) +- `Http.HeaderNames` - constants with "known" header names (such as `HeaderNames.CONTENT_LENGTH`) +- `Http.Header` - abstraction of a header with a value (such as `Content-Length: 0`) +- `Http.Headers` - constants with commonly used headers with values (such as `Headers.CONTENT_LENGTH_ZERO`) + +Internal types: +- `Http.HeaderNameEnum` - "known" headers, optimized for performance in header containers +- `Http.HeaderNameImpl` - custom headers + +## Factory methods + +Factory methods to create header names and values are located on their relevant type that contains constants (aligned + with how we treat `MediaTypes`: + +Header names: +1. `Http.HeaderNames.create(String)` - create a header name from the provided name (uses known header if possible) +2. `Http.HeaderNames.create(String, String)` - create a header name (optimized) with lower case and name +3. `Http.HeaderNames.createFromLowercase(String)` - create a header name when we have a guaranteed lowercase name (such as in HTTP/2) + +Headers (name and value): +1. `Http.Headers.create(....)` - create a header with the provided name and value +2. `Http.Headers.createCached(...)` - create a header that caches its HTTP/1.1 bytes (optimization for heavily used headers) + +Methods with `changing` and `sensitive` - these options are used for HTTP/2 (and HTTP/3) to correctly cache names/values when talking over the network + +# HTTP Header containers + +Abstraction of a collection of headers, as used in server and client requests and responses. +The containers are optimized for read and write speed by using an array for "known" headers (Headers that are part of our +`HeaderNameEnum`). Other headers are stored in a map, keyed by `HeaderName`. + +## Types + +- `Headers` - a collection of HTTP headers that is read-only +- `WritableHeader` - a collection of HTTP headers that is mutable +- `ClientRequestHeaders` - writable headers to create client request +- `ClientResponseHeaders` - read-only headers with response from the server +- `ServerRequestHeaders` - read-only headers with request from client +- `ServerResponseHeaders` - writable header to create server response diff --git a/common/http/src/main/java/io/helidon/common/http/ClientRequestHeaders.java b/common/http/src/main/java/io/helidon/common/http/ClientRequestHeaders.java index 29b1fbd1067..a9cf5306918 100644 --- a/common/http/src/main/java/io/helidon/common/http/ClientRequestHeaders.java +++ b/common/http/src/main/java/io/helidon/common/http/ClientRequestHeaders.java @@ -56,7 +56,7 @@ default ClientRequestHeaders accept(MediaType... accepted) { MediaType mediaType = accepted[i]; values[i] = mediaType.text(); } - set(Http.Header.create(Http.Header.ACCEPT, values)); + set(Http.Headers.create(Http.HeaderNames.ACCEPT, values)); return this; } } diff --git a/common/http/src/main/java/io/helidon/common/http/ClientRequestHeadersImpl.java b/common/http/src/main/java/io/helidon/common/http/ClientRequestHeadersImpl.java index 655cceef71c..8b7ec911027 100644 --- a/common/http/src/main/java/io/helidon/common/http/ClientRequestHeadersImpl.java +++ b/common/http/src/main/java/io/helidon/common/http/ClientRequestHeadersImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -23,9 +23,7 @@ import java.util.function.Consumer; import java.util.function.Supplier; -import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; /** * Client request headers. @@ -50,12 +48,12 @@ public boolean contains(HeaderName name) { } @Override - public boolean contains(HeaderValue headerWithValue) { + public boolean contains(Http.Header headerWithValue) { return delegate.contains(headerWithValue); } @Override - public HeaderValue get(HeaderName name) { + public Http.Header get(HeaderName name) { return delegate.get(name); } @@ -67,8 +65,8 @@ public int size() { @Override public List acceptedTypes() { if (mediaTypes == null) { - if (delegate.contains(Header.ACCEPT)) { - List accepts = delegate.get(Header.ACCEPT).allValues(true); + if (delegate.contains(Http.HeaderNames.ACCEPT)) { + List accepts = delegate.get(Http.HeaderNames.ACCEPT).allValues(true); List mediaTypes = new ArrayList<>(accepts.size()); for (String accept : accepts) { @@ -85,13 +83,13 @@ public List acceptedTypes() { } @Override - public ClientRequestHeaders setIfAbsent(HeaderValue header) { + public ClientRequestHeaders setIfAbsent(Http.Header header) { delegate.setIfAbsent(header); return this; } @Override - public ClientRequestHeaders add(HeaderValue header) { + public ClientRequestHeaders add(Http.Header header) { delegate.add(header); return this; } @@ -103,19 +101,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(HeaderValue header) { + public ClientRequestHeaders set(Http.Header header) { delegate.set(header); return this; } @Override - public Iterator iterator() { + public Iterator iterator() { return delegate.iterator(); } @@ -129,4 +127,10 @@ public ClientRequestHeaders clear() { delegate.clear(); return this; } + + @Override + public ClientRequestHeaders from(Headers headers) { + headers.forEach(this::set); + return this; + } } diff --git a/common/http/src/main/java/io/helidon/common/http/ClientResponseHeaders.java b/common/http/src/main/java/io/helidon/common/http/ClientResponseHeaders.java index bdc6b99a58e..0dff36cd2c1 100644 --- a/common/http/src/main/java/io/helidon/common/http/ClientResponseHeaders.java +++ b/common/http/src/main/java/io/helidon/common/http/ClientResponseHeaders.java @@ -23,13 +23,12 @@ import java.util.Optional; import io.helidon.common.http.Http.DateTime; -import io.helidon.common.http.Http.HeaderValue; import io.helidon.common.media.type.ParserMode; -import static io.helidon.common.http.Http.Header.ACCEPT_PATCH; -import static io.helidon.common.http.Http.Header.EXPIRES; -import static io.helidon.common.http.Http.Header.LAST_MODIFIED; -import static io.helidon.common.http.Http.Header.LOCATION; +import static io.helidon.common.http.Http.HeaderNames.ACCEPT_PATCH; +import static io.helidon.common.http.Http.HeaderNames.EXPIRES; +import static io.helidon.common.http.Http.HeaderNames.LAST_MODIFIED; +import static io.helidon.common.http.Http.HeaderNames.LOCATION; /** * HTTP Headers of a client response. @@ -72,7 +71,7 @@ default List acceptPatches() { } /** - * Optionally gets the value of {@link io.helidon.common.http.Http.Header#LOCATION} header. + * Optionally gets the value of {@link io.helidon.common.http.Http.HeaderNames#LOCATION} header. *

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

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

* Gives the date/time after which the response is considered stale. * @@ -113,7 +112,7 @@ default Optional lastModified() { default Optional expires() { if (contains(EXPIRES)) { return Optional.of(get(EXPIRES)) - .map(HeaderValue::value) + .map(Http.Header::value) .map(DateTime::parse); } return Optional.empty(); diff --git a/common/http/src/main/java/io/helidon/common/http/ClientResponseHeadersImpl.java b/common/http/src/main/java/io/helidon/common/http/ClientResponseHeadersImpl.java index 82e1a882bdc..776f903532c 100644 --- a/common/http/src/main/java/io/helidon/common/http/ClientResponseHeadersImpl.java +++ b/common/http/src/main/java/io/helidon/common/http/ClientResponseHeadersImpl.java @@ -43,20 +43,20 @@ public boolean contains(Http.HeaderName name) { } @Override - public boolean contains(Http.HeaderValue headerWithValue) { + public boolean contains(Http.Header headerWithValue) { return headers.contains(headerWithValue); } @Override - public Http.HeaderValue get(Http.HeaderName name) { + public Http.Header get(Http.HeaderName name) { return headers.get(name); } @Override public Optional contentType() { if (parserMode == ParserMode.RELAXED) { - return contains(HeaderEnum.CONTENT_TYPE) - ? Optional.of(HttpMediaType.create(get(HeaderEnum.CONTENT_TYPE).value(), parserMode)) + return contains(HeaderNameEnum.CONTENT_TYPE) + ? Optional.of(HttpMediaType.create(get(HeaderNameEnum.CONTENT_TYPE).value(), parserMode)) : Optional.empty(); } return headers.contentType(); @@ -68,7 +68,7 @@ public int size() { } @Override - public Iterator iterator() { + public Iterator iterator() { return headers.iterator(); } diff --git a/common/http/src/main/java/io/helidon/common/http/ContentDisposition.java b/common/http/src/main/java/io/helidon/common/http/ContentDisposition.java index 68908150c48..fe5f95fc55a 100644 --- a/common/http/src/main/java/io/helidon/common/http/ContentDisposition.java +++ b/common/http/src/main/java/io/helidon/common/http/ContentDisposition.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -47,7 +47,7 @@ * * */ -public class ContentDisposition implements Http.HeaderValue { +public class ContentDisposition implements Http.Header { private static final String NAME_PARAMETER = "name"; private static final String FILENAME_PARAMETER = "filename"; private static final String CREATION_DATE_PARAMETER = "creation-date"; @@ -126,12 +126,12 @@ public static ContentDisposition empty() { @Override public String name() { - return Http.Header.CONTENT_DISPOSITION.defaultCase(); + return Http.HeaderNames.CONTENT_DISPOSITION.defaultCase(); } @Override public Http.HeaderName headerName() { - return Http.Header.CONTENT_DISPOSITION; + return Http.HeaderNames.CONTENT_DISPOSITION; } @Override diff --git a/common/http/src/main/java/io/helidon/common/http/CookieParser.java b/common/http/src/main/java/io/helidon/common/http/CookieParser.java index 85fe7668dd9..0d95befe5b3 100644 --- a/common/http/src/main/java/io/helidon/common/http/CookieParser.java +++ b/common/http/src/main/java/io/helidon/common/http/CookieParser.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -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.HeaderValue httpHeader) { + static Parameters parse(Http.Header httpHeader) { Map> allCookies = new HashMap<>(); for (String value : httpHeader.allValues()) { parse(allCookies, value); diff --git a/common/http/src/main/java/io/helidon/common/http/DirectHandler.java b/common/http/src/main/java/io/helidon/common/http/DirectHandler.java index c0a4f7d423c..9ce4bffc56d 100644 --- a/common/http/src/main/java/io/helidon/common/http/DirectHandler.java +++ b/common/http/src/main/java/io/helidon/common/http/DirectHandler.java @@ -337,7 +337,7 @@ public Builder header(Http.HeaderName name, String... values) { * @param header header value * @return updated builder */ - public Builder header(Http.HeaderValue header) { + public Builder header(Http.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.HeaderValues.CONTENT_TYPE_TEXT_PLAIN); + this.headers.setIfAbsent(Http.Headers.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.Header.CONTENT_LENGTH); + this.headers.remove(Http.HeaderNames.CONTENT_LENGTH); } else { - header(Http.Header.CONTENT_LENGTH, String.valueOf(entity.length)); + header(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(entity.length)); } return this; } diff --git a/common/http/src/main/java/io/helidon/common/http/Forwarded.java b/common/http/src/main/java/io/helidon/common/http/Forwarded.java index 5a6a93fc936..bf4b04ea310 100644 --- a/common/http/src/main/java/io/helidon/common/http/Forwarded.java +++ b/common/http/src/main/java/io/helidon/common/http/Forwarded.java @@ -21,10 +21,10 @@ import java.util.Locale; import java.util.Optional; -import static io.helidon.common.http.Http.Header.FORWARDED; +import static io.helidon.common.http.Http.HeaderNames.FORWARDED; /** - * A representation of the {@link Http.Header#FORWARDED} HTTP header. + * A representation of the {@link io.helidon.common.http.Http.HeaderNames#FORWARDED} HTTP header. */ public class Forwarded { private static final System.Logger LOGGER = System.getLogger(Forwarded.class.getName()); diff --git a/common/http/src/main/java/io/helidon/common/http/HeaderEnum.java b/common/http/src/main/java/io/helidon/common/http/HeaderNameEnum.java similarity index 92% rename from common/http/src/main/java/io/helidon/common/http/HeaderEnum.java rename to common/http/src/main/java/io/helidon/common/http/HeaderNameEnum.java index fdbd289be23..260294d07e6 100644 --- a/common/http/src/main/java/io/helidon/common/http/HeaderEnum.java +++ b/common/http/src/main/java/io/helidon/common/http/HeaderNameEnum.java @@ -21,7 +21,11 @@ import io.helidon.common.buffers.Ascii; -enum HeaderEnum implements Http.HeaderName { +/* + * 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 { ACCEPT("Accept"), ACCEPT_CHARSET("Accept-Charset"), ACCEPT_ENCODING("Accept-Encoding"), @@ -40,7 +44,7 @@ enum HeaderEnum implements Http.HeaderName { EXPECT("Expect"), FORWARDED("Forwarded"), FROM("From"), - HOST(Http.Header.HOST_STRING), + HOST(Http.HeaderNames.HOST_STRING), IF_MATCH("If-Match"), IF_MODIFIED_SINCE("If-Modified-Since"), IF_NONE_MATCH("If-None-Match"), @@ -103,7 +107,7 @@ enum HeaderEnum implements Http.HeaderName { static { Map byName = new HashMap<>(); Map byCapName = new HashMap<>(); - for (HeaderEnum value : HeaderEnum.values()) { + for (HeaderNameEnum value : HeaderNameEnum.values()) { byName.put(value.lowerCase(), value); byCapName.put(value.defaultCase(), value); } @@ -115,7 +119,7 @@ enum HeaderEnum implements Http.HeaderName { private final String http1Case; private final int index; - HeaderEnum(String http1Case) { + HeaderNameEnum(String http1Case) { this.http1Case = http1Case; this.lowerCase = this.http1Case.toLowerCase(); this.index = this.ordinal(); diff --git a/common/http/src/main/java/io/helidon/common/http/HeaderImpl.java b/common/http/src/main/java/io/helidon/common/http/HeaderNameImpl.java similarity index 69% rename from common/http/src/main/java/io/helidon/common/http/HeaderImpl.java rename to common/http/src/main/java/io/helidon/common/http/HeaderNameImpl.java index 9aa98e74a00..153f60b4df6 100644 --- a/common/http/src/main/java/io/helidon/common/http/HeaderImpl.java +++ b/common/http/src/main/java/io/helidon/common/http/HeaderNameImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -18,17 +18,22 @@ import java.util.Objects; -record HeaderImpl(String lowerCase, String defaultCase) implements Http.HeaderName { +record HeaderNameImpl(String lowerCase, String defaultCase) implements Http.HeaderName { @Override public boolean equals(Object obj) { if (obj == this) { return true; } + /* + A Http.HeaderName can only be HeaderNameImpl, or HeaderNameEnum. + If you attempt to create a new name that is already an enum, you should get that enum, so we only have to + care about HeaderNameImpl here + */ if (obj == null || obj.getClass() != this.getClass()) { return false; } - var that = (HeaderImpl) obj; + var that = (HeaderNameImpl) obj; return this.lowerCase.equals(that.lowerCase); } diff --git a/common/http/src/main/java/io/helidon/common/http/HeaderValueCopy.java b/common/http/src/main/java/io/helidon/common/http/HeaderValueCopy.java index 7e1f987e787..fcde92aba87 100644 --- a/common/http/src/main/java/io/helidon/common/http/HeaderValueCopy.java +++ b/common/http/src/main/java/io/helidon/common/http/HeaderValueCopy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -20,10 +20,10 @@ import java.util.List; class HeaderValueCopy extends HeaderValueBase { - private final Http.HeaderValue original; + private final Http.Header original; private List values; - HeaderValueCopy(Http.HeaderValue header) { + HeaderValueCopy(Http.Header header) { super(header.headerName(), header.changing(), header.sensitive(), header.value()); this.original = header; diff --git a/common/http/src/main/java/io/helidon/common/http/HeaderValueList.java b/common/http/src/main/java/io/helidon/common/http/HeaderValueList.java index f360648039e..a0a98e44c4f 100644 --- a/common/http/src/main/java/io/helidon/common/http/HeaderValueList.java +++ b/common/http/src/main/java/io/helidon/common/http/HeaderValueList.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -17,13 +17,14 @@ package io.helidon.common.http; import java.util.ArrayList; +import java.util.Collection; import java.util.List; class HeaderValueList extends HeaderValueBase { private List values; - HeaderValueList(Http.HeaderName name, boolean changing, boolean sensitive, List values) { - super(name, changing, sensitive, values.get(0)); + HeaderValueList(Http.HeaderName name, boolean changing, boolean sensitive, Collection values) { + super(name, changing, sensitive, values.iterator().next()); this.values = new ArrayList<>(values); } diff --git a/common/http/src/main/java/io/helidon/common/http/Headers.java b/common/http/src/main/java/io/helidon/common/http/Headers.java index 4f918d43d95..f4f32a496af 100644 --- a/common/http/src/main/java/io/helidon/common/http/Headers.java +++ b/common/http/src/main/java/io/helidon/common/http/Headers.java @@ -35,32 +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.common.http.Http.HeaderValue#name()}) + * When you receive headers, the stored values (as can be obtained by {@link io.helidon.common.http.Http.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 { - - /** - * Returns an unmodifiable {@link java.util.List} of all header fields - each element represents a value of a single header - * field - * in the request. Consider to use {@link #value(io.helidon.common.http.Http.HeaderName)} - * or {@link #all(io.helidon.common.http.Http.HeaderName, java.util.function.Supplier)} method instead. - *

- * Always returns a List, which may be empty if the parameter is not present. - * - * @param headerName the header name - * @return a {@code List} of values with zero or greater size - * @throws NullPointerException if {@code headerName} is {@code null} - * @see #value(io.helidon.common.http.Http.HeaderName) - * @see #values(io.helidon.common.http.Http.HeaderName) - * @deprecated use {@link #all(io.helidon.common.http.Http.HeaderName, java.util.function.Supplier)} instead - */ - @Deprecated(forRemoval = true) - default List all(String headerName) { - return all(Http.Header.create(headerName), List::of); - } - +public interface Headers extends Iterable { /** * Get all values of a header. * @@ -84,7 +63,7 @@ default List all(String headerName) { * @param value value of the header * @return {@code true} if the header is defined */ - boolean contains(Http.HeaderValue value); + boolean contains(Http.Header value); /** * Get a header value. @@ -93,13 +72,13 @@ default List all(String headerName) { * @return value if present * @throws java.util.NoSuchElementException in case the header is not present */ - Http.HeaderValue get(Http.HeaderName name); + Http.Header get(Http.HeaderName name); /** * Returns a header value as a single {@link String} potentially concatenated using comma character - * from {@link #all(String) all} header fields. + * from {@link #all(io.helidon.common.http.Http.HeaderName, java.util.function.Supplier)} header fields. *

- * Accordingly to RFC2616, Message Headers: + * According to RFC2616, Message Headers: *

* Multiple message-header fields with the same field-name MAY be * present in a message if and only if the entire field-value for that @@ -146,16 +125,17 @@ default Optional first(Http.HeaderName headerName) { * Result is composed from all header fields with requested {@code headerName} where each header value is tokenized by * a comma character. Tokenization respects value quoting by double-quote character. *

- * Always returns a List, which may be empty if the parameter is not present. + * Always returns a List, which may be empty if the header is not present. * * @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(String) + * @see #all(io.helidon.common.http.Http.HeaderName, java.util.function.Supplier) * @see #value(io.helidon.common.http.Http.HeaderName) */ default List values(Http.HeaderName headerName) { - return all(headerName, List::of).stream() + return all(headerName, List::of) + .stream() .flatMap(val -> Utils.tokenize(',', "\"", true, val).stream()) .collect(Collectors.toList()); } @@ -164,11 +144,11 @@ default List values(Http.HeaderName headerName) { * Content length if defined. * * @return content length or empty if not defined - * @see io.helidon.common.http.Http.Header#CONTENT_LENGTH + * @see io.helidon.common.http.Http.HeaderNames#CONTENT_LENGTH */ default OptionalLong contentLength() { - if (contains(HeaderEnum.CONTENT_LENGTH)) { - return OptionalLong.of(get(HeaderEnum.CONTENT_LENGTH).value(long.class)); + if (contains(HeaderNameEnum.CONTENT_LENGTH)) { + return OptionalLong.of(get(HeaderNameEnum.CONTENT_LENGTH).value(long.class)); } return OptionalLong.empty(); } @@ -177,11 +157,11 @@ default OptionalLong contentLength() { * Content type (if defined). * * @return content type, empty if content type is not present - * @see io.helidon.common.http.Http.Header#CONTENT_TYPE + * @see io.helidon.common.http.Http.HeaderNames#CONTENT_TYPE */ default Optional contentType() { - if (contains(HeaderEnum.CONTENT_TYPE)) { - return Optional.of(HttpMediaType.create(get(HeaderEnum.CONTENT_TYPE) + if (contains(HeaderNameEnum.CONTENT_TYPE)) { + return Optional.of(HttpMediaType.create(get(HeaderNameEnum.CONTENT_TYPE) .value())); } return Optional.empty(); @@ -195,7 +175,7 @@ default Optional contentType() { int size(); /** - * Returns a list of acceptedTypes ({@link io.helidon.common.http.Http.Header#ACCEPT} header) content discoveryTypes in + * Returns a list of acceptedTypes ({@link io.helidon.common.http.Http.HeaderNames#ACCEPT} header) content discoveryTypes in * quality factor order. Never {@code null}. * Returns an empty list by default. * @@ -235,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/common/http/src/main/java/io/helidon/common/http/HeadersImpl.java b/common/http/src/main/java/io/helidon/common/http/HeadersImpl.java index 6b123f4e586..70d11a9a2f2 100644 --- a/common/http/src/main/java/io/helidon/common/http/HeadersImpl.java +++ b/common/http/src/main/java/io/helidon/common/http/HeadersImpl.java @@ -27,33 +27,33 @@ import java.util.function.Consumer; import java.util.function.Supplier; +import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; import io.helidon.common.http.Http.HeaderValueWriteable; @SuppressWarnings("unchecked") class HeadersImpl> implements WritableHeaders { - static final int KNOWN_HEADER_SIZE = HeaderEnum.values().length; + static final int KNOWN_HEADER_SIZE = HeaderNameEnum.values().length; /* Optimization for most commonly used header names */ - private final HeaderValue[] knownHeaders = new HeaderValue[KNOWN_HEADER_SIZE]; + private final Header[] knownHeaders = new Http.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() { } HeadersImpl(Headers headers) { - for (HeaderValue header : headers) { + for (Header header : headers) { set(header); } } @Override public List all(HeaderName name, Supplier> defaultSupplier) { - HeaderValue headerValue = find(name); + Header headerValue = find(name); if (headerValue == null) { return defaultSupplier.get(); } @@ -66,8 +66,8 @@ public boolean contains(HeaderName name) { } @Override - public boolean contains(HeaderValue headerWithValue) { - HeaderValue headerValue = find(headerWithValue.headerName()); + public boolean contains(Http.Header headerWithValue) { + Http.Header headerValue = find(headerWithValue.headerName()); if (headerValue == null) { return false; } @@ -79,8 +79,8 @@ public boolean contains(HeaderValue headerWithValue) { } @Override - public HeaderValue get(HeaderName name) { - HeaderValue headerValue = find(name); + public Http.Header get(HeaderName name) { + Header headerValue = find(name); if (headerValue == null) { throw new NoSuchElementException("Header " + name + " is not present in these headers"); } @@ -94,8 +94,8 @@ public int size() { @Override public List acceptedTypes() { - if (contains(Http.Header.ACCEPT)) { - List accepts = get(Http.Header.ACCEPT).allValues(true); + if (contains(Http.HeaderNames.ACCEPT)) { + List accepts = get(Http.HeaderNames.ACCEPT).allValues(true); List mediaTypes = new ArrayList<>(accepts.size()); for (String accept : accepts) { @@ -109,13 +109,13 @@ public List acceptedTypes() { } @Override - public Iterator iterator() { + public Iterator iterator() { return new HeaderIterator(); } @Override - public T setIfAbsent(HeaderValue header) { - HeaderValue found = find(header.headerName()); + public T setIfAbsent(Header header) { + Http.Header found = find(header.headerName()); if (found == null) { set(header); } @@ -124,9 +124,9 @@ public T setIfAbsent(HeaderValue header) { } @Override - public T add(HeaderValue header) { + public T add(Header header) { HeaderName name = header.headerName(); - HeaderValue headerValue = find(name); + Http.Header headerValue = find(name); if (headerValue == null) { set(header); } else { @@ -152,8 +152,8 @@ public T remove(HeaderName name) { } @Override - public T remove(HeaderName name, Consumer removedConsumer) { - HeaderValue remove = doRemove(name); + public T remove(HeaderName name, Consumer removedConsumer) { + Http.Header remove = doRemove(name); if (remove != null) { removedConsumer.accept(remove); } @@ -161,10 +161,10 @@ public T remove(HeaderName name, Consumer removedConsumer) { } @Override - public T set(HeaderValue header) { + public T set(Http.Header header) { HeaderName name = header.headerName(); - HeaderValue usedHeader = header; + Header usedHeader = header; if (header instanceof HeaderValueWriteable) { // we must create a new instance, as we risk modifying state of the provided header usedHeader = new HeaderValueCopy(header); @@ -187,11 +187,19 @@ public T clear() { return (T) this; } + @Override + public T from(Headers headers) { + for (Header header : headers) { + set(header); + } + return (T) this; + } + @Override public String toString() { StringBuilder builder = new StringBuilder(); - for (HeaderValue headerValue : this) { + for (Http.Header headerValue : this) { for (String value : headerValue.allValues()) { builder.append(headerValue.name()) .append(": "); @@ -219,17 +227,17 @@ public String toString() { return builder.toString(); } - public HeaderValue doRemove(HeaderName name) { - if (name instanceof HeaderEnum) { - int index = ((HeaderEnum) name).ordinal(); - HeaderValue value = knownHeaders[index]; + public Header doRemove(HeaderName name) { + if (name instanceof HeaderNameEnum) { + int index = ((HeaderNameEnum) name).ordinal(); + Http.Header value = knownHeaders[index]; knownHeaders[index] = null; knownHeaderIndices.remove(index); return value; } return customHeaders.remove(name); } - private HeaderValue find(HeaderName name) { + private Header find(HeaderName name) { int index = name.index(); if (index > -1) { @@ -239,12 +247,12 @@ private HeaderValue find(HeaderName name) { return customHeaders.get(name); } - private class HeaderIterator implements Iterator { + private class HeaderIterator implements Iterator

{ private final boolean noCustom = customHeaders.isEmpty(); private boolean inKnown = true; private int last = -1; - private Iterator customHeadersIterator; + private Iterator
customHeadersIterator; @Override public boolean hasNext() { @@ -264,7 +272,7 @@ public boolean hasNext() { } @Override - public HeaderValue next() { + public Header next() { if (last >= 0) { return knownHeaders[last]; } diff --git a/common/http/src/main/java/io/helidon/common/http/Http.java b/common/http/src/main/java/io/helidon/common/http/Http.java index c5e56e62c5f..9200357d97d 100644 --- a/common/http/src/main/java/io/helidon/common/http/Http.java +++ b/common/http/src/main/java/io/helidon/common/http/Http.java @@ -55,60 +55,6 @@ public final class Http { private Http() { } - /** - * Enumeration of supported HTTP protocol versions. - */ - public enum Version { - - /** - * HTTP version {@code HTTP/1.0}. - */ - V1_0("HTTP/1.0"), - - /** - * HTTP version {@code HTTP/1.1}. - */ - V1_1("HTTP/1.1"), - - /** - * HTTP version {@code HTTP/2.0}. - */ - V2_0("HTTP/2.0"); - - private final String value; - - Version(String value) { - this.value = value; - } - - /** - * Returns HTTP version for provided parameter. - * - * @param version HTTP version. - * @return Version instance. - * @throws NullPointerException if parameter {@code version} is null. - * @throws IllegalArgumentException if it is not provided version. - */ - public static Version create(String version) { - Objects.requireNonNull(version, "Version value is null!"); - for (Version v : Version.values()) { - if (version.equals(v.value)) { - return v; - } - } - throw new IllegalArgumentException("Unknown HTTP version: " + version + "!"); - } - - /** - * Returns {@code String} representation of this {@link io.helidon.common.http.Http.Version}. - * - * @return a string representation. - */ - public String value() { - return value; - } - } - /** * Interface representing an HTTP request method, all standard methods are in {@link io.helidon.common.http.Http.Method} * enumeration. @@ -802,7 +748,7 @@ public static Family of(int statusCode) { /** * HTTP header name. */ - public sealed interface HeaderName permits HeaderImpl, HeaderEnum { + 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 @@ -842,9 +788,9 @@ default boolean isPseudoHeader() { /** * HTTP Header with {@link io.helidon.common.http.Http.HeaderName} and value. * - * @see io.helidon.common.http.Http.HeaderValues + * @see io.helidon.common.http.Http.Headers */ - public interface HeaderValue { + public interface Header { /** * Name of the header as configured by user @@ -1015,14 +961,14 @@ private void writeHeader(BufferData buffer, byte[] nameBytes, byte[] valueBytes) /** * Mutable header value. */ - public interface HeaderValueWriteable extends HeaderValue { + 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(HeaderValue header) { + static HeaderValueWriteable create(Header header) { return new HeaderValueCopy(header); } @@ -1038,104 +984,103 @@ static HeaderValueWriteable create(HeaderValue header) { /** * Utility class with a list of names of standard HTTP headers and related tooling methods. */ - @SuppressWarnings({"WeakerAccess", "unused"}) - public static final class Header { + public static final class HeaderNames { /** * The {@code Accept} header name. * Content-Types that are acceptedTypes for the response. */ - public static final HeaderName ACCEPT = HeaderEnum.ACCEPT; + public static final HeaderName ACCEPT = HeaderNameEnum.ACCEPT; /** * The {@code Accept-Charset} header name. * Character sets that are acceptedTypes. */ - public static final HeaderName ACCEPT_CHARSET = HeaderEnum.ACCEPT_CHARSET; + 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 = HeaderEnum.ACCEPT_ENCODING; + 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 = HeaderEnum.ACCEPT_LANGUAGE; + 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 = HeaderEnum.ACCEPT_DATETIME; + 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 = HeaderEnum.ACCESS_CONTROL_ALLOW_CREDENTIALS; + 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 = HeaderEnum.ACCESS_CONTROL_ALLOW_HEADERS; + 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 = HeaderEnum.ACCESS_CONTROL_ALLOW_METHODS; + 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 = HeaderEnum.ACCESS_CONTROL_ALLOW_ORIGIN; + 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 = HeaderEnum.ACCESS_CONTROL_EXPOSE_HEADERS; + 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 = HeaderEnum.ACCESS_CONTROL_MAX_AGE; + 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 = HeaderEnum.ACCESS_CONTROL_REQUEST_HEADERS; + 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 = HeaderEnum.ACCESS_CONTROL_REQUEST_METHOD; + 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 = HeaderEnum.AUTHORIZATION; + 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 = HeaderEnum.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 = HeaderEnum.EXPECT; + 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 = HeaderEnum.FORWARDED; + 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 = HeaderEnum.FROM; + 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 = HeaderEnum.HOST; + public static final HeaderName HOST = HeaderNameEnum.HOST; /** * The {@value} header. * @@ -1147,53 +1092,53 @@ public static final class Header { * 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 = HeaderEnum.IF_MATCH; + 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 = HeaderEnum.IF_MODIFIED_SINCE; + 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 = HeaderEnum.IF_NONE_MATCH; + 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 = HeaderEnum.IF_RANGE; + 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 = HeaderEnum.IF_UNMODIFIED_SINCE; + 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 = HeaderEnum.MAX_FORWARDS; + 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 = HeaderEnum.ORIGIN; + public static final HeaderName ORIGIN = HeaderNameEnum.ORIGIN; /** * The {@code Proxy-Authenticate} header name. * Proxy authentication information. */ - public static final HeaderName PROXY_AUTHENTICATE = HeaderEnum.PROXY_AUTHENTICATE; + public static final HeaderName PROXY_AUTHENTICATE = HeaderNameEnum.PROXY_AUTHENTICATE; /** * The {@code Proxy-Authorization} header name. * Proxy authorization information. */ - public static final HeaderName PROXY_AUTHORIZATION = HeaderEnum.PROXY_AUTHORIZATION; + 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 = HeaderEnum.RANGE; + 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. @@ -1201,11 +1146,11 @@ public static final class Header { * {@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 = HeaderEnum.REFERER; + public static final HeaderName REFERER = HeaderNameEnum.REFERER; /** * The {@code {@value}} header name. */ - public static final HeaderName REFRESH = HeaderEnum.REFRESH; + 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 @@ -1213,216 +1158,216 @@ public static final class Header { * {@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 = HeaderEnum.TE; + 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 = HeaderEnum.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 = HeaderEnum.VIA; + 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 = HeaderEnum.ACCEPT_PATCH; + 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 = HeaderEnum.ACCEPT_RANGES; + 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 = HeaderEnum.AGE; + 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 = HeaderEnum.ALLOW; + 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 = HeaderEnum.ALT_SVC; + 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 = HeaderEnum.CACHE_CONTROL; + 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 = HeaderEnum.CONNECTION; + 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 = HeaderEnum.CONTENT_DISPOSITION; + 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 = HeaderEnum.CONTENT_ENCODING; + 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 = HeaderEnum.CONTENT_LANGUAGE; + 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 = HeaderEnum.CONTENT_LENGTH; + 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 = HeaderEnum.CONTENT_LOCATION; + 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 = HeaderEnum.CONTENT_RANGE; + 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 = HeaderEnum.CONTENT_TYPE; + 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 = HeaderEnum.DATE; + 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 = HeaderEnum.ETAG; + 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 = HeaderEnum.EXPIRES; + 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 = HeaderEnum.LAST_MODIFIED; + 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 = HeaderEnum.LINK; + 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 = HeaderEnum.LOCATION; + 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 = HeaderEnum.PRAGMA; + 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 = HeaderEnum.PUBLIC_KEY_PINS; + 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 = HeaderEnum.RETRY_AFTER; + public static final HeaderName RETRY_AFTER = HeaderNameEnum.RETRY_AFTER; /** * The {@code Server} header name. * A name for the server. */ - public static final HeaderName SERVER = HeaderEnum.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 = HeaderEnum.SET_COOKIE; + 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 = HeaderEnum.SET_COOKIE2; + 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 = HeaderEnum.STRICT_TRANSPORT_SECURITY; + 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 = HeaderEnum.TRAILER; + 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 = HeaderEnum.TRANSFER_ENCODING; + 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 = HeaderEnum.TSV; + public static final HeaderName TSV = HeaderNameEnum.TSV; /** * The {@code Upgrade} header name. * Ask to upgrade to another protocol. */ - public static final HeaderName UPGRADE = HeaderEnum.UPGRADE; + 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 = HeaderEnum.VARY; + 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 = HeaderEnum.WARNING; + 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 = HeaderEnum.WWW_AUTHENTICATE; + 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 = HeaderEnum.X_HELIDON_CN; + 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 = HeaderEnum.X_FORWARDED_FOR; + 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 = HeaderEnum.X_FORWARDED_HOST; + 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 = HeaderEnum.X_FORWARDED_PORT; + public static final HeaderName X_FORWARDED_PORT = HeaderNameEnum.X_FORWARDED_PORT; /** * The {@code X_FORWARDED_PREFIX} header name. @@ -1430,28 +1375,28 @@ public static final class Header { * through one or more proxies. * */ - public static final HeaderName X_FORWARDED_PREFIX = HeaderEnum.X_FORWARDED_PREFIX; + 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 = HeaderEnum.X_FORWARDED_PROTO; + public static final HeaderName X_FORWARDED_PROTO = HeaderNameEnum.X_FORWARDED_PROTO; - private Header() { + private HeaderNames() { } /** * 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. + * 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 = HeaderEnum.byCapitalizedName(name); + HeaderName headerName = HeaderNameEnum.byCapitalizedName(name); if (headerName == null) { - return new HeaderImpl(Ascii.toLowerCase(name), name); + return new HeaderNameImpl(Ascii.toLowerCase(name), name); } return headerName; } @@ -1465,10 +1410,10 @@ public static HeaderName create(String name) { * @param defaultCase default case to use for custom header names (header names not known by Helidon) * @return header name instance */ - public static HeaderName createName(String lowerCase, String defaultCase) { - HeaderName headerName = HeaderEnum.byName(lowerCase); + public static HeaderName create(String lowerCase, String defaultCase) { + HeaderName headerName = HeaderNameEnum.byName(lowerCase); if (headerName == null) { - return new HeaderImpl(lowerCase, defaultCase); + return new HeaderNameImpl(lowerCase, defaultCase); } else { return headerName; } @@ -1481,17 +1426,126 @@ public static HeaderName createName(String lowerCase, String defaultCase) { * @return a new header name */ public static HeaderName createFromLowercase(String lowerCase) { - if (!Ascii.toLowerCase(lowerCase).equals(lowerCase)) { - throw new IllegalArgumentException("Lower case string required: " + lowerCase); - } - HeaderName headerName = HeaderEnum.byName(lowerCase); + HeaderName headerName = HeaderNameEnum.byName(lowerCase); if (headerName == null) { - return new HeaderImpl(lowerCase, lowerCase); + 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. @@ -1500,8 +1554,8 @@ public static HeaderName createFromLowercase(String lowerCase) { * @param value value of the header * @return a new header */ - public static HeaderValue createCached(String name, String value) { - return createCached(create(name), value); + public static Header createCached(String name, long value) { + return createCached(HeaderNames.create(name), value); } /** @@ -1512,7 +1566,7 @@ public static HeaderValue createCached(String name, String value) { * @param value value of the header * @return a new header */ - public static HeaderValue createCached(HeaderName name, String value) { + public static Header createCached(HeaderName name, String value) { return new HeaderValueCached(name, false, false, value.getBytes(StandardCharsets.US_ASCII), @@ -1527,7 +1581,19 @@ public static HeaderValue createCached(HeaderName name, String value) { * @param value value of the header * @return a new header */ - public static HeaderValue createCached(HeaderName name, int value) { + 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)); } @@ -1539,7 +1605,7 @@ public static HeaderValue createCached(HeaderName name, int value) { * @return a new header * @see #create(io.helidon.common.http.Http.HeaderName, boolean, boolean, String...) */ - public static HeaderValue create(HeaderName name, LazyString value) { + public static Header create(HeaderName name, LazyString value) { Objects.requireNonNull(name); Objects.requireNonNull(value); @@ -1554,7 +1620,7 @@ public static HeaderValue create(HeaderName name, LazyString value) { * @return a new header * @see #create(io.helidon.common.http.Http.HeaderName, boolean, boolean, String...) */ - public static HeaderValue create(HeaderName name, int value) { + public static Header create(HeaderName name, int value) { Objects.requireNonNull(name); return new HeaderValueSingle(name, false, false, String.valueOf(value)); @@ -1568,7 +1634,7 @@ public static HeaderValue create(HeaderName name, int value) { * @return a new header * @see #create(io.helidon.common.http.Http.HeaderName, boolean, boolean, String...) */ - public static HeaderValue create(HeaderName name, long value) { + public static Header create(HeaderName name, long value) { Objects.requireNonNull(name); return new HeaderValueSingle(name, false, false, String.valueOf(value)); @@ -1582,7 +1648,7 @@ public static HeaderValue create(HeaderName name, long value) { * @return a new header * @see #create(io.helidon.common.http.Http.HeaderName, boolean, boolean, String...) */ - public static HeaderValue create(HeaderName name, String value) { + public static Header create(HeaderName name, String value) { Objects.requireNonNull(name, "HeaderName must not be null"); Objects.requireNonNull(value, "HeaderValue must not be null"); @@ -1592,15 +1658,60 @@ public static HeaderValue create(HeaderName name, String value) { 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.common.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.common.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.common.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 name name of the header * @param values values of the header * @return a new header * @see #create(io.helidon.common.http.Http.HeaderName, boolean, boolean, String...) */ - public static HeaderValue create(HeaderName name, String... values) { + 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); } @@ -1612,10 +1723,34 @@ public static HeaderValue create(HeaderName name, String... values) { * @return a new header * @see #create(io.helidon.common.http.Http.HeaderName, boolean, boolean, String...) */ - public static HeaderValue create(HeaderName name, List values) { + 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.common.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.common.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. @@ -1626,7 +1761,7 @@ public static HeaderValue create(HeaderName name, List values) { * @param value value of the header * @return a new header */ - public static HeaderValue createCached(HeaderName name, boolean changing, boolean sensitive, String value) { + public static Header createCached(HeaderName name, boolean changing, boolean sensitive, String value) { return new HeaderValueCached(name, changing, sensitive, value.getBytes(StandardCharsets.UTF_8), value); } @@ -1639,95 +1774,34 @@ public static HeaderValue createCached(HeaderName name, boolean changing, boolea * @param values value(s) of the header * @return a new header */ - public static HeaderValue create(HeaderName name, boolean changing, boolean sensitive, String... values) { + public static Header create(HeaderName name, boolean changing, boolean sensitive, String... values) { return new HeaderValueArray(name, changing, sensitive, values); } - } - - /** - * Values of commonly used headers. - */ - public static final class HeaderValues { - /** - * Accept byte ranges for file download. - */ - public static final HeaderValue ACCEPT_RANGES_BYTES = Header.createCached(Header.ACCEPT_RANGES, "bytes"); - /** - * Not accepting byte ranges for file download. - */ - public static final HeaderValue ACCEPT_RANGES_NONE = Header.createCached(Header.ACCEPT_RANGES, "none"); - /** - * Chunked transfer encoding. - * Used in {@code HTTP/1}. - */ - public static final HeaderValue TRANSFER_ENCODING_CHUNKED = Header.createCached(Header.TRANSFER_ENCODING, "chunked"); - /** - * Connection keep-alive. - * Used in {@code HTTP/1}. - */ - public static final HeaderValue CONNECTION_KEEP_ALIVE = Header.createCached(Header.CONNECTION, "keep-alive"); - /** - * Connection close. - * Used in {@code HTTP/1}. - */ - public static final HeaderValue CONNECTION_CLOSE = Header.createCached(Header.CONNECTION, "close"); - /** - * Content type application/json with no charset. - */ - public static final HeaderValue CONTENT_TYPE_JSON = Header.createCached(Header.CONTENT_TYPE, "application/json"); - /** - * Content type text plain with no charset. - */ - public static final HeaderValue CONTENT_TYPE_TEXT_PLAIN = Header.createCached(Header.CONTENT_TYPE, "text/plain"); - /** - * Content type octet stream. - */ - public static final HeaderValue CONTENT_TYPE_OCTET_STREAM = Header.createCached(Header.CONTENT_TYPE, - "application/octet-stream"); - /** - * Content type SSE event stream. - */ - public static final HeaderValue CONTENT_TYPE_EVENT_STREAM = Header.createCached(Header.CONTENT_TYPE, - "text/event-stream"); /** - * Accept application/json. - */ - public static final HeaderValue ACCEPT_JSON = Header.createCached(Header.ACCEPT, "application/json"); - /** - * Accept text/plain with UTF-8. - */ - public static final HeaderValue ACCEPT_TEXT = Header.createCached(Header.ACCEPT, "text/plain;charset=UTF-8"); - /** - * Accept text/event-stream. - */ - public static final HeaderValue ACCEPT_EVENT_STREAM = Header.createCached(Header.ACCEPT, "text/event-stream"); - /** - * Expect 100 header. - */ - public static final HeaderValue EXPECT_100 = Header.createCached(Header.EXPECT, "100-continue"); - /** - * Content length with 0 value. - */ - public static final HeaderValue CONTENT_LENGTH_ZERO = Header.createCached(Header.CONTENT_LENGTH, "0"); - /** - * Cache control without any caching. - */ - public static final HeaderValue CACHE_NO_CACHE = Header.create(Header.CACHE_CONTROL, "no-cache", - "no-store", - "must-revalidate", - "no-transform"); - /** - * Cache control that allows caching with no transform. + * 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 final HeaderValue CACHE_NORMAL = Header.createCached(Header.CACHE_CONTROL, "no-transform"); + public static Header create(HeaderName name, boolean changing, boolean sensitive, int value) { + return create(name, changing, sensitive, String.valueOf(value)); + } /** - * TE header set to {@code trailers}, used to enable trailer headers. + * 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 final HeaderValue TE_TRAILERS = Header.createCached(Header.TE, "trailers"); - - private HeaderValues() { + public static Header create(HeaderName name, boolean changing, boolean sensitive, long value) { + return create(name, changing, sensitive, String.valueOf(value)); } } diff --git a/common/http/src/main/java/io/helidon/common/http/Http1HeadersParser.java b/common/http/src/main/java/io/helidon/common/http/Http1HeadersParser.java index e7c74620da7..a2f8dfa3422 100644 --- a/common/http/src/main/java/io/helidon/common/http/Http1HeadersParser.java +++ b/common/http/src/main/java/io/helidon/common/http/Http1HeadersParser.java @@ -27,13 +27,13 @@ */ public final class Http1HeadersParser { // TODO expand set of fastpath headers - private static final byte[] HD_HOST = (HeaderEnum.HOST.defaultCase() + ":").getBytes(StandardCharsets.UTF_8); - private static final byte[] HD_ACCEPT = (HeaderEnum.ACCEPT.defaultCase() + ":").getBytes(StandardCharsets.UTF_8); + private static final byte[] HD_HOST = (HeaderNameEnum.HOST.defaultCase() + ":").getBytes(StandardCharsets.UTF_8); + private static final byte[] HD_ACCEPT = (HeaderNameEnum.ACCEPT.defaultCase() + ":").getBytes(StandardCharsets.UTF_8); private static final byte[] HD_CONNECTION = - (HeaderEnum.CONNECTION.defaultCase() + ":").getBytes(StandardCharsets.UTF_8); + (HeaderNameEnum.CONNECTION.defaultCase() + ":").getBytes(StandardCharsets.UTF_8); private static final byte[] HD_USER_AGENT = - (HeaderEnum.USER_AGENT.defaultCase() + ":").getBytes(StandardCharsets.UTF_8); + (HeaderNameEnum.USER_AGENT.defaultCase() + ":").getBytes(StandardCharsets.UTF_8); private Http1HeadersParser() { } @@ -67,7 +67,7 @@ public static WritableHeaders readHeaders(DataReader reader, int maxHeadersSi reader.skip(2); maxLength -= eol + 1; - Http.HeaderValue headerValue = Http.Header.create(header, value); + Http.Header headerValue = Http.Headers.create(header, value); headers.add(headerValue); if (validate) { headerValue.validate(); @@ -85,25 +85,25 @@ private static Http.HeaderName readHeaderName(DataReader reader, case (byte) 'H' -> { if (reader.startsWith(HD_HOST)) { reader.skip(HD_HOST.length); - return HeaderEnum.HOST; + return HeaderNameEnum.HOST; } } case (byte) 'A' -> { if (reader.startsWith(HD_ACCEPT)) { reader.skip(HD_ACCEPT.length); - return HeaderEnum.ACCEPT; + return HeaderNameEnum.ACCEPT; } } case (byte) 'C' -> { if (reader.startsWith(HD_CONNECTION)) { reader.skip(HD_CONNECTION.length); - return HeaderEnum.CONNECTION; + return HeaderNameEnum.CONNECTION; } } case (byte) 'U' -> { if (reader.startsWith(HD_USER_AGENT)) { reader.skip(HD_USER_AGENT.length); - return HeaderEnum.USER_AGENT; + return HeaderNameEnum.USER_AGENT; } } default -> { @@ -117,7 +117,7 @@ private static Http.HeaderName readHeaderName(DataReader reader, } String headerName = reader.readAsciiString(col); - Http.HeaderName header = Http.Header.create(headerName); + Http.HeaderName header = Http.HeaderNames.create(headerName); reader.skip(1); // skip the colon character return header; diff --git a/common/http/src/main/java/io/helidon/common/http/HttpMediaType.java b/common/http/src/main/java/io/helidon/common/http/HttpMediaType.java index b846ebb57a5..a3ac51d54c8 100644 --- a/common/http/src/main/java/io/helidon/common/http/HttpMediaType.java +++ b/common/http/src/main/java/io/helidon/common/http/HttpMediaType.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2023 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -29,6 +29,8 @@ /** * Media type used in HTTP headers, in addition to the media type definition, these may contain additional * parameters, such as {@link #QUALITY_FACTOR_PARAMETER} and {@link #CHARSET_PARAMETER}. + * + * @see io.helidon.common.http.HttpMediaTypes */ public sealed interface HttpMediaType extends Predicate, Comparable, @@ -41,48 +43,6 @@ public sealed interface HttpMediaType extends Predicate, * The media type quality factor {@value} parameter name. */ String QUALITY_FACTOR_PARAMETER = "q"; - /** - * {@code application/json} media type without parameters. - */ - HttpMediaType APPLICATION_JSON = HttpMediaType.create(MediaTypes.APPLICATION_JSON); - /** - * application/json media type with UTF-8 charset. - */ - HttpMediaType JSON_UTF_8 = HttpMediaType.builder() - .mediaType(MediaTypes.APPLICATION_JSON) - .charset("UTF-8") - .build(); - /** - * {@code text/plain} media type without parameters. - */ - HttpMediaType TEXT_PLAIN = HttpMediaType.create(MediaTypes.TEXT_PLAIN); - /** - * text/plain media type with UTF-8 charset. - */ - HttpMediaType PLAINTEXT_UTF_8 = HttpMediaType.builder() - .mediaType(MediaTypes.TEXT_PLAIN) - .charset("UTF-8") - .build(); - - /** - * {@code application/octet-stream} media type without parameters. - */ - HttpMediaType APPLICATION_OCTET_STREAM = HttpMediaType.create(MediaTypes.APPLICATION_OCTET_STREAM); - - /** - * Predicate to test if {@link MediaType} is {@code application/json} or has {@code json} suffix. - */ - Predicate JSON_PREDICATE = JSON_UTF_8 - .or(mt -> mt.hasSuffix("json")); - - /** - * Predicate to test if {@link MediaType} is {@code text/event-stream} without any parameter or with parameter "element-type". - * This "element-type" has to be equal to "application/json". - */ - Predicate JSON_EVENT_STREAM_PREDICATE = HttpMediaType.create(MediaTypes.TEXT_EVENT_STREAM) - .and(mt -> mt.hasSuffix("event-stream")) - .and(mt -> !mt.parameters().containsKey("element-type") - || "application/json".equals(mt.parameters().get("element-type"))); /** * A fluent API builder for creating customized Media type instances. diff --git a/common/http/src/main/java/io/helidon/common/http/HttpMediaTypes.java b/common/http/src/main/java/io/helidon/common/http/HttpMediaTypes.java new file mode 100644 index 00000000000..1674d950240 --- /dev/null +++ b/common/http/src/main/java/io/helidon/common/http/HttpMediaTypes.java @@ -0,0 +1,59 @@ +/* + * 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.common.http; + +import java.util.function.Predicate; + +import io.helidon.common.media.type.MediaTypes; + +/** + * Constants for {@link io.helidon.common.http.HttpMediaType}. + */ +public final class HttpMediaTypes { + /** + * application/json media type with UTF-8 charset. + */ + public static final HttpMediaType JSON_UTF_8 = HttpMediaType.builder() + .mediaType(MediaTypes.APPLICATION_JSON) + .charset("UTF-8") + .build(); + /** + * Predicate to test if {@link io.helidon.common.media.type.MediaType} is {@code application/json} or has {@code json} suffix. + */ + public static final Predicate JSON_PREDICATE = JSON_UTF_8 + .or(mt -> mt.hasSuffix("json")); + /** + * text/plain media type with UTF-8 charset. + */ + public static final HttpMediaType PLAINTEXT_UTF_8 = HttpMediaType.builder() + .mediaType(MediaTypes.TEXT_PLAIN) + .charset("UTF-8") + .build(); + /** + * Predicate to test if {@link io.helidon.common.media.type.MediaType} is {@code text/event-stream} without any parameter or with parameter "element-type". + * This "element-type" has to be equal to "application/json". + */ + public static final Predicate JSON_EVENT_STREAM_PREDICATE = HttpMediaType.create(MediaTypes.TEXT_EVENT_STREAM) + .and(mt -> mt.hasSuffix("event-stream")) + .and(mt -> !mt.parameters().containsKey("element-type") + || "application/json".equals(mt.parameters().get("element-type"))); + + private HttpMediaTypes() { + } + + +} diff --git a/common/http/src/main/java/io/helidon/common/http/RequestException.java b/common/http/src/main/java/io/helidon/common/http/RequestException.java index 0f2e1b4fa37..cf3ae50fb3d 100644 --- a/common/http/src/main/java/io/helidon/common/http/RequestException.java +++ b/common/http/src/main/java/io/helidon/common/http/RequestException.java @@ -218,7 +218,7 @@ public Builder setKeepAlive(boolean keepAlive) { * @param header header to add * @return updated builder */ - public Builder header(Http.HeaderValue header) { + public Builder header(Http.Header header) { this.responseHeaders.set(header); return this; } diff --git a/common/http/src/main/java/io/helidon/common/http/RequestedUriDiscoveryContext.java b/common/http/src/main/java/io/helidon/common/http/RequestedUriDiscoveryContext.java index 2d0d5993878..e632821b76a 100644 --- a/common/http/src/main/java/io/helidon/common/http/RequestedUriDiscoveryContext.java +++ b/common/http/src/main/java/io/helidon/common/http/RequestedUriDiscoveryContext.java @@ -326,12 +326,12 @@ public UriInfo uriInfo(String remoteAddress, } } case HOST -> { - authority = headers.first(Http.Header.HOST).orElse(null); + authority = headers.first(Http.HeaderNames.HOST).orElse(null); break nextDiscoveryType; } default -> { - authority = headers.first(Http.Header.HOST).orElse(null); + authority = headers.first(Http.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.Header.HOST).orElse(null); + authority = headers.first(Http.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.Header.X_FORWARDED_FOR); + List xForwardedFors = headers.values(Http.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.Header.X_FORWARDED_PROTO).orElse(null); - host = headers.first(Http.Header.X_FORWARDED_HOST).orElse(null); - port = headers.first(Http.Header.X_FORWARDED_PORT).map(Integer::parseInt).orElse(-1); - path = headers.first(Http.Header.X_FORWARDED_PREFIX) + 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) .map(prefix -> { String absolute = requestPath; return prefix + (absolute.startsWith("/") ? "" : "/") + absolute; diff --git a/common/http/src/main/java/io/helidon/common/http/ServerRequestHeaders.java b/common/http/src/main/java/io/helidon/common/http/ServerRequestHeaders.java index a0b74dd583d..82ee7df6358 100644 --- a/common/http/src/main/java/io/helidon/common/http/ServerRequestHeaders.java +++ b/common/http/src/main/java/io/helidon/common/http/ServerRequestHeaders.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -21,7 +21,7 @@ import java.util.List; import java.util.Optional; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.Header; import io.helidon.common.media.type.MediaType; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.parameters.Parameters; @@ -36,8 +36,8 @@ public interface ServerRequestHeaders extends Headers { * * @see JDK-8163921 */ - HeaderValue HUC_ACCEPT_DEFAULT = Http.Header.create(Http.Header.ACCEPT, - "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"); + Http.Header HUC_ACCEPT_DEFAULT = Http.Headers.create(Http.HeaderNames.ACCEPT, + "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2"); /** * Accepted types for {@link #HUC_ACCEPT_DEFAULT}. @@ -70,16 +70,16 @@ static ServerRequestHeaders create() { } /** - * Optionally returns a value of {@link Http.Header#IF_MODIFIED_SINCE} header. + * Optionally returns a value of {@link io.helidon.common.http.Http.HeaderNames#IF_MODIFIED_SINCE} header. *

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

* Only send the response if the entity has not been modified since a specific time. * - * @return Content of {@link Http.Header#IF_UNMODIFIED_SINCE} header. + * @return Content of {@link io.helidon.common.http.Http.HeaderNames#IF_UNMODIFIED_SINCE} header. */ default Optional ifUnmodifiedSince() { - if (contains(Http.Header.IF_UNMODIFIED_SINCE)) { - return Optional.of(get(Http.Header.IF_UNMODIFIED_SINCE)) - .map(HeaderValue::value) + if (contains(Http.HeaderNames.IF_UNMODIFIED_SINCE)) { + return Optional.of(get(Http.HeaderNames.IF_UNMODIFIED_SINCE)) + .map(Http.Header::value) .map(Http.DateTime::parse); } return Optional.empty(); @@ -127,7 +127,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.common.http.Http.Header#ACCEPT} + * Method uses content negotiation {@link io.helidon.common.http.Http.HeaderNames#ACCEPT} * header parameter and returns an empty value in case nothing matches. * * @param mediaTypes media type candidates, never null @@ -172,43 +172,43 @@ default Optional bestAccepted(MediaType... mediaTypes) { * values are cookie values. */ default Parameters cookies() { - if (contains(Http.Header.COOKIE)) { - return CookieParser.parse(get(Http.Header.COOKIE)); + if (contains(Http.HeaderNames.COOKIE)) { + return CookieParser.parse(get(Http.HeaderNames.COOKIE)); } else { return CookieParser.empty(); } } /** - * Optionally returns acceptedTypes version in time ({@link io.helidon.common.http.Http.Header#ACCEPT_DATETIME} header). + * Optionally returns acceptedTypes version in time ({@link io.helidon.common.http.Http.HeaderNames#ACCEPT_DATETIME} header). * * @return Acceptable version in time. */ default Optional acceptDatetime() { - if (contains(Http.Header.ACCEPT_DATETIME)) { - return Optional.of(get(Http.Header.ACCEPT_DATETIME)) - .map(HeaderValue::value) + if (contains(Http.HeaderNames.ACCEPT_DATETIME)) { + return Optional.of(get(Http.HeaderNames.ACCEPT_DATETIME)) + .map(Http.Header::value) .map(Http.DateTime::parse); } return Optional.empty(); } /** - * Optionally returns request date ({@link io.helidon.common.http.Http.Header#DATE} header). + * Optionally returns request date ({@link io.helidon.common.http.Http.HeaderNames#DATE} header). * * @return Request date. */ default Optional date() { - if (contains(Http.Header.DATE)) { - return Optional.of(get(Http.Header.DATE)) - .map(HeaderValue::value) + if (contains(Http.HeaderNames.DATE)) { + return Optional.of(get(Http.HeaderNames.DATE)) + .map(Header::value) .map(Http.DateTime::parse); } return Optional.empty(); } /** - * Optionally returns the address of the previous web page (header {@link io.helidon.common.http.Http.Header#REFERER}) from which a link + * Optionally returns the address of the previous web page (header {@link io.helidon.common.http.Http.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,9 +217,9 @@ default Optional date() { * @return Referrers URI */ default Optional referer() { - if (contains(Http.Header.REFERER)) { - return Optional.of(get(Http.Header.REFERER)) - .map(HeaderValue::value) + if (contains(Http.HeaderNames.REFERER)) { + return Optional.of(get(Http.HeaderNames.REFERER)) + .map(Header::value) .map(URI::create); } return Optional.empty(); diff --git a/common/http/src/main/java/io/helidon/common/http/ServerRequestHeadersImpl.java b/common/http/src/main/java/io/helidon/common/http/ServerRequestHeadersImpl.java index f9e410a8f9d..6e5aeeea428 100644 --- a/common/http/src/main/java/io/helidon/common/http/ServerRequestHeadersImpl.java +++ b/common/http/src/main/java/io/helidon/common/http/ServerRequestHeadersImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -47,12 +47,12 @@ public boolean contains(HeaderName name) { } @Override - public boolean contains(Http.HeaderValue headerWithValue) { + public boolean contains(Http.Header headerWithValue) { return headers.contains(headerWithValue); } @Override - public Http.HeaderValue get(HeaderName name) { + public Http.Header get(HeaderName name) { return headers.get(name); } @@ -77,7 +77,7 @@ public List acceptedTypes() { } List acceptedTypes; - List acceptValues = all(Http.Header.ACCEPT, List::of); + List acceptValues = all(Http.HeaderNames.ACCEPT, List::of); if (acceptValues.size() == 1 && HUC_ACCEPT_DEFAULT.value().equals(acceptValues.get(0))) { acceptedTypes = HUC_ACCEPT_DEFAULT_TYPES; } else { @@ -97,7 +97,7 @@ public List acceptedTypes() { } @Override - public Iterator iterator() { + public Iterator iterator() { return headers.iterator(); } diff --git a/common/http/src/main/java/io/helidon/common/http/ServerResponseHeaders.java b/common/http/src/main/java/io/helidon/common/http/ServerResponseHeaders.java index 526e7bdbd54..d64e2f17a30 100644 --- a/common/http/src/main/java/io/helidon/common/http/ServerResponseHeaders.java +++ b/common/http/src/main/java/io/helidon/common/http/ServerResponseHeaders.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -22,12 +22,11 @@ import java.time.ZoneId; import java.time.ZonedDateTime; -import io.helidon.common.http.Http.Header; import io.helidon.common.media.type.MediaType; -import static io.helidon.common.http.Http.Header.EXPIRES; -import static io.helidon.common.http.Http.Header.LAST_MODIFIED; -import static io.helidon.common.http.Http.Header.LOCATION; +import static io.helidon.common.http.Http.HeaderNames.EXPIRES; +import static io.helidon.common.http.Http.HeaderNames.LAST_MODIFIED; +import static io.helidon.common.http.Http.HeaderNames.LOCATION; /** * Mutable headers of a server response. @@ -56,24 +55,7 @@ static ServerResponseHeaders create(Headers existing) { /** * Adds one or more acceptedTypes path document formats - * (header {@link Header#ACCEPT_PATCH}). - * - * @param acceptableMediaTypes media types to add. - * @return this instance - */ - default ServerResponseHeaders addAcceptPatches(HttpMediaType... acceptableMediaTypes) { - String[] values = new String[acceptableMediaTypes.length]; - for (int i = 0; i < acceptableMediaTypes.length; i++) { - HttpMediaType acceptableMediaType = acceptableMediaTypes[i]; - values[i] = acceptableMediaType.text(); - } - return add(Header.create(Header.ACCEPT_PATCH, - values)); - } - - /** - * Adds one or more acceptedTypes path document formats - * (header {@link Header#ACCEPT_PATCH}). + * (header {@link io.helidon.common.http.Http.HeaderNames#ACCEPT_PATCH}). * * @param acceptableMediaTypes media types to add. * @return this instance @@ -84,8 +66,8 @@ default ServerResponseHeaders addAcceptPatches(MediaType... acceptableMediaTypes MediaType acceptableMediaType = acceptableMediaTypes[i]; values[i] = acceptableMediaType.text(); } - return add(Header.create(Header.ACCEPT_PATCH, - values)); + return add(Http.Headers.create(Http.HeaderNames.ACCEPT_PATCH, + values)); } /** @@ -131,7 +113,7 @@ default ServerResponseHeaders addCookie(String name, String value) { ServerResponseHeaders clearCookie(String name); /** - * Sets the value of {@link Header#LAST_MODIFIED} header. + * Sets the value of {@link io.helidon.common.http.Http.HeaderNames#LAST_MODIFIED} header. *

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

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

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

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

* The date/time after which the response is considered stale. * @@ -188,7 +170,7 @@ default ServerResponseHeaders expires(ZonedDateTime dateTime) { * @return updated headers */ default ServerResponseHeaders expires(Instant dateTime) { - return set(Header.create(EXPIRES, ZonedDateTime.ofInstant(dateTime, ZoneId.systemDefault()) + return set(Http.Headers.create(EXPIRES, ZonedDateTime.ofInstant(dateTime, ZoneId.systemDefault()) .format(Http.DateTime.RFC_1123_DATE_TIME))); } } diff --git a/common/http/src/main/java/io/helidon/common/http/ServerResponseHeadersImpl.java b/common/http/src/main/java/io/helidon/common/http/ServerResponseHeadersImpl.java index b60b2719e57..ffefb0241b7 100644 --- a/common/http/src/main/java/io/helidon/common/http/ServerResponseHeadersImpl.java +++ b/common/http/src/main/java/io/helidon/common/http/ServerResponseHeadersImpl.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -35,7 +35,7 @@ class ServerResponseHeadersImpl extends HeadersImpl imple @Override public ServerResponseHeaders addCookie(SetCookie cookie) { - add(Http.Header.create(Http.Header.SET_COOKIE, cookie.toString())); + add(Http.Headers.create(Http.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.Header.SET_COOKIE)) { - remove(Http.Header.SET_COOKIE, it -> { + if (contains(Http.HeaderNames.SET_COOKIE)) { + remove(Http.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.Header.create(Http.Header.SET_COOKIE, newValues)); + set(Http.Headers.create(Http.HeaderNames.SET_COOKIE, newValues)); }); } else { addCookie(expiredCookie); diff --git a/common/http/src/main/java/io/helidon/common/http/WritableHeaders.java b/common/http/src/main/java/io/helidon/common/http/WritableHeaders.java index 22543e4aaf0..e023bf26eed 100644 --- a/common/http/src/main/java/io/helidon/common/http/WritableHeaders.java +++ b/common/http/src/main/java/io/helidon/common/http/WritableHeaders.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -16,11 +16,11 @@ package io.helidon.common.http; -import java.util.List; +import java.util.Collection; import java.util.function.Consumer; +import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; import io.helidon.common.media.type.MediaType; /** @@ -54,7 +54,7 @@ static WritableHeaders create(Headers headers) { * @param header header with value to set * @return this instance */ - B setIfAbsent(HeaderValue header); + B setIfAbsent(Http.Header header); /** * Add a header or add a header value if the header is already present. @@ -62,7 +62,7 @@ static WritableHeaders create(Headers headers) { * @param header header with value * @return this instance */ - B add(HeaderValue header); + B add(Header header); /** * Add a header or add a header value if the header is already present. @@ -72,7 +72,29 @@ static WritableHeaders create(Headers headers) { * @return this instance */ default B add(HeaderName header, String... value) { - return add(Http.Header.create(header, value)); + return add(Http.Headers.create(header, value)); + } + + /** + * Add a header or add a header value if the header is already present. + * + * @param header header name + * @param value header value + * @return this instance + */ + default B add(HeaderName header, int value) { + return add(Http.Headers.create(header, value)); + } + + /** + * Add a header or add a header value if the header is already present. + * + * @param header header name + * @param value header value + * @return this instance + */ + default B add(HeaderName header, long value) { + return add(Http.Headers.create(header, value)); } /** @@ -91,53 +113,72 @@ default B add(HeaderName header, String... value) { * called * @return this instance */ - B remove(HeaderName name, Consumer removedConsumer); + B remove(HeaderName name, Consumer

removedConsumer); /** * Sets the MIME type of the response body. * - * @param contentType Media type of the content. + * @param contentType Media type of the content, {@link io.helidon.common.http.HttpMediaType} may be used to add parameters * @return this instance */ default B contentType(MediaType contentType) { - return set(Http.Header.create(HeaderEnum.CONTENT_TYPE, contentType.text())); + return set(Http.Headers.create(HeaderNameEnum.CONTENT_TYPE, contentType.text())); } /** - * Sets the MIME type of the response body. + * Set a header and replace it if it already existed. * - * @param contentType Media type of the content. + * @param header header to set * @return this instance */ - default B contentType(HttpMediaType contentType) { - return set(Http.Header.create(HeaderEnum.CONTENT_TYPE, contentType.text())); + B set(Http.Header header); + + /** + * Set a header and replace it if it already existed. + * Use {@link #set(io.helidon.common.http.Http.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. + * + * @param name header name to set + * @param values value(s) of the header + * @return this instance + */ + default B set(HeaderName name, String... values) { + return set(Http.Headers.create(name, true, false, values)); } + /** * Set a header and replace it if it already existed. + * Use {@link #set(io.helidon.common.http.Http.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. * - * @param header header to set + * @param name header name to set + * @param value integer value of the header * @return this instance */ - B set(HeaderValue header); + default B set(HeaderName name, int value) { + return set(Http.Headers.create(name, true, false, value)); + } /** * Set a header and replace it if it already existed. - * Use {@link #set(io.helidon.common.http.Http.HeaderValue)} for headers that are known in advance (use a constant), + * Use {@link #set(io.helidon.common.http.Http.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. * * @param name header name to set - * @param values value(s) of the header + * @param value long value of the header * @return this instance */ - default B set(HeaderName name, String... values) { - return set(Http.Header.create(name, true, false, values)); + default B set(HeaderName name, long value) { + return set(Http.Headers.create(name, true, false, value)); } /** * Set a header and replace it if it already existed. - * Use {@link #set(io.helidon.common.http.Http.HeaderValue)} for headers that are known in advance (use a constant), + * Use {@link #set(io.helidon.common.http.Http.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. * @@ -145,8 +186,8 @@ default B set(HeaderName name, String... values) { * @param values value(s) of the header * @return this instance */ - default B set(HeaderName name, List values) { - return set(Http.Header.create(name, values)); + default B set(HeaderName name, Collection values) { + return set(Http.Headers.create(name, values)); } /** @@ -159,10 +200,10 @@ default B set(HeaderName name, List values) { * @return this instance */ default B contentLength(long length) { - return set(Http.Header.create(HeaderEnum.CONTENT_LENGTH, - true, - false, - String.valueOf(length))); + return set(Http.Headers.create(HeaderNameEnum.CONTENT_LENGTH, + true, + false, + String.valueOf(length))); } /** @@ -171,4 +212,14 @@ default B contentLength(long length) { * @return this instance */ B clear(); + + /** + * For each header from the provided headers, set its value on these headers. + * If a header exists on these headers and on the provided headers, it would be replaced with the value(s) from + * provided headers. + * + * @param headers to read headers from and set them on this instance + * @return this instance + */ + B from(Headers headers); } diff --git a/common/http/src/test/java/io/helidon/common/http/CookieParserTest.java b/common/http/src/test/java/io/helidon/common/http/CookieParserTest.java index 34c4867eabd..62e5a59e7fc 100644 --- a/common/http/src/test/java/io/helidon/common/http/CookieParserTest.java +++ b/common/http/src/test/java/io/helidon/common/http/CookieParserTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -16,12 +16,11 @@ package io.helidon.common.http; -import io.helidon.common.http.Http.Header; import io.helidon.common.parameters.Parameters; import org.junit.jupiter.api.Test; -import static io.helidon.common.http.Http.Header.COOKIE; +import static io.helidon.common.http.Http.HeaderNames.COOKIE; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; @@ -31,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(Header.create(COOKIE, header)); + Parameters p = CookieParser.parse(Http.Headers.create(COOKIE, header)); assertThat(p, notNullValue()); assertThat(p.all("foo"), contains("bar")); assertThat(p.all("aaa"), contains("bbb")); @@ -43,7 +42,7 @@ public void rfc2965() throws Exception { @Test public void unquote() throws Exception { - Parameters p = CookieParser.parse(Header.create(COOKIE, "foo=\"bar\"; aaa=bbb; c=\"what_the_hell\"; aaa=\"ccc\"")); + Parameters p = CookieParser.parse(Http.Headers.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")); @@ -57,7 +56,7 @@ void testEmpty() { @Test void testMultiValueSingleHeader() { - Parameters cookies = CookieParser.parse(Header.create(COOKIE, "foo=bar; aaa=bbb; c=here; aaa=ccc")); + Parameters cookies = CookieParser.parse(Http.Headers.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")); @@ -66,7 +65,7 @@ void testMultiValueSingleHeader() { @Test void testMultiValueMultiHeader() { - Parameters cookies = CookieParser.parse(Header.create(COOKIE, "foo=bar; aaa=bbb; c=here", "aaa=ccc")); + Parameters cookies = CookieParser.parse(Http.Headers.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/common/http/src/test/java/io/helidon/common/http/ForwardedTest.java b/common/http/src/test/java/io/helidon/common/http/ForwardedTest.java index a4fdcee28cd..36e5a180d28 100644 --- a/common/http/src/test/java/io/helidon/common/http/ForwardedTest.java +++ b/common/http/src/test/java/io/helidon/common/http/ForwardedTest.java @@ -73,7 +73,7 @@ void testAll() { @Test void testMultiValuesCommaSeparated() { HeadersImpl headers = new HeadersImpl<>(); - headers.add(Http.Header.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(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\""); 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.Header.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10", + 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\""); List forwardedList = Forwarded.create(headers); @@ -116,7 +116,7 @@ void testMultiValues() { @Test void testMultiValuesAndCommaSeparated() { HeadersImpl headers = new HeadersImpl<>(); - headers.add(Http.Header.FORWARDED, "for=192.0.2.60;proto=http;by=203.0.113.43;Host=10.10.10.10", + 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\",for=\"14.22.11.22\""); List forwardedList = Forwarded.create(headers); diff --git a/common/http/src/test/java/io/helidon/common/http/HeaderNamesTest.java b/common/http/src/test/java/io/helidon/common/http/HeaderNamesTest.java index 23f9f4780e4..4a2b5ee8e7e 100644 --- a/common/http/src/test/java/io/helidon/common/http/HeaderNamesTest.java +++ b/common/http/src/test/java/io/helidon/common/http/HeaderNamesTest.java @@ -25,6 +25,8 @@ import org.junit.jupiter.api.Test; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; @@ -32,7 +34,7 @@ import static org.junit.jupiter.api.Assertions.assertAll; class HeaderNamesTest { - private static final Class clazz = Http.Header.class; + private static final Class clazz = Http.HeaderNames.class; private static final Set constants = Stream.of(clazz.getDeclaredFields()) .filter(it -> Modifier.isStatic(it.getModifiers())) .filter(it -> Modifier.isFinal(it.getModifiers())) @@ -42,11 +44,11 @@ class HeaderNamesTest { @Test void testAllEnumValuesHaveConstants() { - HeaderEnum[] expectedNames = HeaderEnum.values(); + HeaderNameEnum[] expectedNames = HeaderNameEnum.values(); Set missing = new LinkedHashSet<>(); - for (HeaderEnum expectedName : expectedNames) { + for (HeaderNameEnum expectedName : expectedNames) { String name = expectedName.name(); if (!constants.contains(name)) { missing.add(name); @@ -77,4 +79,44 @@ void testAllConstantsAreValid() throws NoSuchFieldException, IllegalAccessExcept } } + + @Test + void testEqualsAndHashCodeKnownHeader() { + Http.HeaderName customAccept = Http.HeaderNames.create("ACCEPT"); + + assertThat(customAccept, equalTo(Http.HeaderNames.ACCEPT)); + assertThat(Http.HeaderNames.ACCEPT, equalTo(customAccept)); + assertThat(customAccept.hashCode(), is(Http.HeaderNames.ACCEPT.hashCode())); + + + customAccept = Http.HeaderNames.create("accept", "ACCEPT"); + + assertThat(customAccept, equalTo(Http.HeaderNames.ACCEPT)); + assertThat(Http.HeaderNames.ACCEPT, equalTo(customAccept)); + assertThat(customAccept.hashCode(), is(Http.HeaderNames.ACCEPT.hashCode())); + } + + @Test + void testEqualsAndHashCodeCustomHeader() { + Http.HeaderName custom1 = Http.HeaderNames.create("My-Custom-Header"); + Http.HeaderName custom2 = Http.HeaderNames.create("my-custom-header"); + + + assertThat(custom1, equalTo(custom2)); + assertThat(custom2, equalTo(custom1)); + 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"); + + assertThat(custom1, equalTo(custom2)); + assertThat(custom2, equalTo(custom1)); + assertThat(custom1.hashCode(), is(custom2.hashCode())); + + assertThat(custom1.lowerCase(), is("my-custom-header")); + assertThat(custom1.defaultCase(), is("My-Custom-Header")); + assertThat(custom2.lowerCase(), is("my-custom-header")); + assertThat(custom2.defaultCase(), is("my-custom-header")); + } } diff --git a/common/http/src/test/java/io/helidon/common/http/Http1HeadersParserTest.java b/common/http/src/test/java/io/helidon/common/http/Http1HeadersParserTest.java index ebf86b2f506..a3a49871156 100644 --- a/common/http/src/test/java/io/helidon/common/http/Http1HeadersParserTest.java +++ b/common/http/src/test/java/io/helidon/common/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.Header.create(headerName)).values(); + String responseHeaderValue = headers.get(Http.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.Header.create(CUSTOM_HEADER_NAME)).values(); + String responseHeaderValue = headers.get(Http.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.Header.create(header); + Http.HeaderName headerName = Http.HeaderNames.create(header); assertThat("Headers should contain header: " + headerName.lowerCase(), headers.contains(headerName), is(true)); diff --git a/common/http/src/test/java/io/helidon/common/http/HttpTest.java b/common/http/src/test/java/io/helidon/common/http/HttpTest.java index b6e9f225541..9d32a116c92 100644 --- a/common/http/src/test/java/io/helidon/common/http/HttpTest.java +++ b/common/http/src/test/java/io/helidon/common/http/HttpTest.java @@ -61,7 +61,7 @@ void testResposneStatusCustomReason() { @ParameterizedTest @MethodSource("headers") void testHeaderValidation(String headerName, String headerValues, boolean expectsValid) { - Http.HeaderValue header = Http.Header.create(Http.Header.create(headerName), headerValues); + Http.Header header = Http.Headers.create(headerName, headerValues); if (expectsValid) { header.validate(); } else { diff --git a/common/http/src/test/java/io/helidon/common/http/MediaTypeTest.java b/common/http/src/test/java/io/helidon/common/http/MediaTypeTest.java index a71910f942b..1c783ffeb6b 100644 --- a/common/http/src/test/java/io/helidon/common/http/MediaTypeTest.java +++ b/common/http/src/test/java/io/helidon/common/http/MediaTypeTest.java @@ -97,9 +97,9 @@ void qualityFactor() { @Test void asPredicate() { assertThat(HttpMediaType.create("application/json").test(MediaTypes.APPLICATION_JSON), is(true)); - assertThat(HttpMediaType.JSON_UTF_8.test(MediaTypes.create("application/json")), is(true)); + assertThat(HttpMediaTypes.JSON_UTF_8.test(MediaTypes.create("application/json")), is(true)); assertThat(HttpMediaType.create("application/*").test(MediaTypes.APPLICATION_JSON), is(true)); - assertThat(HttpMediaType.JSON_UTF_8.test(MediaTypes.create("application/*")), is(true)); + assertThat(HttpMediaTypes.JSON_UTF_8.test(MediaTypes.create("application/*")), is(true)); assertThat(HttpMediaType.create(MediaTypes.APPLICATION_JSON).withCharset("UTF-8") .test(MediaTypes.create("application/json")), is(true)); @@ -107,12 +107,12 @@ void asPredicate() { @Test void jsonPredicate() { - assertThat(HttpMediaType.JSON_PREDICATE.test(HttpMediaType.create(MediaTypes.create("application/json"))), is(true)); - assertThat(HttpMediaType.JSON_PREDICATE.test(HttpMediaType.create(MediaTypes.create("application/javascript"))), + assertThat(HttpMediaTypes.JSON_PREDICATE.test(HttpMediaType.create(MediaTypes.create("application/json"))), is(true)); + assertThat(HttpMediaTypes.JSON_PREDICATE.test(HttpMediaType.create(MediaTypes.create("application/javascript"))), is(false)); - assertThat(HttpMediaType.JSON_PREDICATE.test(HttpMediaType.create(MediaTypes.create("application/manifest+json"))), + assertThat(HttpMediaTypes.JSON_PREDICATE.test(HttpMediaType.create(MediaTypes.create("application/manifest+json"))), is(true)); - assertThat(HttpMediaType.JSON_PREDICATE.test(HttpMediaType.create(MediaTypes.create("application/manifest"))), is(false)); + assertThat(HttpMediaTypes.JSON_PREDICATE.test(HttpMediaType.create(MediaTypes.create("application/manifest"))), is(false)); } @Test 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 85962ad231a..16405d8f3a5 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.helidon.common.testing.http.junit5; import java.util.List; import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; import org.hamcrest.Description; @@ -77,7 +77,7 @@ public static Matcher hasHeader(HeaderName name) { * @param header http header with values * @return matcher validating the {@link io.helidon.common.http.Headers} does contain the provided header */ - public static Matcher hasHeader(Http.HeaderValue header) { + public static Matcher hasHeader(Http.Header header) { return new HasValueMatcher(header); } @@ -95,7 +95,7 @@ public static Matcher hasHeader(Http.HeaderValue header) { * @return matcher validating the {@link io.helidon.common.http.Headers} does contain the provided header */ public static Matcher hasHeader(Http.HeaderName name, String... value) { - return new HasValueMatcher(Header.create(name, value)); + return new HasValueMatcher(Http.Headers.create(name, value)); } /** @@ -160,7 +160,7 @@ private static class HasValueMatcher extends TypeSafeMatcher { private final HeaderName name; private final Matcher> valuesMatcher; - HasValueMatcher(Http.HeaderValue header) { + HasValueMatcher(Http.Header header) { this.name = header.headerName(); this.valuesMatcher = Matchers.containsInAnyOrder(header.allValues().toArray(new String[0])); } @@ -214,7 +214,7 @@ public void describeTo(Description description) { @Override protected boolean matchesSafely(Headers httpHeaders) { if (httpHeaders.contains(name)) { - Http.HeaderValue headerValue = httpHeaders.get(name); + Http.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 c95a0acffd4..3dba3517e48 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 @@ -136,7 +136,7 @@ public static ClientResponseHeaders headersFromResponse(String response) { if (i < 0) { throw new AssertionError("Header without semicolon - " + line); } - headers.add(Http.Header.create(line.substring(0, i).trim()), line.substring(i + 1).trim()); + headers.add(Http.HeaderNames.create(line.substring(0, i).trim()), line.substring(i + 1).trim()); } return ClientResponseHeaders.create(headers); } diff --git a/cors/src/main/java/io/helidon/cors/CorsSupportHelper.java b/cors/src/main/java/io/helidon/cors/CorsSupportHelper.java index ea2145f4f41..be5a4b7a6cd 100644 --- a/cors/src/main/java/io/helidon/cors/CorsSupportHelper.java +++ b/cors/src/main/java/io/helidon/cors/CorsSupportHelper.java @@ -30,7 +30,7 @@ import io.helidon.common.config.Config; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.cors.LogHelper.Headers; import static io.helidon.cors.LogHelper.DECISION_LEVEL; @@ -326,7 +326,7 @@ public void prepareResponse(CorsRequestAdapter requestAdapter, CorsResponseAd // 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.builder() - .allowOrigins(requestAdapter.firstHeader(Header.ORIGIN).orElse("*")) + .allowOrigins(requestAdapter.firstHeader(Http.HeaderNames.ORIGIN).orElse("*")) .allowMethods(requestAdapter.method()) .build() : aggregator.lookupCrossOrigin( @@ -369,8 +369,8 @@ public Aggregator aggregator() { private boolean isRequestTypeNormal(CorsRequestAdapter requestAdapter, boolean silent) { // If no origin header or same as host, then just normal - Optional originOpt = requestAdapter.firstHeader(Header.ORIGIN); - Optional hostOpt = requestAdapter.firstHeader(Header.HOST); + Optional originOpt = requestAdapter.firstHeader(HeaderNames.ORIGIN); + Optional hostOpt = requestAdapter.firstHeader(HeaderNames.HOST); boolean result = originOpt.isEmpty() || (hostOpt.isPresent() && originOpt.get().contains("://" + hostOpt.get())); LogHelper.logIsRequestTypeNormal(result, silent, requestAdapter, originOpt, hostOpt); @@ -382,7 +382,7 @@ private RequestType inferCORSRequestType(CorsRequestAdapter requestAdapter, b String methodName = requestAdapter.method(); boolean isMethodOPTION = methodName.equalsIgnoreCase(Http.Method.OPTIONS.text()); boolean requestContainsAccessControlRequestMethodHeader = - requestAdapter.headerContainsKey(Header.ACCESS_CONTROL_REQUEST_METHOD); + requestAdapter.headerContainsKey(Http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD); RequestType result = isMethodOPTION && requestContainsAccessControlRequestMethodHeader ? RequestType.PREFLIGHT @@ -417,7 +417,7 @@ Optional processCorsRequest( // If enabled but not whitelisted, deny request List allowedOrigins = Arrays.asList(crossOriginConfig.allowOrigins()); - Optional originOpt = requestAdapter.firstHeader(Header.ORIGIN); + Optional originOpt = requestAdapter.firstHeader(Http.HeaderNames.ORIGIN); if (!allowedOrigins.contains("*") && !contains(originOpt, allowedOrigins, CorsSupportHelper::compareOrigins)) { return Optional.of(forbid(requestAdapter, responseAdapter, @@ -443,26 +443,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(Header.ORIGIN).orElseThrow(noRequiredHeaderExcFactory(Header.ORIGIN)); + String origin = requestAdapter.firstHeader(Http.HeaderNames.ORIGIN) + .orElseThrow(noRequiredHeaderExcFactory(Http.HeaderNames.ORIGIN)); if (crossOrigin.allowCredentials()) { new Headers() - .add(Header.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true") - .add(Header.ACCESS_CONTROL_ALLOW_ORIGIN, origin) - .add(Header.VARY, Header.ORIGIN) + .add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true") + .add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin) + .add(Http.HeaderNames.VARY, Http.HeaderNames.ORIGIN) .setAndLog(responseAdapter::header, "allow-credentials was set in CORS config"); } else { List allowedOrigins = Arrays.asList(crossOrigin.allowOrigins()); new Headers() - .add(Header.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigins.contains("*") ? "*" : origin) - .add(Header.VARY, Header.ORIGIN) + .add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, allowedOrigins.contains("*") ? "*" : origin) + .add(Http.HeaderNames.VARY, Http.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(Header.ACCESS_CONTROL_EXPOSE_HEADERS, h)); + h -> headers.add(Http.HeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, h)); headers.setAndLog(responseAdapter::header, "expose-headers was set in CORS config"); } @@ -479,13 +480,13 @@ void addCorsHeadersToResponse(CrossOriginConfig crossOrigin, */ R processCorsPreFlightRequest(CorsRequestAdapter requestAdapter, CorsResponseAdapter responseAdapter) { - Optional originOpt = requestAdapter.firstHeader(Header.ORIGIN); + Optional originOpt = requestAdapter.firstHeader(HeaderNames.ORIGIN); if (originOpt.isEmpty()) { - return forbid(requestAdapter, responseAdapter, noRequiredHeader(Header.ORIGIN)); + return forbid(requestAdapter, responseAdapter, noRequiredHeader(Http.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(Header.ACCESS_CONTROL_REQUEST_METHOD).get(); + String requestedMethod = requestAdapter.firstHeader(Http.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( @@ -514,12 +515,12 @@ R processCorsPreFlightRequest(CorsRequestAdapter requestAdapter, CorsResponse responseAdapter, METHOD_NOT_IN_ALLOWED_LIST, () -> String.format("header %s requested method %s but allowedMethods is %s", - Header.ACCESS_CONTROL_REQUEST_METHOD, + HeaderNames.ACCESS_CONTROL_REQUEST_METHOD, requestedMethod, allowedMethods)); } // Check if headers are allowed - Set requestHeaders = parseHeader(requestAdapter.allHeaders(Header.ACCESS_CONTROL_REQUEST_HEADERS)); + Set requestHeaders = parseHeader(requestAdapter.allHeaders(Http.HeaderNames.ACCESS_CONTROL_REQUEST_HEADERS)); List allowedHeaders = Arrays.asList(crossOrigin.allowHeaders()); if (!allowedHeaders.contains("*") && !contains(requestHeaders, allowedHeaders)) { return forbid(requestAdapter, @@ -532,16 +533,16 @@ R processCorsPreFlightRequest(CorsRequestAdapter requestAdapter, CorsResponse // Build successful response Headers headers = new Headers() - .add(Header.ACCESS_CONTROL_ALLOW_ORIGIN, originOpt.get()); + .add(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, originOpt.get()); if (crossOrigin.allowCredentials()) { - headers.add(Header.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true", "allowCredentials config was set"); + headers.add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true", "allowCredentials config was set"); } - headers.add(Header.ACCESS_CONTROL_ALLOW_METHODS, requestedMethod); + headers.add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS, requestedMethod); formatHeader(requestHeaders.toArray()).ifPresent( - h -> headers.add(Header.ACCESS_CONTROL_ALLOW_HEADERS, h)); + h -> headers.add(Http.HeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, h)); long maxAgeSeconds = crossOrigin.maxAgeSeconds(); if (maxAgeSeconds > 0) { - headers.add(Header.ACCESS_CONTROL_MAX_AGE, maxAgeSeconds, "maxAgeSeconds > 0"); + headers.add(Http.HeaderNames.ACCESS_CONTROL_MAX_AGE, maxAgeSeconds, "maxAgeSeconds > 0"); } headers.setAndLog(responseAdapter::header, "headers set on preflight request"); return responseAdapter.ok(); diff --git a/cors/src/main/java/io/helidon/cors/LogHelper.java b/cors/src/main/java/io/helidon/cors/LogHelper.java index faa58645d01..21f0262bf49 100644 --- a/cors/src/main/java/io/helidon/cors/LogHelper.java +++ b/cors/src/main/java/io/helidon/cors/LogHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022 Oracle and/or its affiliates. + * Copyright (c) 2020, 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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.helidon.cors; import java.util.AbstractMap; @@ -29,7 +30,7 @@ import java.util.stream.Collectors; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.cors.CorsSupportHelper.RequestType; class LogHelper { @@ -77,26 +78,26 @@ static void logIsRequestTypeNormal(boolean result, boolean silent, CorsReque List factorsWhyCrossHost = new ArrayList<>(); if (originOpt.isEmpty()) { - reasonsWhyNormal.add("header " + Header.ORIGIN + " is absent"); + reasonsWhyNormal.add("header " + HeaderNames.ORIGIN + " is absent"); } else { - factorsWhyCrossHost.add(String.format("header %s is present (%s)", Header.ORIGIN, originOpt.get())); + factorsWhyCrossHost.add(String.format("header %s is present (%s)", HeaderNames.ORIGIN, originOpt.get())); } if (hostOpt.isEmpty()) { - reasonsWhyNormal.add("header " + Header.HOST + " is absent"); + reasonsWhyNormal.add("header " + HeaderNames.HOST + " is absent"); } else { - factorsWhyCrossHost.add(String.format("header %s is present (%s)", Header.HOST, hostOpt.get())); + factorsWhyCrossHost.add(String.format("header %s is present (%s)", HeaderNames.HOST, hostOpt.get())); } if (hostOpt.isPresent() && originOpt.isPresent()) { String partOfOriginMatchingHost = "://" + hostOpt.get(); if (originOpt.get() .contains(partOfOriginMatchingHost)) { - reasonsWhyNormal.add(String.format("header %s '%s' matches header %s '%s'", Header.ORIGIN, - originOpt.get(), Header.HOST, hostOpt.get())); + reasonsWhyNormal.add(String.format("header %s '%s' matches header %s '%s'", HeaderNames.ORIGIN, + originOpt.get(), HeaderNames.HOST, hostOpt.get())); } else { - factorsWhyCrossHost.add(String.format("header %s '%s' does not match header %s '%s'", Header.ORIGIN, - originOpt.get(), Header.HOST, hostOpt.get())); + factorsWhyCrossHost.add(String.format("header %s '%s' does not match header %s '%s'", HeaderNames.ORIGIN, + originOpt.get(), HeaderNames.HOST, hostOpt.get())); } } @@ -128,17 +129,18 @@ 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.name())) { - reasonsWhyCORS.add(String.format("method is %s, not %s", methodName, Http.Method.OPTIONS.name())); + if (!methodName.equalsIgnoreCase(Http.Method.OPTIONS.text())) { + reasonsWhyCORS.add(String.format("method is %s, not %s", methodName, Http.Method.OPTIONS.text())); } else { factorsWhyPreflight.add(String.format("method is %s", methodName)); } if (!requestContainsAccessControlRequestMethodHeader) { - reasonsWhyCORS.add(String.format("header %s is absent", Header.ACCESS_CONTROL_REQUEST_METHOD.defaultCase())); + reasonsWhyCORS.add(String.format("header %s is absent", HeaderNames.ACCESS_CONTROL_REQUEST_METHOD.defaultCase())); } else { - factorsWhyPreflight.add(String.format("header %s is present(%s)", Header.ACCESS_CONTROL_REQUEST_METHOD.defaultCase(), - requestAdapter.firstHeader(Header.ACCESS_CONTROL_REQUEST_METHOD))); + factorsWhyPreflight.add(String.format("header %s is present(%s)", + HeaderNames.ACCESS_CONTROL_REQUEST_METHOD.defaultCase(), + requestAdapter.firstHeader(HeaderNames.ACCESS_CONTROL_REQUEST_METHOD))); } if (CorsSupportHelper.LOGGER.isLoggable(DECISION_LEVEL)) { 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 2d44cb7e3c5..d8938bf4789 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 @@ -20,8 +20,8 @@ import java.util.Optional; import io.helidon.common.http.Headers; -import io.helidon.common.http.HttpMediaType; import io.helidon.common.http.WritableHeaders; +import io.helidon.common.media.type.MediaTypes; import io.helidon.config.Config; import io.helidon.cors.CrossOriginConfig; import io.helidon.nima.testing.junit5.webserver.ServerTest; @@ -37,11 +37,11 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; -import static io.helidon.common.http.Http.Header.ACCESS_CONTROL_ALLOW_METHODS; -import static io.helidon.common.http.Http.Header.ACCESS_CONTROL_ALLOW_ORIGIN; -import static io.helidon.common.http.Http.Header.ACCESS_CONTROL_REQUEST_METHOD; -import static io.helidon.common.http.Http.Header.HOST; -import static io.helidon.common.http.Http.Header.ORIGIN; +import static io.helidon.common.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_METHODS; +import static io.helidon.common.http.Http.HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN; +import static io.helidon.common.http.Http.HeaderNames.ACCESS_CONTROL_REQUEST_METHOD; +import static io.helidon.common.http.Http.HeaderNames.HOST; +import static io.helidon.common.http.Http.HeaderNames.ORIGIN; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.is; @@ -69,7 +69,7 @@ public static void setup(WebServerConfig.Builder server) { @Test public void testHelloWorld() { try (Http1ClientResponse response = client.get("/greet") - .accept(HttpMediaType.APPLICATION_JSON) + .accept(MediaTypes.APPLICATION_JSON) .request()) { assertThat(response.status().code(), is(200)); @@ -79,7 +79,7 @@ public void testHelloWorld() { } try (Http1ClientResponse response = client.get("/greet/Joe") - .accept(HttpMediaType.APPLICATION_JSON) + .accept(MediaTypes.APPLICATION_JSON) .request()) { assertThat(response.status().code(), is(200)); @@ -89,14 +89,14 @@ public void testHelloWorld() { } try (Http1ClientResponse response = client.put("/greet/greeting") - .accept(HttpMediaType.APPLICATION_JSON) + .accept(MediaTypes.APPLICATION_JSON) .submit(new GreetingMessage("Hola").forRest())) { assertThat(response.status().code(), is(204)); } try (Http1ClientResponse response = client.get("/greet/Jose") - .accept(HttpMediaType.APPLICATION_JSON) + .accept(MediaTypes.APPLICATION_JSON) .request()) { assertThat(response.status().code(), is(200)); @@ -120,7 +120,7 @@ public void testHelloWorld() { void testAnonymousGreetWithCors() { try (Http1ClientResponse response = client.get() .path("/greet") - .accept(HttpMediaType.APPLICATION_JSON) + .accept(MediaTypes.APPLICATION_JSON) .headers(it -> it .set(ORIGIN, "http://foo.com") .set(HOST, "here.com")) @@ -165,7 +165,7 @@ void testGreetingChangeWithCors() { // Send the follow-up request. GreetingMessage payload = new GreetingMessage("Cheers"); try (Http1ClientResponse response = client.put("/greet/greeting") - .accept(HttpMediaType.APPLICATION_JSON) + .accept(MediaTypes.APPLICATION_JSON) .headers(headers -> { headers.set(ORIGIN, "http://foo.com"); headers.set(HOST, "here.com"); 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 17301b5819d..a728a0de80d 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 @@ -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.Header.CONTENT_DISPOSITION.defaultCase(), "attachment; filename=\"" + fileName + "\"") + .header(Http.HeaderNames.CONTENT_DISPOSITION.defaultCase(), "attachment; filename=\"" + fileName + "\"") .header("opc-request-id", getObjectResponse.getOpcRequestId()) .header("request-id", getObjectResponse.getOpcClientRequestId()) - .header(Http.Header.CONTENT_LENGTH.defaultCase(), getObjectResponse.getContentLength()); + .header(Http.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 e8c778880f0..fa20a88b0b8 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 @@ -109,9 +109,9 @@ public void download(ServerRequest request, ServerResponse response) { byte[] objectContent = fileStream.readAllBytes(); response .status(Http.Status.OK_200) - .header(Http.Header.CONTENT_DISPOSITION.defaultCase(), "attachment; filename=\"" + fileName + "\"") + .header(Http.HeaderNames.CONTENT_DISPOSITION.defaultCase(), "attachment; filename=\"" + fileName + "\"") .header("opc-request-id", getObjectResponse.getOpcRequestId()) - .header(Http.Header.CONTENT_LENGTH.defaultCase(), getObjectResponse.getContentLength().toString()); + .header(Http.HeaderNames.CONTENT_LENGTH.defaultCase(), getObjectResponse.getContentLength().toString()); response.send(objectContent); } catch (IOException e) { 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 2b3b4d5cce9..dbe924a515d 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 @@ -49,7 +49,7 @@ * File service. */ public final class FileService implements HttpService { - private static final Http.HeaderValue UI_LOCATION = Http.Header.createCached(Http.Header.LOCATION, "/ui"); + private static final Http.Header UI_LOCATION = Http.Headers.createCached(Http.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 f88d7b44342..b2cf6d92680 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 @@ -24,7 +24,7 @@ * This application provides a simple file upload service with a UI to exercise multipart. */ public final class Main { - private static final Http.HeaderValue UI_LOCATION = Http.Header.createCached(Http.Header.LOCATION, "/ui"); + private static final Http.Header UI_LOCATION = Http.Headers.createCached(Http.HeaderNames.LOCATION, "/ui"); private Main() { } 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 07e04c5bc9f..5694e2274ec 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 @@ -109,7 +109,7 @@ public void testList() { 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.Header.CONTENT_DISPOSITION).orElse(null), + assertThat(response.headers().first(Http.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/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 0bbc6e6b6b4..450f7a6a3e8 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 @@ -16,7 +16,7 @@ package io.helidon.examples.se.httpstatuscount; import io.helidon.common.http.Http.Status; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.media.type.MediaTypes; import io.helidon.config.Config; import io.helidon.metrics.api.RegistryFactory; import io.helidon.nima.testing.junit5.webserver.ServerTest; @@ -85,7 +85,7 @@ void checkStatusAfterGreet() throws InterruptedException { before[i] = STATUS_COUNTERS[i].getCount(); } try (Http1ClientResponse response = client.get("/greet") - .accept(HttpMediaType.APPLICATION_JSON) + .accept(MediaTypes.APPLICATION_JSON) .request()) { assertThat("Status of /greet", response.status(), is(Status.OK_200)); String entity = response.as(String.class); @@ -100,7 +100,7 @@ void checkAfterStatus(Status status) throws InterruptedException { before[i] = STATUS_COUNTERS[i].getCount(); } try (Http1ClientResponse response = client.get("/status/" + status.code()) - .accept(HttpMediaType.APPLICATION_JSON) + .accept(MediaTypes.APPLICATION_JSON) .request()) { assertThat("Response status", response.status(), is(status)); checkCounters(status, before); 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 e925d97bed0..e38a4fb0dc7 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 @@ -21,11 +21,10 @@ import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.Http.HeaderNames; +import io.helidon.common.media.type.MediaTypes; import io.helidon.config.Config; import io.helidon.microprofile.server.Server; -import io.helidon.nima.http.media.MediaContext; import io.helidon.nima.http.media.jsonp.JsonpSupport; import io.helidon.nima.webclient.http1.Http1Client; import io.helidon.nima.webclient.http1.Http1ClientRequest; @@ -118,15 +117,15 @@ public void testHelloWorld() { @Test void testAnonymousGreetWithCors() { Http1ClientRequest req = client.get() - .header(Header.ORIGIN, "http://foo.com") - .header(Header.HOST, "here.com"); + .header(HeaderNames.ORIGIN, "http://foo.com") + .header(HeaderNames.HOST, "here.com"); Http1ClientResponse r = getResponse("/greet", req); assertThat("HTTP response", r.status().code(), is(200)); String payload = fromPayload(r); assertThat("HTTP response payload", payload, is("Hola World!")); Headers responseHeaders = r.headers(); - Optional allowOrigin = responseHeaders.value(Header.ACCESS_CONTROL_ALLOW_ORIGIN); + Optional allowOrigin = responseHeaders.value(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat("Expected CORS header " + ACCESS_CONTROL_ALLOW_ORIGIN + " is present", allowOrigin.isPresent(), is(true)); assertThat("CORS header " + ACCESS_CONTROL_ALLOW_ORIGIN, allowOrigin.get(), is("*")); @@ -139,9 +138,9 @@ void testGreetingChangeWithCors() { // Send the pre-flight request and check the response. Http1ClientRequest req = client.method(Http.Method.OPTIONS) - .header(Header.ORIGIN, "http://foo.com") - .header(Header.HOST, "here.com") - .header(Header.ACCESS_CONTROL_REQUEST_METHOD, "PUT"); + .header(HeaderNames.ORIGIN, "http://foo.com") + .header(Http.HeaderNames.HOST, "here.com") + .header(HeaderNames.ACCESS_CONTROL_REQUEST_METHOD, "PUT"); List allowOrigins; Headers responseHeaders; @@ -151,11 +150,11 @@ void testGreetingChangeWithCors() { preflightResponseHeaders = res.headers(); } - List allowMethods = preflightResponseHeaders.values(Header.ACCESS_CONTROL_ALLOW_METHODS); + List allowMethods = preflightResponseHeaders.values(HeaderNames.ACCESS_CONTROL_ALLOW_METHODS); assertThat("pre-flight response check for " + ACCESS_CONTROL_ALLOW_METHODS, allowMethods, is(not(empty()))); assertThat("Header " + ACCESS_CONTROL_ALLOW_METHODS, allowMethods, contains("PUT")); - allowOrigins = preflightResponseHeaders.values(Header.ACCESS_CONTROL_ALLOW_ORIGIN); + allowOrigins = preflightResponseHeaders.values(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat("pre-flight response check for " + ACCESS_CONTROL_ALLOW_ORIGIN, allowOrigins, is(not(empty()))); assertThat("Header " + ACCESS_CONTROL_ALLOW_ORIGIN, allowOrigins, contains("http://foo.com")); @@ -163,8 +162,8 @@ void testGreetingChangeWithCors() { // Send the follow-up request. req = client.put() - .header(Header.ORIGIN, "http://foo.com") - .header(Header.HOST, "here.com"); + .header(HeaderNames.ORIGIN, "http://foo.com") + .header(HeaderNames.HOST, "here.com"); preflightResponseHeaders.forEach(req.headers()::add); try (Http1ClientResponse res = putResponse("/greet/greeting", "Cheers", req)) { @@ -172,7 +171,7 @@ void testGreetingChangeWithCors() { responseHeaders = res.headers(); } - allowOrigins = responseHeaders.values(Header.ACCESS_CONTROL_ALLOW_ORIGIN); + allowOrigins = responseHeaders.values(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat("Expected CORS header " + ACCESS_CONTROL_ALLOW_ORIGIN, allowOrigins, is(not(empty()))); assertThat("Header " + ACCESS_CONTROL_ALLOW_ORIGIN, allowOrigins, contains("http://foo.com")); } @@ -181,14 +180,14 @@ void testGreetingChangeWithCors() { @Test void testNamedGreetWithCors() { Http1ClientRequest req = client.get() - .header(Header.ORIGIN, "http://foo.com") - .header(Header.HOST, "here.com"); + .header(HeaderNames.ORIGIN, "http://foo.com") + .header(HeaderNames.HOST, "here.com"); Http1ClientResponse r = getResponse("/greet/Maria", req); assertThat("HTTP response", r.status().code(), is(200)); assertThat(fromPayload(r), containsString("Cheers Maria")); Headers responseHeaders = r.headers(); - Optional allowOrigin = responseHeaders.value(Header.ACCESS_CONTROL_ALLOW_ORIGIN); + Optional allowOrigin = responseHeaders.value(HeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN); assertThat("Expected CORS header " + ACCESS_CONTROL_ALLOW_ORIGIN + " presence check", allowOrigin.isPresent(), is(true)); assertThat(allowOrigin.get(), is("*")); } @@ -197,8 +196,8 @@ void testNamedGreetWithCors() { @Test void testGreetingChangeWithCorsAndOtherOrigin() { Http1ClientRequest req = client.put() - .header(Header.ORIGIN, "http://foo.com") - .header(Header.HOST, "here.com"); + .header(HeaderNames.ORIGIN, "http://foo.com") + .header(HeaderNames.HOST, "here.com"); try (Http1ClientResponse r = putResponse("/greet/greeting", "Ahoy", req)) { // Result depends on whether we are using overrides or not. @@ -213,7 +212,7 @@ private static Http1ClientResponse getResponse(String path) { } private static Http1ClientResponse getResponse(String path, Http1ClientRequest builder) { - return builder.accept(HttpMediaType.APPLICATION_JSON) + return builder.accept(MediaTypes.APPLICATION_JSON) .path(path) .request(); } @@ -234,7 +233,7 @@ private static Http1ClientResponse putResponse(String path, String message) { } private static Http1ClientResponse putResponse(String path, String message, Http1ClientRequest builder) { - return builder.accept(HttpMediaType.APPLICATION_JSON) + return builder.accept(MediaTypes.APPLICATION_JSON) .path(path) .submit(toPayload(message)); } diff --git a/examples/nima/echo/src/main/java/io/helidon/examples/nima/echo/EchoClient.java b/examples/nima/echo/src/main/java/io/helidon/examples/nima/echo/EchoClient.java index 7ada6a9d397..baa4e86a060 100644 --- a/examples/nima/echo/src/main/java/io/helidon/examples/nima/echo/EchoClient.java +++ b/examples/nima/echo/src/main/java/io/helidon/examples/nima/echo/EchoClient.java @@ -17,8 +17,8 @@ package io.helidon.examples.nima.echo; import io.helidon.common.http.Headers; +import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; import io.helidon.nima.webclient.api.HttpClientRequest; import io.helidon.nima.webclient.api.HttpClientResponse; import io.helidon.nima.webclient.api.WebClient; @@ -27,8 +27,8 @@ * A client that invokes the echo server. */ public class EchoClient { - private static final HeaderValue HEADER = Header.create(Header.create("MY-HEADER"), "header-value"); - private static final HeaderValue HEADERS = Header.create(Header.create("MY-HEADERS"), "ha", "hb", "hc"); + 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 EchoClient() { } @@ -52,7 +52,7 @@ public static void main(String[] args) { .request()) { Headers headers = response.headers(); - for (HeaderValue header : headers) { + for (Http.Header header : headers) { System.out.println("Header: " + header.name() + "=" + header.value()); } System.out.println("Entity:"); diff --git a/examples/nima/echo/src/main/java/io/helidon/examples/nima/echo/EchoMain.java b/examples/nima/echo/src/main/java/io/helidon/examples/nima/echo/EchoMain.java index f993e0328f8..5153679580b 100644 --- a/examples/nima/echo/src/main/java/io/helidon/examples/nima/echo/EchoMain.java +++ b/examples/nima/echo/src/main/java/io/helidon/examples/nima/echo/EchoMain.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -76,7 +76,7 @@ private static void echo(ServerRequest req, ServerResponse res) { res.header("R-QUERY_" + queryName, query.all(queryName).toString()); } - for (Http.HeaderValue header : headers) { + for (Http.Header header : headers) { res.header("R-" + header.name(), header.allValues().toString()); } diff --git a/examples/nima/fault-tolerance/src/main/java/io/helidon/examples/nima/faulttolerance/GreetEndpoint.java b/examples/nima/fault-tolerance/src/main/java/io/helidon/examples/nima/faulttolerance/GreetEndpoint.java index e41037e6a2f..407481f791c 100644 --- a/examples/nima/fault-tolerance/src/main/java/io/helidon/examples/nima/faulttolerance/GreetEndpoint.java +++ b/examples/nima/fault-tolerance/src/main/java/io/helidon/examples/nima/faulttolerance/GreetEndpoint.java @@ -54,7 +54,7 @@ String greet() { @FaultTolerance.Bulkhead(name = "bulkhead-it") String greetNamed(@Endpoint.PathParam("name") String name, @Endpoint.QueryParam(value = "throw", defaultValue = "false") String shouldThrow, - @Endpoint.HeaderParam(Http.Header.HOST_STRING) String hostHeader) { + @Endpoint.HeaderParam(Http.HeaderNames.HOST_STRING) String hostHeader) { if ("true".equalsIgnoreCase(shouldThrow)) { throw new InjectionException("Failed on purpose"); } diff --git a/examples/nima/media/src/main/java/io/helidon/examples/nima/media/FileService.java b/examples/nima/media/src/main/java/io/helidon/examples/nima/media/FileService.java index 8df54f84193..ee1b0fbf565 100644 --- a/examples/nima/media/src/main/java/io/helidon/examples/nima/media/FileService.java +++ b/examples/nima/media/src/main/java/io/helidon/examples/nima/media/FileService.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022 Oracle and/or its affiliates. + * Copyright (c) 2020, 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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.helidon.examples.nima.media; import java.io.IOException; @@ -26,7 +27,7 @@ import io.helidon.common.http.ContentDisposition; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.ServerResponseHeaders; import io.helidon.common.media.type.MediaTypes; import io.helidon.nima.http.media.multipart.MultiPart; @@ -48,7 +49,7 @@ * File service. */ final class FileService implements HttpService { - private static final Http.HeaderValue UI_LOCATION = Header.createCached(Header.LOCATION, "/ui"); + private static final Http.Header UI_LOCATION = Http.Headers.createCached(HeaderNames.LOCATION, "/ui"); private final JsonBuilderFactory jsonFactory; private final Path storage; diff --git a/examples/nima/media/src/main/java/io/helidon/examples/nima/media/MediaMain.java b/examples/nima/media/src/main/java/io/helidon/examples/nima/media/MediaMain.java index 3b8931655c8..dac375c2f78 100644 --- a/examples/nima/media/src/main/java/io/helidon/examples/nima/media/MediaMain.java +++ b/examples/nima/media/src/main/java/io/helidon/examples/nima/media/MediaMain.java @@ -17,7 +17,7 @@ package io.helidon.examples.nima.media; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.nima.webserver.WebServer; import io.helidon.nima.webserver.http.HttpRules; import io.helidon.nima.webserver.staticcontent.StaticContentService; @@ -26,7 +26,7 @@ * This application provides a simple file upload service with a UI to exercise multipart. */ public class MediaMain { - private static final Http.HeaderValue UI_LOCATION = Header.createCached(Header.LOCATION, "/ui"); + private static final Http.Header UI_LOCATION = Http.Headers.createCached(HeaderNames.LOCATION, "/ui"); private MediaMain() { } diff --git a/examples/security/basic-auth-with-static-content/src/main/java/io/helidon/security/examples/webserver/basic/BasicExampleBuilderMain.java b/examples/security/basic-auth-with-static-content/src/main/java/io/helidon/security/examples/webserver/basic/BasicExampleBuilderMain.java index b22bcd8e3fc..14610b49cac 100644 --- a/examples/security/basic-auth-with-static-content/src/main/java/io/helidon/security/examples/webserver/basic/BasicExampleBuilderMain.java +++ b/examples/security/basic-auth-with-static-content/src/main/java/io/helidon/security/examples/webserver/basic/BasicExampleBuilderMain.java @@ -23,7 +23,7 @@ import java.util.Set; import java.util.concurrent.TimeUnit; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.logging.common.LogConfig; import io.helidon.nima.webserver.WebServer; import io.helidon.nima.webserver.WebServerConfig; @@ -112,7 +112,7 @@ static void setup(WebServerConfig.Builder server) { .audit()) .get("/{*}", (req, res) -> { Optional securityContext = req.context().get(SecurityContext.class); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Hello, you are: \n" + securityContext .map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()) .orElse("Security context is null")); diff --git a/examples/security/basic-auth-with-static-content/src/main/java/io/helidon/security/examples/webserver/basic/BasicExampleConfigMain.java b/examples/security/basic-auth-with-static-content/src/main/java/io/helidon/security/examples/webserver/basic/BasicExampleConfigMain.java index ad82bd92bd9..e42e6b3a5da 100644 --- a/examples/security/basic-auth-with-static-content/src/main/java/io/helidon/security/examples/webserver/basic/BasicExampleConfigMain.java +++ b/examples/security/basic-auth-with-static-content/src/main/java/io/helidon/security/examples/webserver/basic/BasicExampleConfigMain.java @@ -19,7 +19,7 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.config.Config; import io.helidon.logging.common.LogConfig; import io.helidon.nima.webserver.WebServer; @@ -89,7 +89,7 @@ static void setup(WebServerConfig.Builder server) { .register("/static", StaticContentService.create("/WEB")) .get("/{*}", (req, res) -> { Optional securityContext = req.context().get(SecurityContext.class); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Hello, you are: \n" + securityContext .map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()) .orElse("Security context is null")); diff --git a/examples/security/basic-auth-with-static-content/src/test/java/io/helidon/security/examples/webserver/basic/BasicExampleTest.java b/examples/security/basic-auth-with-static-content/src/test/java/io/helidon/security/examples/webserver/basic/BasicExampleTest.java index 82da7e1fb75..a03b29ce75e 100644 --- a/examples/security/basic-auth-with-static-content/src/test/java/io/helidon/security/examples/webserver/basic/BasicExampleTest.java +++ b/examples/security/basic-auth-with-static-content/src/test/java/io/helidon/security/examples/webserver/basic/BasicExampleTest.java @@ -130,7 +130,7 @@ private void testNotAuthorized(String uri) { try (Http1ClientResponse response = client.get().uri(uri).request()) { assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); - String header = response.headers().get(Http.Header.WWW_AUTHENTICATE).value(); + String header = response.headers().get(Http.HeaderNames.WWW_AUTHENTICATE).value(); assertThat(header.toLowerCase(), containsString("basic")); assertThat(header, containsString("helidon")); diff --git a/examples/security/google-login/src/main/java/io/helidon/security/examples/google/GoogleBuilderMain.java b/examples/security/google-login/src/main/java/io/helidon/security/examples/google/GoogleBuilderMain.java index 201bf5fc992..361c4c5f1e3 100644 --- a/examples/security/google-login/src/main/java/io/helidon/security/examples/google/GoogleBuilderMain.java +++ b/examples/security/google-login/src/main/java/io/helidon/security/examples/google/GoogleBuilderMain.java @@ -19,7 +19,7 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.logging.common.LogConfig; import io.helidon.nima.webserver.WebServer; import io.helidon.nima.webserver.WebServerConfig; @@ -77,7 +77,7 @@ static void setup(WebServerConfig.Builder server) { .get("/rest/profile", SecurityFeature.authenticate(), (req, res) -> { Optional securityContext = req.context().get(SecurityContext.class); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Response from builder based service, you are: \n" + securityContext .flatMap(SecurityContext::user) .map(Subject::toString) diff --git a/examples/security/google-login/src/main/java/io/helidon/security/examples/google/GoogleConfigMain.java b/examples/security/google-login/src/main/java/io/helidon/security/examples/google/GoogleConfigMain.java index d7cd549a3c1..29b281d181a 100644 --- a/examples/security/google-login/src/main/java/io/helidon/security/examples/google/GoogleConfigMain.java +++ b/examples/security/google-login/src/main/java/io/helidon/security/examples/google/GoogleConfigMain.java @@ -19,7 +19,7 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.config.Config; import io.helidon.logging.common.LogConfig; import io.helidon.nima.webserver.WebServer; @@ -85,7 +85,7 @@ static void setup(WebServerConfig.Builder server) { .addFeature(SecurityFeature.create(config.get("security"))) .get("/rest/profile", (req, res) -> { Optional securityContext = req.context().get(SecurityContext.class); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Response from config based service, you are: \n" + securityContext .flatMap(SecurityContext::user) .map(Subject::toString) diff --git a/examples/security/google-login/src/test/java/io/helidon/security/examples/google/GoogleMainTest.java b/examples/security/google-login/src/test/java/io/helidon/security/examples/google/GoogleMainTest.java index 382c4c6b9d7..3d8827ac72d 100644 --- a/examples/security/google-login/src/test/java/io/helidon/security/examples/google/GoogleMainTest.java +++ b/examples/security/google-login/src/test/java/io/helidon/security/examples/google/GoogleMainTest.java @@ -41,7 +41,7 @@ public void testEndpoint() { try (Http1ClientResponse response = client.get("/rest/profile").request()) { assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); - assertThat(response.headers().first(Http.Header.WWW_AUTHENTICATE), + assertThat(response.headers().first(Http.HeaderNames.WWW_AUTHENTICATE), optionalValue(is("Bearer realm=\"helidon\",scope=\"openid profile email\""))); } } diff --git a/examples/security/idcs-login/src/main/java/io/helidon/security/examples/idcs/IdcsBuilderMain.java b/examples/security/idcs-login/src/main/java/io/helidon/security/examples/idcs/IdcsBuilderMain.java index d06ee210fba..ec45a0d3bd4 100644 --- a/examples/security/idcs-login/src/main/java/io/helidon/security/examples/idcs/IdcsBuilderMain.java +++ b/examples/security/idcs-login/src/main/java/io/helidon/security/examples/idcs/IdcsBuilderMain.java @@ -20,7 +20,7 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.config.Config; import io.helidon.logging.common.LogConfig; import io.helidon.nima.webserver.WebServer; @@ -105,7 +105,7 @@ static void setup(WebServerConfig.Builder server) { // web server does not (yet) have possibility to configure routes in config files, so explicit... .get("/rest/profile", (req, res) -> { Optional securityContext = req.context().get(SecurityContext.class); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Response from builder based service, you are: \n" + securityContext .flatMap(SecurityContext::user) .map(Subject::toString) diff --git a/examples/security/idcs-login/src/main/java/io/helidon/security/examples/idcs/IdcsMain.java b/examples/security/idcs-login/src/main/java/io/helidon/security/examples/idcs/IdcsMain.java index 49c620491b1..7a60b6b3dab 100644 --- a/examples/security/idcs-login/src/main/java/io/helidon/security/examples/idcs/IdcsMain.java +++ b/examples/security/idcs-login/src/main/java/io/helidon/security/examples/idcs/IdcsMain.java @@ -20,7 +20,7 @@ import java.util.concurrent.TimeUnit; import io.helidon.common.context.Contexts; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.config.Config; import io.helidon.logging.common.LogConfig; import io.helidon.nima.webserver.WebServer; @@ -83,7 +83,7 @@ static void setup(WebServerConfig.Builder server) { // web server does not (yet) have possibility to configure routes in config files, so explicit... .get("/rest/profile", (req, res) -> { Optional securityContext = req.context().get(SecurityContext.class); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Response from config based service, you are: \n" + securityContext .flatMap(SecurityContext::user) .map(Subject::toString) 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 a114b713e3d..06ad02c5ccd 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 @@ -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.Header.AUTHORIZATION) + req.headers().first(Http.HeaderNames.AUTHORIZATION) .ifPresent(System.out::println); String username = req.context() diff --git a/examples/security/webserver-digest-auth/src/main/java/io/helidon/security/examples/webserver/digest/DigestExampleBuilderMain.java b/examples/security/webserver-digest-auth/src/main/java/io/helidon/security/examples/webserver/digest/DigestExampleBuilderMain.java index fc5867db6cd..d362b722ec5 100644 --- a/examples/security/webserver-digest-auth/src/main/java/io/helidon/security/examples/webserver/digest/DigestExampleBuilderMain.java +++ b/examples/security/webserver-digest-auth/src/main/java/io/helidon/security/examples/webserver/digest/DigestExampleBuilderMain.java @@ -26,7 +26,7 @@ import java.util.Set; import java.util.concurrent.TimeUnit; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.logging.common.LogConfig; import io.helidon.nima.webserver.WebServer; import io.helidon.nima.webserver.WebServerConfig; @@ -113,7 +113,7 @@ static void setup(WebServerConfig.Builder server) { .audit()) .get("/{*}", (req, res) -> { Optional securityContext = req.context().get(SecurityContext.class); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Hello, you are: \n" + securityContext .map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()) .orElse("Security context is null")); diff --git a/examples/security/webserver-digest-auth/src/main/java/io/helidon/security/examples/webserver/digest/DigestExampleConfigMain.java b/examples/security/webserver-digest-auth/src/main/java/io/helidon/security/examples/webserver/digest/DigestExampleConfigMain.java index ccd28a3c45d..9daa2074eff 100644 --- a/examples/security/webserver-digest-auth/src/main/java/io/helidon/security/examples/webserver/digest/DigestExampleConfigMain.java +++ b/examples/security/webserver-digest-auth/src/main/java/io/helidon/security/examples/webserver/digest/DigestExampleConfigMain.java @@ -19,7 +19,7 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.config.Config; import io.helidon.logging.common.LogConfig; import io.helidon.nima.webserver.WebServer; @@ -85,7 +85,7 @@ static void setup(WebServerConfig.Builder server) { // web server does not (yet) have possibility to configure routes in config files, so explicit... .get("/{*}", (req, res) -> { Optional securityContext = req.context().get(SecurityContext.class); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Hello, you are: \n" + securityContext .map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()) .orElse("Security context is null")); diff --git a/examples/security/webserver-digest-auth/src/test/java/io/helidon/security/examples/webserver/digest/DigestExampleTest.java b/examples/security/webserver-digest-auth/src/test/java/io/helidon/security/examples/webserver/digest/DigestExampleTest.java index 7a67b9796e5..8cd110cdec7 100644 --- a/examples/security/webserver-digest-auth/src/test/java/io/helidon/security/examples/webserver/digest/DigestExampleTest.java +++ b/examples/security/webserver-digest-auth/src/test/java/io/helidon/security/examples/webserver/digest/DigestExampleTest.java @@ -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.Header.create("WWW-Authenticate")).orElse(null); + String header = response.headers().first(Http.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/security/examples/webserver/digest/WebClientAuthenticationService.java b/examples/security/webserver-digest-auth/src/test/java/io/helidon/security/examples/webserver/digest/WebClientAuthenticationService.java index 26f04793d40..45fb6fbebba 100644 --- a/examples/security/webserver-digest-auth/src/test/java/io/helidon/security/examples/webserver/digest/WebClientAuthenticationService.java +++ b/examples/security/webserver-digest-auth/src/test/java/io/helidon/security/examples/webserver/digest/WebClientAuthenticationService.java @@ -52,7 +52,7 @@ public WebClientServiceResponse handle(Chain chain, WebClientServiceRequest requ if (username == null || password == null) { return response; } - String challenge = response.headers().first(Http.Header.WWW_AUTHENTICATE).orElse(null); + String challenge = response.headers().first(Http.HeaderNames.WWW_AUTHENTICATE).orElse(null); if (challenge == null) { return response; } @@ -62,7 +62,7 @@ public WebClientServiceResponse handle(Chain chain, WebClientServiceRequest requ if (atz == null) { return response; } - request.headers().add(Http.Header.AUTHORIZATION, atz); + request.headers().add(Http.HeaderNames.AUTHORIZATION, atz); return chain.proceed(request); } } diff --git a/examples/security/webserver-signatures/src/main/java/io/helidon/security/examples/signatures/Service1.java b/examples/security/webserver-signatures/src/main/java/io/helidon/security/examples/signatures/Service1.java index 8ff551fd7f4..bc4f8a91fd3 100644 --- a/examples/security/webserver-signatures/src/main/java/io/helidon/security/examples/signatures/Service1.java +++ b/examples/security/webserver-signatures/src/main/java/io/helidon/security/examples/signatures/Service1.java @@ -18,7 +18,7 @@ import io.helidon.common.LazyValue; import io.helidon.common.context.Contexts; import io.helidon.common.http.Http; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.nima.webclient.http1.Http1Client; import io.helidon.nima.webclient.http1.Http1ClientResponse; import io.helidon.nima.webserver.WebServer; @@ -52,7 +52,7 @@ private void service1Rsa(ServerRequest req, ServerResponse res) { } private void handle(ServerRequest req, ServerResponse res, String path) { - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); req.context() .get(SecurityContext.class) .ifPresentOrElse(context -> { diff --git a/examples/security/webserver-signatures/src/main/java/io/helidon/security/examples/signatures/Service2.java b/examples/security/webserver-signatures/src/main/java/io/helidon/security/examples/signatures/Service2.java index 6ee68423db0..6c5e1a76cfb 100644 --- a/examples/security/webserver-signatures/src/main/java/io/helidon/security/examples/signatures/Service2.java +++ b/examples/security/webserver-signatures/src/main/java/io/helidon/security/examples/signatures/Service2.java @@ -17,7 +17,7 @@ import java.util.Optional; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.nima.webserver.http.HttpRules; import io.helidon.nima.webserver.http.HttpService; import io.helidon.nima.webserver.http.ServerRequest; @@ -34,7 +34,7 @@ public void routing(HttpRules rules) { private void handle(ServerRequest req, ServerResponse res) { Optional securityContext = req.context().get(SecurityContext.class); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Response from service2, you are: \n" + securityContext .flatMap(SecurityContext::user) .map(Subject::toString) diff --git a/examples/todo-app/backend/src/test/java/io/helidon/demo/todos/backend/BackendTests.java b/examples/todo-app/backend/src/test/java/io/helidon/demo/todos/backend/BackendTests.java index 388e80c3461..519b6b6d86a 100644 --- a/examples/todo-app/backend/src/test/java/io/helidon/demo/todos/backend/BackendTests.java +++ b/examples/todo-app/backend/src/test/java/io/helidon/demo/todos/backend/BackendTests.java @@ -113,7 +113,7 @@ void testTodoScenario() { JsonObject returnedTodo = webTarget .path("/api/backend") .request(MediaType.APPLICATION_JSON_TYPE) - .header(Http.Header.AUTHORIZATION.defaultCase(), basicAuth) + .header(Http.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.Header.AUTHORIZATION.defaultCase(), basicAuth) + .header(Http.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.Header.AUTHORIZATION.defaultCase(), basicAuth) + .header(Http.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.Header.AUTHORIZATION.defaultCase(), basicAuth) + .header(Http.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.Header.AUTHORIZATION.defaultCase(), basicAuth) + .header(Http.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/test/java/io/helidon/demo/todos/frontend/FrontendTest.java b/examples/todo-app/frontend/src/test/java/io/helidon/demo/todos/frontend/FrontendTest.java index c8868d81c48..293b6398b28 100644 --- a/examples/todo-app/frontend/src/test/java/io/helidon/demo/todos/frontend/FrontendTest.java +++ b/examples/todo-app/frontend/src/test/java/io/helidon/demo/todos/frontend/FrontendTest.java @@ -39,7 +39,6 @@ import org.junit.jupiter.api.Test; import static io.helidon.config.ConfigSources.classpath; - import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -89,7 +88,7 @@ public void routing(HttpRules rules) { @Test public void testGetList() { try (Http1ClientResponse response = client.get("/api/todo") - .header(Http.Header.AUTHORIZATION, "Basic " + ENCODED_ID) + .header(Http.HeaderNames.AUTHORIZATION, "Basic " + ENCODED_ID) .request()) { assertThat(response.status().code(), is(200)); @@ -100,7 +99,7 @@ public void testGetList() { @Test public void testPostTodo() { try (Http1ClientResponse response = client.post("/api/todo") - .header(Http.Header.AUTHORIZATION, "Basic " + ENCODED_ID) + .header(Http.HeaderNames.AUTHORIZATION, "Basic " + ENCODED_ID) .submit(TODO)) { assertThat(response.status().code(), is(200)); @@ -111,7 +110,7 @@ public void testPostTodo() { @Test public void testGetTodo() { try (Http1ClientResponse response = client.get("/api/todo/1") - .header(Http.Header.AUTHORIZATION, "Basic " + ENCODED_ID) + .header(Http.HeaderNames.AUTHORIZATION, "Basic " + ENCODED_ID) .request()) { assertThat(response.status().code(), is(200)); @@ -122,7 +121,7 @@ public void testGetTodo() { @Test public void testDeleteTodo() { try (Http1ClientResponse response = client.delete("/api/todo/1") - .header(Http.Header.AUTHORIZATION, "Basic " + ENCODED_ID) + .header(Http.HeaderNames.AUTHORIZATION, "Basic " + ENCODED_ID) .request()) { assertThat(response.status().code(), is(200)); @@ -133,7 +132,7 @@ public void testDeleteTodo() { @Test public void testUpdateTodo() { try (Http1ClientResponse response = client.put("/api/todo/1") - .header(Http.Header.AUTHORIZATION, "Basic " + ENCODED_ID) + .header(Http.HeaderNames.AUTHORIZATION, "Basic " + ENCODED_ID) .submit(TODO)) { assertThat(response.status().code(), is(200)); 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 3a85a1a0ae6..ba491764fda 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 @@ -92,7 +92,7 @@ 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.Header.LOCATION, "http://localhost:" + port + "/greet/"); + response.headers().add(Http.HeaderNames.LOCATION, "http://localhost:" + port + "/greet/"); response.status(Http.Status.MOVED_PERMANENTLY_301).send(); } diff --git a/examples/webserver/basics/src/main/java/io/helidon/webserver/examples/basics/Main.java b/examples/webserver/basics/src/main/java/io/helidon/webserver/examples/basics/Main.java index 65b8c639cc3..c6c69b99768 100644 --- a/examples/webserver/basics/src/main/java/io/helidon/webserver/examples/basics/Main.java +++ b/examples/webserver/basics/src/main/java/io/helidon/webserver/examples/basics/Main.java @@ -27,7 +27,6 @@ import io.helidon.common.http.Http; import io.helidon.common.http.HttpException; -import io.helidon.common.http.HttpMediaType; import io.helidon.common.http.ServerRequestHeaders; import io.helidon.common.media.type.MediaTypes; import io.helidon.nima.http.media.EntityReader; @@ -63,8 +62,8 @@ public class Main { private static final JsonBuilderFactory JSON = Json.createBuilderFactory(Collections.emptyMap()); - private static final Http.HeaderName BAR_HEADER = Http.Header.create("bar"); - private static final Http.HeaderName FOO_HEADER = Http.Header.create("foo"); + private static final Http.HeaderName BAR_HEADER = Http.HeaderNames.create("bar"); + private static final Http.HeaderName FOO_HEADER = Http.HeaderNames.create("foo"); // ---------------- EXAMPLES @@ -160,7 +159,7 @@ public static void parametersAndHeaders(HttpRouting.Builder routing) { public static void advancedRouting(HttpRouting.Builder routing) { routing.get("/advancedRouting/foo", (req, res) -> { ServerRequestHeaders headers = req.headers(); - if (headers.isAccepted(HttpMediaType.TEXT_PLAIN) + if (headers.isAccepted(MediaTypes.TEXT_PLAIN) && headers.contains(BAR_HEADER)) { res.send(); diff --git a/examples/webserver/basics/src/test/java/io/helidon/webserver/examples/basics/MainTest.java b/examples/webserver/basics/src/test/java/io/helidon/webserver/examples/basics/MainTest.java index 9f98843bafc..5689d5058fa 100644 --- a/examples/webserver/basics/src/test/java/io/helidon/webserver/examples/basics/MainTest.java +++ b/examples/webserver/basics/src/test/java/io/helidon/webserver/examples/basics/MainTest.java @@ -17,7 +17,6 @@ package io.helidon.webserver.examples.basics; import io.helidon.common.http.Http; -import io.helidon.common.http.HttpMediaType; import io.helidon.common.media.type.MediaTypes; import io.helidon.nima.http.media.MediaContext; import io.helidon.nima.http.media.MediaContextConfig; @@ -41,7 +40,7 @@ @ServerTest public class MainTest { - private static final Http.HeaderName FOO_HEADER = Http.Header.create("foo"); + private static final Http.HeaderName FOO_HEADER = Http.HeaderNames.create("foo"); private final Http1Client client; @@ -147,7 +146,7 @@ public void mediaReader() { // Unsupported Content-Type try (Http1ClientResponse response = client.post("/mediaReader/create-record") - .contentType(HttpMediaType.TEXT_PLAIN) + .contentType(MediaTypes.TEXT_PLAIN) .submit("John Smith")) { assertThat(response.status(), is(INTERNAL_SERVER_ERROR_500)); } @@ -158,7 +157,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.Header.CONTENT_TYPE).orElse(null), is(MediaTypes.TEXT_HTML.text())); + assertThat(response.headers().first(Http.HeaderNames.CONTENT_TYPE).orElse(null), is(MediaTypes.TEXT_HTML.text())); } // JSON @@ -172,7 +171,7 @@ public void supports() { public void errorHandling() { // Valid try (Http1ClientResponse response = client.post("/errorHandling/compute") - .contentType(HttpMediaType.TEXT_PLAIN) + .contentType(MediaTypes.TEXT_PLAIN) .submit("2")) { assertThat(response.status(), is(OK_200)); assertThat(response.entity().as(String.class), is("100 / 2 = 50")); @@ -180,14 +179,14 @@ public void errorHandling() { // Zero try (Http1ClientResponse response = client.post("/errorHandling/compute") - .contentType(HttpMediaType.TEXT_PLAIN) + .contentType(MediaTypes.TEXT_PLAIN) .submit("0")) { assertThat(response.status(), is(PRECONDITION_FAILED_412)); } // NaN try (Http1ClientResponse response = client.post("/errorHandling/compute") - .contentType(HttpMediaType.TEXT_PLAIN) + .contentType(MediaTypes.TEXT_PLAIN) .submit("aaa")) { assertThat(response.status(), is(BAD_REQUEST_400)); } diff --git a/examples/webserver/comment-aas/src/main/java/io/helidon/webserver/examples/comments/CommentsService.java b/examples/webserver/comment-aas/src/main/java/io/helidon/webserver/examples/comments/CommentsService.java index c7a285d95c5..c960e06a7a2 100644 --- a/examples/webserver/comment-aas/src/main/java/io/helidon/webserver/examples/comments/CommentsService.java +++ b/examples/webserver/comment-aas/src/main/java/io/helidon/webserver/examples/comments/CommentsService.java @@ -22,7 +22,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.nima.webserver.http.HttpRules; import io.helidon.nima.webserver.http.HttpService; import io.helidon.nima.webserver.http.ServerRequest; @@ -43,7 +43,7 @@ public void routing(HttpRules rules) { private void handleListComments(ServerRequest req, ServerResponse resp) { String topic = req.path().pathParameters().value("topic"); - resp.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + resp.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); resp.send(listComments(topic)); } diff --git a/examples/webserver/comment-aas/src/main/java/io/helidon/webserver/examples/comments/Main.java b/examples/webserver/comment-aas/src/main/java/io/helidon/webserver/examples/comments/Main.java index 2f0f3e4c4a0..91b129f2b67 100644 --- a/examples/webserver/comment-aas/src/main/java/io/helidon/webserver/examples/comments/Main.java +++ b/examples/webserver/comment-aas/src/main/java/io/helidon/webserver/examples/comments/Main.java @@ -36,7 +36,7 @@ */ public final class Main { - static final Http.HeaderName USER_IDENTITY_HEADER = Http.Header.create("user-identity"); + static final Http.HeaderName USER_IDENTITY_HEADER = Http.HeaderNames.create("user-identity"); private Main() { } diff --git a/examples/webserver/comment-aas/src/test/java/io/helidon/webserver/examples/comments/CommentsServiceTest.java b/examples/webserver/comment-aas/src/test/java/io/helidon/webserver/examples/comments/CommentsServiceTest.java index 9810dd7be04..d132dd584a8 100644 --- a/examples/webserver/comment-aas/src/test/java/io/helidon/webserver/examples/comments/CommentsServiceTest.java +++ b/examples/webserver/comment-aas/src/test/java/io/helidon/webserver/examples/comments/CommentsServiceTest.java @@ -17,7 +17,7 @@ package io.helidon.webserver.examples.comments; import io.helidon.common.http.Http; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.media.type.MediaTypes; import io.helidon.nima.testing.junit5.webserver.DirectClient; import io.helidon.nima.testing.junit5.webserver.RoutingTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; @@ -73,7 +73,7 @@ public void testRouting() { assertThat(response.status(), is(Http.Status.OK_200)); } try (Http1ClientResponse response = client.post("/comments/one") - .contentType(HttpMediaType.TEXT_PLAIN) + .contentType(MediaTypes.TEXT_PLAIN) .submit("aaa")) { assertThat(response.status(), is(Http.Status.OK_200)); diff --git a/examples/webserver/comment-aas/src/test/java/io/helidon/webserver/examples/comments/MainTest.java b/examples/webserver/comment-aas/src/test/java/io/helidon/webserver/examples/comments/MainTest.java index 0a544d4c0f7..58a1e4465ac 100644 --- a/examples/webserver/comment-aas/src/test/java/io/helidon/webserver/examples/comments/MainTest.java +++ b/examples/webserver/comment-aas/src/test/java/io/helidon/webserver/examples/comments/MainTest.java @@ -17,7 +17,7 @@ package io.helidon.webserver.examples.comments; import io.helidon.common.http.Http; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.media.type.MediaTypes; import io.helidon.nima.testing.junit5.webserver.DirectClient; import io.helidon.nima.testing.junit5.webserver.RoutingTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; @@ -50,7 +50,7 @@ static void setup(HttpRouting.Builder routing) { public void argot() { try (Http1ClientResponse response = client.post("/comments/one") .header(Main.USER_IDENTITY_HEADER, "Joe") - .contentType(HttpMediaType.TEXT_PLAIN) + .contentType(MediaTypes.TEXT_PLAIN) .submit("Spring framework is the BEST!")) { assertThat(response.status(), is(Http.Status.NOT_ACCEPTABLE_406)); diff --git a/examples/webserver/mutual-tls/src/main/java/io/helidon/webserver/examples/mtls/SecureService.java b/examples/webserver/mutual-tls/src/main/java/io/helidon/webserver/examples/mtls/SecureService.java index cf48f2e75d8..32fb834b31a 100644 --- a/examples/webserver/mutual-tls/src/main/java/io/helidon/webserver/examples/mtls/SecureService.java +++ b/examples/webserver/mutual-tls/src/main/java/io/helidon/webserver/examples/mtls/SecureService.java @@ -32,7 +32,7 @@ public void routing(HttpRules rules) { .orElse("Unknown CN"); // close to avoid re-using cached connections on the client side - res.header(Http.HeaderValues.CONNECTION_CLOSE); + res.header(Http.Headers.CONNECTION_CLOSE); res.send("Hello " + cn + "!"); }); } diff --git a/examples/webserver/static-content/src/main/java/io/helidon/webserver/examples/staticcontent/Main.java b/examples/webserver/static-content/src/main/java/io/helidon/webserver/examples/staticcontent/Main.java index b788e914503..15ae9f709ef 100644 --- a/examples/webserver/static-content/src/main/java/io/helidon/webserver/examples/staticcontent/Main.java +++ b/examples/webserver/static-content/src/main/java/io/helidon/webserver/examples/staticcontent/Main.java @@ -26,7 +26,7 @@ * The application main class. */ public final class Main { - private static final Http.HeaderValue UI_REDIRECT = Http.Header.createCached(Http.Header.LOCATION, "/ui"); + private static final Http.Header UI_REDIRECT = Http.Headers.createCached(Http.HeaderNames.LOCATION, "/ui"); /** * Cannot be instantiated. diff --git a/examples/webserver/tutorial/src/main/java/io/helidon/webserver/examples/tutorial/CommentService.java b/examples/webserver/tutorial/src/main/java/io/helidon/webserver/examples/tutorial/CommentService.java index 75cefd9c2e8..9f9e33c046f 100644 --- a/examples/webserver/tutorial/src/main/java/io/helidon/webserver/examples/tutorial/CommentService.java +++ b/examples/webserver/tutorial/src/main/java/io/helidon/webserver/examples/tutorial/CommentService.java @@ -21,7 +21,7 @@ import java.util.List; import java.util.concurrent.ConcurrentHashMap; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.nima.webserver.http.HttpRules; import io.helidon.nima.webserver.http.HttpService; import io.helidon.nima.webserver.http.ServerRequest; @@ -42,7 +42,7 @@ public void routing(HttpRules rules) { private void getComments(ServerRequest req, ServerResponse resp) { String roomId = req.path().pathParameters().value("room-id"); - resp.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + resp.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); resp.send(getComments(roomId)); } diff --git a/examples/webserver/tutorial/src/main/java/io/helidon/webserver/examples/tutorial/Main.java b/examples/webserver/tutorial/src/main/java/io/helidon/webserver/examples/tutorial/Main.java index e3a9c576337..f74cfc98f5d 100644 --- a/examples/webserver/tutorial/src/main/java/io/helidon/webserver/examples/tutorial/Main.java +++ b/examples/webserver/tutorial/src/main/java/io/helidon/webserver/examples/tutorial/Main.java @@ -16,7 +16,7 @@ package io.helidon.webserver.examples.tutorial; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.nima.http.media.MediaContext; import io.helidon.nima.webserver.WebServer; import io.helidon.nima.webserver.WebServerConfig; @@ -42,7 +42,7 @@ static void routing(HttpRouting.Builder routing) { routing.any(new UserFilter()) .register("/article", new CommentService()) .post("/mgmt/shutdown", (req, res) -> { - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Shutting down TUTORIAL server. Good bye!\n"); req.context() .get(WebServer.class) diff --git a/examples/webserver/tutorial/src/test/java/io/helidon/webserver/examples/tutorial/CommentServiceTest.java b/examples/webserver/tutorial/src/test/java/io/helidon/webserver/examples/tutorial/CommentServiceTest.java index 191e72d139d..ae9701ef95a 100644 --- a/examples/webserver/tutorial/src/test/java/io/helidon/webserver/examples/tutorial/CommentServiceTest.java +++ b/examples/webserver/tutorial/src/test/java/io/helidon/webserver/examples/tutorial/CommentServiceTest.java @@ -17,8 +17,7 @@ package io.helidon.webserver.examples.tutorial; import io.helidon.common.http.Http; -import io.helidon.common.http.HttpMediaType; -import io.helidon.nima.testing.junit5.webserver.DirectClient; +import io.helidon.common.media.type.MediaTypes; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpServer; import io.helidon.nima.webclient.http1.Http1Client; @@ -73,7 +72,7 @@ void testRouting() { // Add first comment try (Http1ClientResponse response = client.post("/article/one") - .contentType(HttpMediaType.TEXT_PLAIN) + .contentType(MediaTypes.TEXT_PLAIN) .submit("aaa")) { assertThat(response.status(), is(Http.Status.OK_200)); } @@ -86,7 +85,7 @@ void testRouting() { // Add second comment try (Http1ClientResponse response = client.post("/article/one") - .contentType(HttpMediaType.TEXT_PLAIN) + .contentType(MediaTypes.TEXT_PLAIN) .submit("bbb")) { assertThat(response.status(), is(Http.Status.OK_200)); } diff --git a/examples/webserver/tutorial/src/test/java/io/helidon/webserver/examples/tutorial/UserFilterTest.java b/examples/webserver/tutorial/src/test/java/io/helidon/webserver/examples/tutorial/UserFilterTest.java index e948a7329bf..4b7dd04c019 100644 --- a/examples/webserver/tutorial/src/test/java/io/helidon/webserver/examples/tutorial/UserFilterTest.java +++ b/examples/webserver/tutorial/src/test/java/io/helidon/webserver/examples/tutorial/UserFilterTest.java @@ -56,7 +56,7 @@ public void filter() { } try (Http1ClientResponse response = client.get() - .header(Http.Header.COOKIE, "Unauthenticated-User-Alias=Foo") + .header(Http.HeaderNames.COOKIE, "Unauthenticated-User-Alias=Foo") .request()) { assertThat(response.entity().as(String.class), is("Foo")); } 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 200c226cacc..04e7677f8c1 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 @@ -226,7 +226,7 @@ protected void addQueryParams(HttpClientRequest request, Map> headers) { request.headers(clientHeaders -> { - headers.forEach((key, value) -> clientHeaders.set(Http.Header.create(key), value)); + headers.forEach((key, value) -> clientHeaders.set(Http.HeaderNames.create(key), value)); }); } 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 6fc10b3d87c..18f2982ef0c 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 @@ -15,21 +15,16 @@ */ package io.helidon.integrations.micrometer; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; - import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; -import io.helidon.common.http.HttpMediaType; import io.helidon.common.media.type.MediaTypes; -import io.helidon.nima.webclient.api.WebClient; +import io.helidon.nima.webclient.api.ClientResponseTyped; +import io.helidon.nima.webclient.api.HttpClientResponse; import io.helidon.nima.webclient.http1.Http1Client; -import io.helidon.nima.webclient.http1.Http1ClientResponse; import io.helidon.nima.webserver.WebServer; import io.micrometer.core.instrument.Counter; @@ -41,6 +36,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; + public class MicrometerSimplePrometheusTest { private static PrometheusMeterRegistry registry; @@ -83,44 +81,43 @@ void prepTest() { } @Test - public void checkViaMediaType() throws ExecutionException, InterruptedException { + public void checkViaMediaType() { timer1.record(2L, TimeUnit.SECONDS); counter1.increment(3); gauge1.set(4); - Http1ClientResponse response = webClient.get() - .header(Header.ACCEPT, HttpMediaType.TEXT_PLAIN.toString()) + ClientResponseTyped response = webClient.get() + .header(Http.HeaderNames.ACCEPT, MediaTypes.TEXT_PLAIN.text()) .path("/micrometer") - .request(); + .request(String.class); - String promOutput = response.entity().as(String.class); + String promOutput = response.entity(); assertThat("Unexpected HTTP status, response is: " + promOutput, response.status(), is(Http.Status.OK_200)); } @Test - public void checkViaQueryParam() throws ExecutionException, InterruptedException { + public void checkViaQueryParam() { timer1.record(2L, TimeUnit.SECONDS); counter1.increment(3); gauge1.set(4); - Http1ClientResponse response = webClient.get() - .header(Header.ACCEPT, MediaTypes.create(MediaTypes.TEXT_PLAIN.type(), "special").toString()) + ClientResponseTyped response = webClient.get() + .header(Http.HeaderNames.ACCEPT, MediaTypes.create(MediaTypes.TEXT_PLAIN.type(), "special").toString()) .path("/micrometer") .queryParam("type", "prometheus") - .request(); + .request(String.class); assertThat("Unexpected HTTP status", response.status(), is(Http.Status.OK_200)); - - String promOutput = response.entity().as(String.class); } @Test public void checkNoMatch() throws ExecutionException, InterruptedException { - Http1ClientResponse response = webClient.get() - .header(Header.ACCEPT, MediaTypes.create(MediaTypes.TEXT_PLAIN.type(), "special").toString()) + try(HttpClientResponse response = webClient.get() + .header(Http.HeaderNames.ACCEPT, MediaTypes.create(MediaTypes.TEXT_PLAIN.type(), "special").toString()) .path("/micrometer") - .request(); + .request()) { - assertThat("Expected failed HTTP status", response.status(), is(Http.Status.NOT_ACCEPTABLE_406)); + assertThat("Expected failed HTTP status", response.status(), is(Http.Status.NOT_ACCEPTABLE_406)); + } } private void initSomeMetrics() { 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 2bcfdfc6774..9da52707609 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 @@ -29,7 +29,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.Header.create("X-Vault-Token"); + private static final Http.HeaderName VAULT_TOKEN_HEADER_NAME = Http.HeaderNames.create("X-Vault-Token"); private final AtomicReference currentToken = new AtomicReference<>(); 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 291e5136f97..69c9408d2eb 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 @@ -35,7 +35,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.Header.create("X-Vault-Namespace"); + private static final Http.HeaderName VAULT_NAMESPACE_HEADER_NAME = Http.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 43f08797e52..df9794a8c9c 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 @@ -31,7 +31,7 @@ */ @Weight(1) public class NoVaultAuth implements VaultAuth { - private static final Http.HeaderName VAULT_NAMESPACE_HEADER_NAME = Http.Header.create("X-Vault-Namespace"); + private static final Http.HeaderName VAULT_NAMESPACE_HEADER_NAME = Http.HeaderNames.create("X-Vault-Namespace"); /** * Required for service loader. */ 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 c8562986f95..a1c74e25eba 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 @@ -27,7 +27,7 @@ class K8sRestApi extends VaultRestApi { - private static final Http.HeaderName VAULT_TOKEN_HEADER_NAME = Http.Header.create("X-Vault-Token"); + private static final Http.HeaderName VAULT_TOKEN_HEADER_NAME = Http.HeaderNames.create("X-Vault-Token"); private final AtomicReference currentToken = new AtomicReference<>(); private final K8sAuth auth; 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 d19c183c38d..8c18d3d1b5e 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 @@ -39,7 +39,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.Header.create("X-Vault-Namespace"); + private static final Http.HeaderName VAULT_NAMESPACE_HEADER_NAME = Http.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/TokenVaultAuth.java b/integrations/vault/auths/token/src/main/java/io/helidon/integrations/vault/auths/token/TokenVaultAuth.java index f2b5f279418..c24a53a2ceb 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 @@ -37,8 +37,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.Header.create("X-Vault-Token"); - private static final Http.HeaderName VAULT_NAMESPACE_HEADER_NAME = Http.Header.create("X-Vault-Namespace"); + 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 final String token; private final String baseNamespace; 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 815dc9ea25d..57d066ddc5a 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 @@ -126,7 +126,7 @@ private Http1ClientRequest mapRequest(ClientRequest request) { // map request headers request.getRequestHeaders().forEach((key, value) -> { String[] values = value.toArray(new String[0]); - httpRequest.header(Http.Header.create(key), values); + httpRequest.header(Http.HeaderNames.create(key), values); }); // SSL context @@ -184,7 +184,7 @@ public String getReasonPhrase() { }, request); // copy headers - for (Http.HeaderValue header : httpResponse.headers()) { + for (Http.Header header : httpResponse.headers()) { for (String v : header.allValues()) { response.getHeaders().add(header.name(), v); } 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 1d4fdb8967a..fd1fe6df7f4 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 @@ -47,8 +47,8 @@ * Narayana LRA coordinator client. */ public class NarayanaClient implements CoordinatorClient { - private static final Http.HeaderName LRA_HTTP_CONTEXT_HEADER = Http.Header.create(LRA.LRA_HTTP_CONTEXT_HEADER); - private static final Http.HeaderName LRA_HTTP_RECOVERY_HEADER = Http.Header.create(LRA.LRA_HTTP_RECOVERY_HEADER); + 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 System.Logger LOGGER = System.getLogger(NarayanaClient.class.getName()); @@ -117,7 +117,7 @@ private URI startInternal(URI parentLRA, String clientID, PropagatedHeaders head } //propagate supported headers from coordinator headers.scan(res.headers().toMap()); - URI lraId = res.headers().first(Http.Header.LOCATION) + URI lraId = res.headers().first(Http.HeaderNames.LOCATION) // TMM doesn't send lraId as LOCATION .or(() -> res.headers().first(LRA_HTTP_CONTEXT_HEADER)) .map(URI::create) @@ -199,8 +199,10 @@ public Optional join(URI lraId, .put() .queryParam(QUERY_PARAM_TIME_LIMIT, String.valueOf(timeLimit)) .headers(h -> { - h.add(Http.Header.createCached(HEADER_LINK, links)); // links are expected either in header - headers.toMap().forEach((name, value) -> h.set(Http.Header.create(name), value)); // header propagation + // links are expected either in header + h.add(Http.Headers.createCached(HEADER_LINK, links)); + // header propagation + headers.toMap().forEach((name, value) -> h.set(Http.HeaderNames.create(name), value)); }); try (var res = req.submit(links)) { @@ -331,7 +333,7 @@ private String compensatorLinks(Participant p) { private Consumer copyHeaders(PropagatedHeaders headers) { return wcHeaders -> { - headers.toMap().forEach((key, value) -> wcHeaders.set(Http.Header.create(key), value)); + headers.toMap().forEach((key, value) -> wcHeaders.set(Http.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 a9600491c3c..1a2a17c1d39 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 @@ -72,8 +72,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.Header.create(LRA.LRA_HTTP_CONTEXT_HEADER); - private static final Http.HeaderName LRA_HTTP_RECOVERY_HEADER = Http.Header.create(LRA.LRA_HTTP_RECOVERY_HEADER); + 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 Set RECOVERABLE_STATUSES = Set.of(LRAStatus.Cancelling, LRAStatus.Closing, LRAStatus.Active); private static final JsonBuilderFactory JSON = Json.createBuilderFactory(Collections.emptyMap()); @@ -228,7 +228,7 @@ private void cancel(ServerRequest req, ServerResponse res) { private void join(ServerRequest req, ServerResponse res) { String lraId = req.path().pathParameters().value("LraId"); - String compensatorLink = req.headers().first(Http.Header.LINK).orElse(""); + String compensatorLink = req.headers().first(Http.HeaderNames.LINK).orElse(""); Lra lra = lraPersistentRegistry.get(lraId); if (lra == null) { @@ -243,7 +243,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.Header.LOCATION, recoveryUrl); + res.headers().set(Http.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 e36b696ba94..06f7f39fca7 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 @@ -48,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.Header.create(LRA_HTTP_CONTEXT_HEADER); - static final Http.HeaderName LRA_HTTP_ENDED_CONTEXT_HEADER_NAME = Http.Header.create(LRA_HTTP_ENDED_CONTEXT_HEADER); - static final Http.HeaderName LRA_HTTP_PARENT_CONTEXT_HEADER_NAME = Http.Header.create(LRA_HTTP_PARENT_CONTEXT_HEADER); - static final Http.HeaderName LRA_HTTP_RECOVERY_HEADER_NAME = Http.Header.create(LRA_HTTP_RECOVERY_HEADER); + 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); private static final System.Logger LOGGER = System.getLogger(Lra.class.getName()); 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 b7e633fcdfb..8c58d4bad49 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 @@ -83,7 +83,7 @@ public void clearRegistry() { public void simpleCall() { try (Http1ClientResponse response = client.get("/metrics").request()) { assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers().first(Http.Header.CONTENT_TYPE).orElse(null), + assertThat(response.headers().first(Http.HeaderNames.CONTENT_TYPE).orElse(null), StringStartsWith.startsWith("text/plain")); String body = response.as(String.class); assertThat(body, containsString("# HELP beta")); @@ -99,7 +99,7 @@ public void simpleCall() { @Test public void doubleCall() { try (Http1ClientResponse response = client.get("/metrics").request()) { - assertThat(response.headers().first(Http.Header.CONTENT_TYPE).orElse(null), + assertThat(response.headers().first(Http.HeaderNames.CONTENT_TYPE).orElse(null), StringStartsWith.startsWith("text/plain")); String body = response.as(String.class); assertThat(body, containsString("alpha_total{method=\"bar\",} 6.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 6483d31e339..82d43c13ce1 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2022 Oracle and/or its affiliates. + * Copyright (c) 2020, 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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.helidon.microprofile.cors; import java.util.List; @@ -110,7 +111,7 @@ static class RequestAdapterMp implements CorsRequestAdapter findCookie(Map> headers) { - List cookies = headers.get(Http.Header.COOKIE.defaultCase()); + List cookies = headers.get(Http.HeaderNames.COOKIE.defaultCase()); if ((null == cookies) || cookies.isEmpty()) { return Optional.empty(); } @@ -1153,7 +1153,7 @@ public Builder config(Config config) { * @return updated builder instance */ public Builder jwtHeader(String header) { - if (Http.Header.COOKIE.defaultCase().equalsIgnoreCase(header)) { + if (Http.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 117467389c6..970a2337020 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 @@ -23,6 +23,8 @@ import io.helidon.common.Reflected; import io.helidon.common.http.Http; +import io.helidon.common.http.Http.HeaderName; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.HttpPrologue; import io.helidon.common.http.ServerRequestHeaders; import io.helidon.common.parameters.Parameters; @@ -49,9 +51,9 @@ class NonJaxRsResource { private static final System.Logger LOGGER = System.getLogger(NonJaxRsResource.class.getName()); private static final String LRA_PARTICIPANT = "lra-participant"; - private static final Http.HeaderName LRA_HTTP_CONTEXT_HEADER = Http.Header.create(LRA.LRA_HTTP_CONTEXT_HEADER); - private static final Http.HeaderName LRA_HTTP_ENDED_CONTEXT_HEADER = Http.Header.create(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER); - private static final Http.HeaderName LRA_HTTP_PARENT_CONTEXT_HEADER = Http.Header.create(LRA.LRA_HTTP_PARENT_CONTEXT_HEADER); + private static final HeaderName LRA_HTTP_CONTEXT_HEADER = HeaderNames.create(LRA.LRA_HTTP_CONTEXT_HEADER); + private static final HeaderName LRA_HTTP_ENDED_CONTEXT_HEADER = HeaderNames.create(LRA.LRA_HTTP_ENDED_CONTEXT_HEADER); + private static final HeaderName LRA_HTTP_PARENT_CONTEXT_HEADER = HeaderNames.create(LRA.LRA_HTTP_PARENT_CONTEXT_HEADER); private static final Map> PARTICIPANT_RESPONSE_BUILDERS = Map.of( ParticipantStatus.Compensating, () -> LRAResponse.compensating(ParticipantStatus.Compensating), @@ -182,7 +184,7 @@ private void sendResult(ServerResponse res, Object result) { private void sendResponse(ServerResponse res, Response response) { res.status(Http.Status.create(response.getStatus())); response.getHeaders() - .forEach((k, values) -> res.header(Http.Header.create(k), + .forEach((k, values) -> res.header(HeaderNames.create(k), values.stream() .map(String::valueOf) .toArray(String[]::new))); 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 52fccbf29fe..94fdcdbd0e6 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 @@ -105,7 +105,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.Header.create(LRA_HTTP_CONTEXT_HEADER); + private static final Http.HeaderName LRA_HTTP_CONTEXT_HEADER_NAME = Http.HeaderNames.create(LRA_HTTP_CONTEXT_HEADER); private static volatile int port = -1; 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 c22b27d0e83..d354433df4f 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 @@ -36,7 +36,7 @@ import io.helidon.common.context.Contexts; import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.InternalServerException; import io.helidon.common.uri.UriPath; import io.helidon.microprofile.server.HelidonHK2InjectionManagerFactory.InjectionManagerWrapper; @@ -219,7 +219,7 @@ private void doHandle(Context ctx, ServerRequest req, ServerResponse res) { new HelidonMpSecurityContext(), new MapPropertiesDelegate(), resourceConfig); - for (HeaderValue header : req.headers()) { + for (Header header : req.headers()) { requestContext.headers(header.name(), header.allValues()); } @@ -333,16 +333,16 @@ public OutputStream writeResponseStatusAndHeaders(long contentLengthParam, String name = entry.getKey(); List values = entry.getValue(); if (values.size() == 1) { - res.header(Header.create(Header.create(name), values.get(0))); + res.header(Http.Headers.create(HeaderNames.create(name), values.get(0))); } else { - res.header(Header.create(Header.create(entry.getKey()), entry.getValue())); + res.header(Http.Headers.create(entry.getKey(), entry.getValue())); } } Response.StatusType statusInfo = containerResponse.getStatusInfo(); res.status(Http.Status.create(statusInfo.getStatusCode(), statusInfo.getReasonPhrase())); if (contentLength > 0) { - res.header(Header.create(Header.CONTENT_LENGTH, String.valueOf(contentLength))); + res.header(Http.Headers.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 ade22ee1de8..0bb96507483 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 @@ -482,7 +482,7 @@ private void registerDefaultRedirect() { .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.Header.LOCATION, basePath); + res.headers().set(Http.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 dc8c79c0078..d0f559172b0 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2022 Oracle and/or its affiliates. + * Copyright (c) 2021, 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. @@ -20,7 +20,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http; import io.helidon.common.http.Http.HeaderName; import io.helidon.microprofile.tests.junit5.AddBean; import io.helidon.microprofile.tests.junit5.AddConfig; @@ -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 = Header.create(COOL_HEADER); + static final HeaderName COOL_HEADER_NAME = Http.HeaderNames.create(COOL_HEADER); static final String COOL_VALUE = "cool value"; static final String COOLER_HEADER = "Cooler-Header"; - static final HeaderName COOLER_HEADER_NAME = Header.create(COOLER_HEADER); + static final HeaderName COOLER_HEADER_NAME = Http.HeaderNames.create(COOLER_HEADER); static final String COOLER_VALUE = "cooler value"; static final String COOLEST_HEADER = "Coolest-Header"; - static final HeaderName COOLEST_HEADER_NAME = Header.create(COOLEST_HEADER); + static final HeaderName COOLEST_HEADER_NAME = Http.HeaderNames.create(COOLEST_HEADER); static final String COOLEST_VALUE = "coolest value"; @Test 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 c774ecc67d3..b80dabf57ea 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 @@ -123,8 +123,8 @@ public ServerConnection upgrade(ConnectionContext ctx, HttpPrologue prologue, Wr // Validate origin if (!anyOrigin()) { - if (headers.contains(Http.Header.ORIGIN)) { - String origin = headers.get(Http.Header.ORIGIN).value(); + if (headers.contains(Http.HeaderNames.ORIGIN)) { + String origin = headers.get(Http.HeaderNames.ORIGIN).value(); if (!origins().contains(origin)) { throw RequestException.builder() .message("Invalid Origin") @@ -229,8 +229,8 @@ WebSocketEngine.UpgradeInfo protocolHandshake(WritableHeaders headers, UriQue // Map Tyrus response headers back to Nima upgradeResponse.getHeaders() .forEach((key, value) -> headers.add( - Http.Header.create( - Http.Header.createName(key, key.toLowerCase(Locale.ROOT)), + Http.Headers.create( + Http.HeaderNames.create(key, key.toLowerCase(Locale.ROOT)), value))); return upgradeInfo; } diff --git a/nima/graphql/server/src/main/java/io/helidon/nima/graphql/server/GraphQlService.java b/nima/graphql/server/src/main/java/io/helidon/nima/graphql/server/GraphQlService.java index a82da308dd1..dc7e12196f5 100644 --- a/nima/graphql/server/src/main/java/io/helidon/nima/graphql/server/GraphQlService.java +++ b/nima/graphql/server/src/main/java/io/helidon/nima/graphql/server/GraphQlService.java @@ -24,7 +24,7 @@ import io.helidon.common.GenericType; import io.helidon.common.configurable.ServerThreadPoolSupplier; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.media.type.MediaTypes; import io.helidon.common.uri.UriQuery; import io.helidon.config.Config; import io.helidon.cors.CrossOriginConfig; @@ -134,7 +134,7 @@ private void processRequest(ServerResponse res, String operationName, Map variables) { - res.headers().contentType(HttpMediaType.APPLICATION_JSON); + res.headers().contentType(MediaTypes.APPLICATION_JSON); res.send(JSONB.toJson(invocationHandler.execute(query, operationName, variables))); } diff --git a/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcProtocolHandler.java b/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcProtocolHandler.java index bed736fa501..3d9da87e230 100644 --- a/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcProtocolHandler.java +++ b/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcProtocolHandler.java @@ -23,7 +23,7 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.HttpPrologue; import io.helidon.common.http.WritableHeaders; import io.helidon.nima.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 HeaderValue GRPC_CONTENT_TYPE = Header.createCached(Header.CONTENT_TYPE, "application/grpc"); - private static final HeaderValue GRPC_ENCODING_IDENTITY = Header.createCached("grpc-encoding", "identity"); + 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 final HttpPrologue prologue; private final Http2Headers headers; diff --git a/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcProtocolSelector.java b/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcProtocolSelector.java index 1657485d7c7..8af19d6d035 100644 --- a/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcProtocolSelector.java +++ b/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcProtocolSelector.java @@ -63,8 +63,8 @@ public SubProtocolResult subProtocol(ConnectionContext ctx, // we know this is HTTP/2, so no need to check protocol and version Headers httpHeaders = headers.httpHeaders(); - if (httpHeaders.contains(Http.Header.CONTENT_TYPE)) { - String contentType = httpHeaders.get(Http.Header.CONTENT_TYPE).value(); + if (httpHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { + String contentType = httpHeaders.get(Http.HeaderNames.CONTENT_TYPE).value(); if (contentType.startsWith("application/grpc")) { GrpcRouting routing = router.routing(GrpcRouting.class, GrpcRouting.empty()); diff --git a/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcStatus.java b/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcStatus.java index 93115334b9e..1dc529d04d1 100644 --- a/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcStatus.java +++ b/nima/grpc/webserver/src/main/java/io/helidon/nima/grpc/webserver/GrpcStatus.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -16,9 +16,10 @@ package io.helidon.nima.grpc.webserver; +import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.grpc.Status; @@ -33,15 +34,15 @@ public final class GrpcStatus { /** * grpc status header name. */ - public static final HeaderName STATUS_NAME = Header.createFromLowercase("grpc-status"); + public static final HeaderName STATUS_NAME = HeaderNames.createFromLowercase("grpc-status"); /** * The operation completed successfully. */ - public static final HeaderValue OK = Header.createCached(STATUS_NAME, Status.Code.OK.value()); + public static final Header OK = Http.Headers.createCached(STATUS_NAME, Status.Code.OK.value()); /** * The operation was cancelled (typically by the caller). */ - public static final HeaderValue CANCELLED = Header.createCached(STATUS_NAME, Status.Code.CANCELLED.value()); + public static final Http.Header CANCELLED = Http.Headers.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 @@ -49,14 +50,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 HeaderValue UNKNOWN = Header.createCached(STATUS_NAME, Status.Code.UNKNOWN.value()); + public static final Http.Header UNKNOWN = Http.Headers.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 HeaderValue INVALID_ARGUMENT = Header.createCached(STATUS_NAME, Status.Code.INVALID_ARGUMENT.value()); + public static final Header INVALID_ARGUMENT = Http.Headers.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 @@ -64,15 +65,16 @@ public final class GrpcStatus { * successful response from a server could have been delayed long * enough for the deadline to expire. */ - public static final HeaderValue DEADLINE_EXCEEDED = Header.createCached(STATUS_NAME, Status.Code.DEADLINE_EXCEEDED.value()); + public static final Http.Header DEADLINE_EXCEEDED = + Http.Headers.createCached(STATUS_NAME, Status.Code.DEADLINE_EXCEEDED.value()); /** * Some requested entity (e.g., file or directory) was not found. */ - public static final HeaderValue NOT_FOUND = Header.createCached(STATUS_NAME, Status.Code.NOT_FOUND.value()); + public static final Header NOT_FOUND = Http.Headers.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 HeaderValue ALREADY_EXISTS = Header.createCached(STATUS_NAME, Status.Code.ALREADY_EXISTS.value()); + public static final Header ALREADY_EXISTS = Http.Headers.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 @@ -81,12 +83,14 @@ public final class GrpcStatus { * used if the caller cannot be identified (use UNAUTHENTICATED * instead for those errors). */ - public static final HeaderValue PERMISSION_DENIED = Header.createCached(STATUS_NAME, Status.Code.PERMISSION_DENIED.value()); + public static final Http.Header PERMISSION_DENIED = + Http.Headers.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 HeaderValue RESOURCE_EXHAUSTED = Header.createCached(STATUS_NAME, Status.Code.RESOURCE_EXHAUSTED.value()); + public static final Http.Header RESOURCE_EXHAUSTED = + Http.Headers.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 @@ -104,8 +108,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 HeaderValue FAILED_PRECONDITION = Header.createCached(STATUS_NAME, - Status.Code.FAILED_PRECONDITION.value()); + public static final Http.Header FAILED_PRECONDITION = Http.Headers.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. @@ -113,7 +117,7 @@ public final class GrpcStatus { *

See litmus test above for deciding between FAILED_PRECONDITION, * ABORTED, and UNAVAILABLE. */ - public static final HeaderValue ABORTED = Header.createCached(STATUS_NAME, Status.Code.ABORTED.value()); + public static final Header ABORTED = Http.Headers.createCached(STATUS_NAME, Status.Code.ABORTED.value()); /** * Operation was attempted past the valid range. E.g., seeking or * reading past end of file. @@ -130,17 +134,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 HeaderValue OUT_OF_RANGE = Header.createCached(STATUS_NAME, Status.Code.OUT_OF_RANGE.value()); + public static final Http.Header OUT_OF_RANGE = Http.Headers.createCached(STATUS_NAME, Status.Code.OUT_OF_RANGE.value()); /** * Operation is not implemented or not supported/enabled in this service. */ - public static final HeaderValue UNIMPLEMENTED = Header.createCached(STATUS_NAME, Status.Code.UNIMPLEMENTED.value()); + public static final Http.Header UNIMPLEMENTED = Http.Headers.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 HeaderValue INTERNAL = Header.createCached(STATUS_NAME, Status.Code.INTERNAL.value()); + public static final Header INTERNAL = Http.Headers.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 @@ -150,16 +154,16 @@ public final class GrpcStatus { *

See litmus test above for deciding between FAILED_PRECONDITION, * ABORTED, and UNAVAILABLE. */ - public static final HeaderValue UNAVAILABLE = Header.createCached(STATUS_NAME, Status.Code.UNAVAILABLE.value()); + public static final Header UNAVAILABLE = Http.Headers.createCached(STATUS_NAME, Status.Code.UNAVAILABLE.value()); /** * Unrecoverable data loss or corruption. */ - public static final HeaderValue DATA_LOSS = Header.createCached(STATUS_NAME, Status.Code.DATA_LOSS.value()); + public static final Http.Header DATA_LOSS = Http.Headers.createCached(STATUS_NAME, Status.Code.DATA_LOSS.value()); /** * The request does not have valid authentication credentials for the * operation. */ - public static final HeaderValue UNAUTHENTICATED = Header.createCached(STATUS_NAME, Status.Code.UNAUTHENTICATED.value()); + public static final Http.Header UNAUTHENTICATED = Http.Headers.createCached(STATUS_NAME, Status.Code.UNAUTHENTICATED.value()); private GrpcStatus() { } diff --git a/nima/http/encoding/deflate/src/main/java/io/helidon/nima/http/encoding/deflate/DeflateEncoding.java b/nima/http/encoding/deflate/src/main/java/io/helidon/nima/http/encoding/deflate/DeflateEncoding.java index 95e0991464e..0908693ee98 100644 --- a/nima/http/encoding/deflate/src/main/java/io/helidon/nima/http/encoding/deflate/DeflateEncoding.java +++ b/nima/http/encoding/deflate/src/main/java/io/helidon/nima/http/encoding/deflate/DeflateEncoding.java @@ -31,11 +31,11 @@ * Support for {@code deflate} content encoding. */ public class DeflateEncoding implements ContentEncoding { - private static final Http.HeaderValue CONTENT_ENCODING_DEFLATE = - Http.Header.createCached(Http.Header.CONTENT_ENCODING, - false, - false, - "deflate"); + private static final Http.Header CONTENT_ENCODING_DEFLATE = + Http.Headers.createCached(Http.HeaderNames.CONTENT_ENCODING, + false, + false, + "deflate"); private final String name; DeflateEncoding(String name) { @@ -92,7 +92,7 @@ public OutputStream encode(OutputStream network) { @Override public void headers(WritableHeaders headers) { headers.add(CONTENT_ENCODING_DEFLATE); - headers.remove(Http.Header.CONTENT_LENGTH); + headers.remove(Http.HeaderNames.CONTENT_LENGTH); } }; } diff --git a/nima/http/encoding/encoding/src/main/java/io/helidon/nima/http/encoding/ContentEncodingSupportImpl.java b/nima/http/encoding/encoding/src/main/java/io/helidon/nima/http/encoding/ContentEncodingSupportImpl.java index eba4acfcef4..f12040db5b0 100644 --- a/nima/http/encoding/encoding/src/main/java/io/helidon/nima/http/encoding/ContentEncodingSupportImpl.java +++ b/nima/http/encoding/encoding/src/main/java/io/helidon/nima/http/encoding/ContentEncodingSupportImpl.java @@ -116,11 +116,11 @@ public ContentDecoder decoder(String encodingId) throws NoSuchElementException { @Override public ContentEncoder encoder(Headers headers) { - if (!contentEncodingEnabled() || !headers.contains(Http.Header.ACCEPT_ENCODING)) { + if (!contentEncodingEnabled() || !headers.contains(Http.HeaderNames.ACCEPT_ENCODING)) { return ContentEncoder.NO_OP; } - String acceptEncoding = headers.get(Http.Header.ACCEPT_ENCODING).value(); + String acceptEncoding = headers.get(Http.HeaderNames.ACCEPT_ENCODING).value(); /* Accept-Encoding: gzip Accept-Encoding: gzip, compress, br diff --git a/nima/http/encoding/gzip/src/main/java/io/helidon/nima/http/encoding/gzip/GzipEncoding.java b/nima/http/encoding/gzip/src/main/java/io/helidon/nima/http/encoding/gzip/GzipEncoding.java index 70589b4d77f..d3995ad21cc 100644 --- a/nima/http/encoding/gzip/src/main/java/io/helidon/nima/http/encoding/gzip/GzipEncoding.java +++ b/nima/http/encoding/gzip/src/main/java/io/helidon/nima/http/encoding/gzip/GzipEncoding.java @@ -24,22 +24,21 @@ import java.util.zip.GZIPOutputStream; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.HeaderValue; import io.helidon.common.http.WritableHeaders; import io.helidon.nima.http.encoding.ContentDecoder; import io.helidon.nima.http.encoding.ContentEncoder; import io.helidon.nima.http.encoding.ContentEncoding; -import static io.helidon.common.http.Http.Header.CONTENT_LENGTH; +import static io.helidon.common.http.Http.HeaderNames.CONTENT_LENGTH; /** * Support for gzip content encoding. */ public class GzipEncoding implements ContentEncoding { - private static final HeaderValue CONTENT_ENCODING_GZIP = Http.Header.createCached(Http.Header.CONTENT_ENCODING, - false, - false, - "gzip"); + private static final Http.Header CONTENT_ENCODING_GZIP = Http.Headers.createCached(Http.HeaderNames.CONTENT_ENCODING, + false, + false, + "gzip"); private final String name; diff --git a/nima/http/media/jackson/src/main/java/io/helidon/nima/http/media/jackson/JacksonSupport.java b/nima/http/media/jackson/src/main/java/io/helidon/nima/http/media/jackson/JacksonSupport.java index d6640529d55..0e9f0b758d9 100644 --- a/nima/http/media/jackson/src/main/java/io/helidon/nima/http/media/jackson/JacksonSupport.java +++ b/nima/http/media/jackson/src/main/java/io/helidon/nima/http/media/jackson/JacksonSupport.java @@ -34,7 +34,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; -import static io.helidon.common.http.Http.HeaderValues.CONTENT_TYPE_JSON; +import static io.helidon.common.http.Http.Headers.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.Header.CONTENT_TYPE)) { + if (requestHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { if (requestHeaders.contains(CONTENT_TYPE_JSON)) { if (objectMapper.canSerialize(type.rawType())) { return new WriterResponse<>(SupportLevel.COMPATIBLE, this::writer); diff --git a/nima/http/media/jackson/src/main/java/io/helidon/nima/http/media/jackson/JacksonWriter.java b/nima/http/media/jackson/src/main/java/io/helidon/nima/http/media/jackson/JacksonWriter.java index 98c9cc96d56..313677a3299 100644 --- a/nima/http/media/jackson/src/main/java/io/helidon/nima/http/media/jackson/JacksonWriter.java +++ b/nima/http/media/jackson/src/main/java/io/helidon/nima/http/media/jackson/JacksonWriter.java @@ -51,7 +51,7 @@ public void write(GenericType type, Headers requestHeaders, WritableHeaders responseHeaders) { - responseHeaders.setIfAbsent(Http.HeaderValues.CONTENT_TYPE_JSON); + responseHeaders.setIfAbsent(Http.Headers.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.HeaderValues.CONTENT_TYPE_JSON); + headers.setIfAbsent(Http.Headers.CONTENT_TYPE_JSON); write(type, object, outputStream); } diff --git a/nima/http/media/jackson/src/test/java/io/helidon/nima/http/media/jackson/JacksonMediaTest.java b/nima/http/media/jackson/src/test/java/io/helidon/nima/http/media/jackson/JacksonMediaTest.java index c7bab671512..5fa72d56baa 100644 --- a/nima/http/media/jackson/src/test/java/io/helidon/nima/http/media/jackson/JacksonMediaTest.java +++ b/nima/http/media/jackson/src/test/java/io/helidon/nima/http/media/jackson/JacksonMediaTest.java @@ -70,7 +70,7 @@ void testWriteSingle() { res.supplier().get() .write(BOOK_TYPE, new Book("test-title"), os, headers); - assertThat(headers, HttpHeaderMatcher.hasHeader(Http.HeaderValues.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.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.HeaderValues.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.CONTENT_TYPE_JSON)); String result = os.toString(StandardCharsets.UTF_8); assertThat(result, containsString("\"title\"")); assertThat(result, containsString("\"first\"")); diff --git a/nima/http/media/jsonb/src/main/java/io/helidon/nima/http/media/jsonb/JsonbSupport.java b/nima/http/media/jsonb/src/main/java/io/helidon/nima/http/media/jsonb/JsonbSupport.java index 4fff88d0393..8b5257aef84 100644 --- a/nima/http/media/jsonb/src/main/java/io/helidon/nima/http/media/jsonb/JsonbSupport.java +++ b/nima/http/media/jsonb/src/main/java/io/helidon/nima/http/media/jsonb/JsonbSupport.java @@ -33,7 +33,7 @@ import jakarta.json.bind.Jsonb; import jakarta.json.bind.JsonbBuilder; -import static io.helidon.common.http.Http.HeaderValues.CONTENT_TYPE_JSON; +import static io.helidon.common.http.Http.Headers.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.Header.CONTENT_TYPE)) { + if (requestHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { if (requestHeaders.contains(CONTENT_TYPE_JSON)) { return new WriterResponse<>(SupportLevel.COMPATIBLE, this::writer); } diff --git a/nima/http/media/jsonb/src/main/java/io/helidon/nima/http/media/jsonb/JsonbWriter.java b/nima/http/media/jsonb/src/main/java/io/helidon/nima/http/media/jsonb/JsonbWriter.java index 6c550069746..dc410b27e31 100644 --- a/nima/http/media/jsonb/src/main/java/io/helidon/nima/http/media/jsonb/JsonbWriter.java +++ b/nima/http/media/jsonb/src/main/java/io/helidon/nima/http/media/jsonb/JsonbWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -48,7 +48,7 @@ public void write(GenericType type, Headers requestHeaders, WritableHeaders responseHeaders) { - responseHeaders.setIfAbsent(Http.HeaderValues.CONTENT_TYPE_JSON); + responseHeaders.setIfAbsent(Http.Headers.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.HeaderValues.CONTENT_TYPE_JSON); + headers.setIfAbsent(Http.Headers.CONTENT_TYPE_JSON); write(type, object, outputStream); } diff --git a/nima/http/media/jsonb/src/test/java/io/helidon/nima/http/media/jsonb/JsonbMediaTest.java b/nima/http/media/jsonb/src/test/java/io/helidon/nima/http/media/jsonb/JsonbMediaTest.java index 6194876aa4f..56b8b587613 100644 --- a/nima/http/media/jsonb/src/test/java/io/helidon/nima/http/media/jsonb/JsonbMediaTest.java +++ b/nima/http/media/jsonb/src/test/java/io/helidon/nima/http/media/jsonb/JsonbMediaTest.java @@ -70,7 +70,7 @@ void testWriteSingle() { res.supplier().get() .write(BOOK_TYPE, new Book("test-title"), os, headers); - assertThat(headers, HttpHeaderMatcher.hasHeader(Http.HeaderValues.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.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.HeaderValues.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.CONTENT_TYPE_JSON)); String result = os.toString(StandardCharsets.UTF_8); assertThat(result, containsString("\"title\"")); assertThat(result, containsString("\"first\"")); diff --git a/nima/http/media/jsonp/src/main/java/io/helidon/nima/http/media/jsonp/JsonpWriter.java b/nima/http/media/jsonp/src/main/java/io/helidon/nima/http/media/jsonp/JsonpWriter.java index 6abdc7d6209..1abe25f7266 100644 --- a/nima/http/media/jsonp/src/main/java/io/helidon/nima/http/media/jsonp/JsonpWriter.java +++ b/nima/http/media/jsonp/src/main/java/io/helidon/nima/http/media/jsonp/JsonpWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -50,7 +50,7 @@ public void write(GenericType type, Headers requestHeaders, WritableHeaders responseHeaders) { - responseHeaders.setIfAbsent(Http.HeaderValues.CONTENT_TYPE_JSON); + responseHeaders.setIfAbsent(Http.Headers.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.HeaderValues.CONTENT_TYPE_JSON); + headers.setIfAbsent(Http.Headers.CONTENT_TYPE_JSON); write(type, object, outputStream); } diff --git a/nima/http/media/jsonp/src/test/java/io/helidon/nima/http/media/jsonp/JsonpMediaTest.java b/nima/http/media/jsonp/src/test/java/io/helidon/nima/http/media/jsonp/JsonpMediaTest.java index d82947ffa5e..ba161d82334 100644 --- a/nima/http/media/jsonp/src/test/java/io/helidon/nima/http/media/jsonp/JsonpMediaTest.java +++ b/nima/http/media/jsonp/src/test/java/io/helidon/nima/http/media/jsonp/JsonpMediaTest.java @@ -74,7 +74,7 @@ void testWriteSingle() { res.supplier().get() .write(JSON_OBJECT_TYPE, createObject("test-title"), os, headers); - assertThat(headers, HttpHeaderMatcher.hasHeader(Http.HeaderValues.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.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.HeaderValues.CONTENT_TYPE_JSON)); + assertThat(headers, HttpHeaderMatcher.hasHeader(Http.Headers.CONTENT_TYPE_JSON)); String result = os.toString(StandardCharsets.UTF_8); assertThat(result, containsString("\"title\"")); assertThat(result, containsString("\"first\"")); diff --git a/nima/http/media/media/src/main/java/io/helidon/nima/http/media/FormParamsSupport.java b/nima/http/media/media/src/main/java/io/helidon/nima/http/media/FormParamsSupport.java index edb6c4d26f0..d39a8a8e042 100644 --- a/nima/http/media/media/src/main/java/io/helidon/nima/http/media/FormParamsSupport.java +++ b/nima/http/media/media/src/main/java/io/helidon/nima/http/media/FormParamsSupport.java @@ -34,7 +34,7 @@ import io.helidon.common.GenericType; import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.Header; import io.helidon.common.http.HttpMediaType; import io.helidon.common.http.WritableHeaders; import io.helidon.common.media.type.MediaTypes; @@ -181,12 +181,12 @@ private static class FormParamsWriter implements EntityWriter { private final String separator; private final Function nameEncoder; private final Function valueEncoder; - private final HeaderValue contentTypeHeader; + private final Http.Header contentTypeHeader; private FormParamsWriter(String separator, Function nameEncoder, Function valueEncoder, - HeaderValue contentTypeHeader) { + Header contentTypeHeader) { this.separator = separator; this.nameEncoder = nameEncoder; this.valueEncoder = valueEncoder; @@ -215,7 +215,7 @@ private void write(Parameters toWrite, WritableHeaders writableHeaders) { Charset charset; - if (writableHeaders.contains(Http.Header.CONTENT_TYPE)) { + if (writableHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { charset = writableHeaders.contentType() .flatMap(HttpMediaType::charset) .map(Charset::forName) @@ -251,9 +251,9 @@ private void write(Parameters toWrite, } private static class FormParamsUrlWriter extends FormParamsWriter { - private static final HeaderValue CONTENT_TYPE_URL_ENCODED = - Http.Header.createCached(Http.Header.CONTENT_TYPE, - HttpMediaType.create(MediaTypes.APPLICATION_FORM_URLENCODED) + private static final Http.Header CONTENT_TYPE_URL_ENCODED = + Http.Headers.createCached(Http.HeaderNames.CONTENT_TYPE, + HttpMediaType.create(MediaTypes.APPLICATION_FORM_URLENCODED) .withCharset("utf-8") .text()); private static final String SEPARATOR = "&"; @@ -266,9 +266,9 @@ private FormParamsUrlWriter() { } private static class FormParamsPlaintextWriter extends FormParamsWriter { - private static final HeaderValue CONTENT_TYPE_TEXT = - Http.Header.createCached(Http.Header.CONTENT_TYPE, - HttpMediaType.create(MediaTypes.TEXT_PLAIN) + private static final Http.Header CONTENT_TYPE_TEXT = + Http.Headers.createCached(Http.HeaderNames.CONTENT_TYPE, + HttpMediaType.create(MediaTypes.TEXT_PLAIN) .withCharset("utf-8") .text()); private static final String SEPARATOR = "\n"; diff --git a/nima/http/media/media/src/main/java/io/helidon/nima/http/media/PathSupport.java b/nima/http/media/media/src/main/java/io/helidon/nima/http/media/PathSupport.java index 64bb452bd8b..59f47092aaf 100644 --- a/nima/http/media/media/src/main/java/io/helidon/nima/http/media/PathSupport.java +++ b/nima/http/media/media/src/main/java/io/helidon/nima/http/media/PathSupport.java @@ -126,11 +126,11 @@ private void write(Path toWrite, OutputStream outputStream, WritableHeaders writableHeaders) { - if (!writableHeaders.contains(Http.Header.CONTENT_TYPE)) { + if (!writableHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { MediaType mediaType = MediaTypes.detectType(toWrite).orElse(MediaTypes.APPLICATION_OCTET_STREAM); writableHeaders.contentType(mediaType); } - if (!writableHeaders.contains(Http.Header.CONTENT_DISPOSITION)) { + if (!writableHeaders.contains(Http.HeaderNames.CONTENT_DISPOSITION)) { writableHeaders.set(ContentDisposition.builder() .filename(String.valueOf(toWrite.getFileName())) .build()); diff --git a/nima/http/media/media/src/main/java/io/helidon/nima/http/media/StringSupport.java b/nima/http/media/media/src/main/java/io/helidon/nima/http/media/StringSupport.java index 15460ec2e68..cb5d6fe673f 100644 --- a/nima/http/media/media/src/main/java/io/helidon/nima/http/media/StringSupport.java +++ b/nima/http/media/media/src/main/java/io/helidon/nima/http/media/StringSupport.java @@ -28,8 +28,9 @@ import io.helidon.common.GenericType; import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.Header; import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.common.http.WritableHeaders; /** @@ -119,8 +120,8 @@ private static EntityWriter writer() { private static final class StringWriter implements EntityWriter { - private static final HeaderValue HEADER_PLAIN_TEXT = Http.Header.createCached(Http.Header.CONTENT_TYPE, - HttpMediaType.PLAINTEXT_UTF_8.text()); + private static final Header HEADER_PLAIN_TEXT = Http.Headers.createCached(Http.HeaderNames.CONTENT_TYPE, + HttpMediaTypes.PLAINTEXT_UTF_8.text()); @Override public void write(GenericType type, @@ -143,7 +144,7 @@ private void write(String toWrite, OutputStream outputStream, WritableHeaders writableHeaders) { Charset charset; - if (writableHeaders.contains(Http.Header.CONTENT_TYPE)) { + if (writableHeaders.contains(Http.HeaderNames.CONTENT_TYPE)) { charset = writableHeaders.contentType() .flatMap(HttpMediaType::charset) .map(Charset::forName) diff --git a/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/MultiPartImpl.java b/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/MultiPartImpl.java index cedd0599837..116aea76e81 100644 --- a/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/MultiPartImpl.java +++ b/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/MultiPartImpl.java @@ -23,7 +23,7 @@ import java.util.NoSuchElementException; import io.helidon.common.buffers.DataReader; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.Http1HeadersParser; import io.helidon.common.http.WritableHeaders; import io.helidon.nima.http.media.MediaContext; @@ -83,12 +83,12 @@ public boolean hasNext() { if (probablyBoundary.equals(boundary)) { dataReader.skip(2); // skip the new line after boundary WritableHeaders headers = Http1HeadersParser.readHeaders(dataReader, 1024, true); - if (headers.contains(Header.CONTENT_LENGTH)) { + if (headers.contains(HeaderNames.CONTENT_LENGTH)) { next = new ReadablePartLength(context, headers, dataReader, index++, - headers.get(Header.CONTENT_LENGTH).value(long.class)); + headers.get(HeaderNames.CONTENT_LENGTH).value(long.class)); return true; } else { next = new ReadablePartNoLength(context, headers, dataReader, index++, boundary, endBoundary); diff --git a/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/MultiPartWriter.java b/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/MultiPartWriter.java index af8a055e0da..e2e6b23db9f 100644 --- a/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/MultiPartWriter.java +++ b/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/MultiPartWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -32,12 +32,12 @@ class MultiPartWriter implements EntityWriter { private final MediaContext context; - private final Http.HeaderValue contentType; + private final Http.Header contentType; private final byte[] boundaryPrefix; MultiPartWriter(MediaContext context, HttpMediaType mediaType, String boundary) { this.context = context; - this.contentType = Http.Header.create(Http.Header.CONTENT_TYPE, false, false, mediaType.text()); + this.contentType = Http.Headers.create(Http.HeaderNames.CONTENT_TYPE, false, false, mediaType.text()); this.boundaryPrefix = ("--" + boundary).getBytes(StandardCharsets.UTF_8); } diff --git a/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/ReadablePartAbstract.java b/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/ReadablePartAbstract.java index d4c1abad96c..e9f2b829cb4 100644 --- a/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/ReadablePartAbstract.java +++ b/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/ReadablePartAbstract.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -22,6 +22,7 @@ import io.helidon.common.http.Headers; import io.helidon.common.http.Http; import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.nima.http.media.ReadableEntity; abstract class ReadablePartAbstract implements ReadablePart { @@ -55,7 +56,7 @@ public Optional fileName() { @Override public HttpMediaType contentType() { if (mediaType == null) { - mediaType = headers.contentType().orElse(HttpMediaType.PLAINTEXT_UTF_8); + mediaType = headers.contentType().orElse(HttpMediaTypes.PLAINTEXT_UTF_8); } return mediaType; } @@ -78,8 +79,8 @@ public boolean hasEntity() { protected abstract void finish(); private void contentDisposition() { - if (headers.contains(Http.Header.CONTENT_DISPOSITION)) { - this.contentDisposition = ContentDisposition.parse(headers.get(Http.Header.CONTENT_DISPOSITION).value()); + if (headers.contains(Http.HeaderNames.CONTENT_DISPOSITION)) { + this.contentDisposition = ContentDisposition.parse(headers.get(Http.HeaderNames.CONTENT_DISPOSITION).value()); } else { this.contentDisposition = ContentDisposition.empty(); } diff --git a/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/WriteablePart.java b/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/WriteablePart.java index 1bc1deb4b04..adf7c9960ae 100644 --- a/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/WriteablePart.java +++ b/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/WriteablePart.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -23,6 +23,7 @@ import io.helidon.common.http.Headers; import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.common.http.WritableHeaders; import io.helidon.common.media.type.MediaType; import io.helidon.nima.http.media.MediaContext; @@ -94,7 +95,7 @@ class Builder implements io.helidon.common.Builder { private final String partName; private String fileName; - private HttpMediaType mediaType = HttpMediaType.PLAINTEXT_UTF_8; + private HttpMediaType mediaType = HttpMediaTypes.PLAINTEXT_UTF_8; private Supplier objectContent; private Supplier inputStreamSupplier; private byte[] byteContent; diff --git a/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/WriteablePartAbstract.java b/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/WriteablePartAbstract.java index 01340a5a671..02f357039a1 100644 --- a/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/WriteablePartAbstract.java +++ b/nima/http/media/multipart/src/main/java/io/helidon/nima/http/media/multipart/WriteablePartAbstract.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -27,7 +27,7 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.HttpMediaType; import io.helidon.common.http.WritableHeaders; import io.helidon.common.media.type.MediaTypes; @@ -69,7 +69,7 @@ public Headers headers() { protected void sendHeaders(OutputStream outputStream, Headers headers) throws IOException { BufferData bufferData = BufferData.growing(128); - for (Http.HeaderValue header : headers) { + for (Http.Header header : headers) { header.writeHttp1Header(bufferData); } bufferData.writeTo(outputStream); @@ -78,7 +78,7 @@ protected void sendHeaders(OutputStream outputStream, Headers headers) throws IO } protected void send(OutputStream outputStream, WritableHeaders headers, byte[] bytes) { - headers.set(Header.create(Header.CONTENT_LENGTH, true, false, String.valueOf(bytes.length))); + headers.set(Http.Headers.create(HeaderNames.CONTENT_LENGTH, true, false, String.valueOf(bytes.length))); try (outputStream) { sendHeaders(outputStream, headers); @@ -93,18 +93,18 @@ protected void send(OutputStream outputStream, WritableHeaders headers, byte[ void contentType(WritableHeaders headers) { // we support form-data and byte-ranges, falling back to form data if unknown if (contentType().test(MediaTypes.MULTIPART_BYTERANGES)) { - headers.remove(Header.CONTENT_DISPOSITION); + headers.remove(HeaderNames.CONTENT_DISPOSITION); } else { - if (!headers.contains(Header.CONTENT_DISPOSITION)) { + if (!headers.contains(HeaderNames.CONTENT_DISPOSITION)) { List disposition = new LinkedList<>(); 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(Header.create(Header.CONTENT_DISPOSITION, String.join("; ", disposition))); + headers.setIfAbsent(Http.Headers.create(HeaderNames.CONTENT_DISPOSITION, String.join("; ", disposition))); } } - if (!headers.contains(Header.CONTENT_TYPE)) { - headers.set(Header.CONTENT_TYPE, contentType().text()); + if (!headers.contains(HeaderNames.CONTENT_TYPE)) { + headers.set(HeaderNames.CONTENT_TYPE, contentType().text()); } } } diff --git a/nima/http/processor/src/main/resources/templates/inject/nima/http-method.java.hbs b/nima/http/processor/src/main/resources/templates/inject/nima/http-method.java.hbs index f7b66a8de62..e35f9533ace 100644 --- a/nima/http/processor/src/main/resources/templates/inject/nima/http-method.java.hbs +++ b/nima/http/processor/src/main/resources/templates/inject/nima/http-method.java.hbs @@ -37,7 +37,7 @@ import jakarta.inject.Singleton; @Weight({{weight}}) {{{generatedSticker}}} class {{className}} implements GeneratedHandler { -{{#each http.headers}}private static final Http.HeaderName {{this.field}} = Http.Header.create("{{this.name}}"); +{{#each http.headers}}private static final Http.HeaderName {{this.field}} = Http.HeaderNames.create("{{this.name}}"); {{/each}} private static final Http.Method METHOD = Http.Method.create("{{http.method}}"); diff --git a/nima/http2/http2/src/main/java/io/helidon/nima/http2/Http2Headers.java b/nima/http2/http2/src/main/java/io/helidon/nima/http2/Http2Headers.java index 4e057140f2f..ea67050f80e 100644 --- a/nima/http2/http2/src/main/java/io/helidon/nima/http2/Http2Headers.java +++ b/nima/http2/http2/src/main/java/io/helidon/nima/http2/Http2Headers.java @@ -30,7 +30,7 @@ import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.ServerRequestHeaders; import io.helidon.common.http.WritableHeaders; @@ -51,27 +51,27 @@ public class Http2Headers { /** * Header name of the authority pseudo header. */ - public static final HeaderName AUTHORITY_NAME = Header.create(AUTHORITY); + public static final HeaderName AUTHORITY_NAME = HeaderNames.create(AUTHORITY); static final String METHOD = ":method"; /** * Header name of the method pseudo header. */ - public static final HeaderName METHOD_NAME = Header.create(METHOD); + public static final HeaderName METHOD_NAME = HeaderNames.create(METHOD); static final String PATH = ":path"; /** * Header name of the path pseudo header. */ - public static final HeaderName PATH_NAME = Header.create(PATH); + public static final HeaderName PATH_NAME = Http.HeaderNames.create(PATH); static final String SCHEME = ":scheme"; /** * Header name of the scheme pseudo header. */ - public static final HeaderName SCHEME_NAME = Header.create(SCHEME); + public static final HeaderName SCHEME_NAME = Http.HeaderNames.create(SCHEME); static final String STATUS = ":status"; /** * Header name of the status pseudo header. */ - public static final HeaderName STATUS_NAME = Header.create(STATUS); + public static final HeaderName STATUS_NAME = HeaderNames.create(STATUS); static final DynamicHeader EMPTY_HEADER_RECORD = new DynamicHeader(null, null, 0); private static final System.Logger LOGGER = System.getLogger(Http2Headers.class.getName()); private static final String TRAILERS = "trailers"; @@ -294,7 +294,7 @@ public void validateResponse() throws Http2Exception { if (!pseudoHeaders.hasStatus()) { throw new Http2Exception(Http2ErrorCode.PROTOCOL, "Missing :status pseudo header"); } - if (headers.contains(Header.CONNECTION)) { + if (headers.contains(HeaderNames.CONNECTION)) { throw new Http2Exception(Http2ErrorCode.PROTOCOL, "Connection in response headers"); } if (pseudoHeaders.hasScheme()) { @@ -317,11 +317,11 @@ public void validateRequest() throws Http2Exception { if (pseudoHeaders.hasStatus()) { throw new Http2Exception(Http2ErrorCode.PROTOCOL, ":status in request headers"); } - if (headers.contains(Header.CONNECTION)) { + if (headers.contains(Http.HeaderNames.CONNECTION)) { throw new Http2Exception(Http2ErrorCode.PROTOCOL, "Connection in request headers"); } - if (headers.contains(Header.TE)) { - List values = headers.all(Header.TE, List::of); + if (headers.contains(HeaderNames.TE)) { + List values = headers.all(HeaderNames.TE, List::of); if (!values.equals(List.of(TRAILERS))) { throw new Http2Exception(Http2ErrorCode.PROTOCOL, "te in headers with other value than trailers: \n" + BufferData.create(values.toString()).debugDataHex()); @@ -431,7 +431,7 @@ public void write(DynamicTable table, Http2HuffmanEncoder huffman, BufferData gr writeHeader(huffman, table, growingBuffer, AUTHORITY_NAME, pseudoHeaders.authority, true, false); } - for (HeaderValue header : headers) { + for (Header header : headers) { String value = header.value(); boolean shouldIndex = !header.changing(); boolean neverIndex = header.sensitive(); @@ -508,7 +508,7 @@ record = table.get(approach.number); "Received invalid pseudo-header field (or explicit value instead of indexed)\n" + BufferData.create(name).debugDataHex()); } - headerName = Header.create(name); + headerName = Http.HeaderNames.create(name); } else { headerName = record.headerName(); } @@ -572,10 +572,10 @@ record = table.get(approach.number); } if (!isPseudoHeader) { - headers.add(Header.create(headerName, - !approach.addToIndex, - approach.neverIndex, - value)); + headers.add(Http.Headers.create(headerName, + !approach.addToIndex, + approach.neverIndex, + value)); } return isPseudoHeader; } @@ -626,7 +626,7 @@ private static Http2Headers createFromWritable(WritableHeaders headers) { removeFromHeadersAddToPseudo(headers, pseudoHeaders::scheme, SCHEME_NAME); removeFromHeadersAddToPseudo(headers, pseudoHeaders::method, METHOD_NAME); - headers.remove(Header.HOST, it -> { + headers.remove(HeaderNames.HOST, it -> { if (!pseudoHeaders.hasAuthority()) { pseudoHeaders.authority(it.value()); } @@ -737,53 +737,53 @@ enum StaticHeader implements IndexedHeaderRecord { STATUS_400(12, STATUS_NAME, "400"), STATUS_404(13, STATUS_NAME, "404"), STATUS_500(14, STATUS_NAME, "500"), - ACCEPT_CHARSET(15, Header.ACCEPT_CHARSET), - ACCEPT_ENCODING(16, Header.ACCEPT_ENCODING, "gzip, deflate", false), - ACCEPT_LANGUAGE(17, Header.ACCEPT_LANGUAGE), - ACCEPT_RANGES(18, Header.ACCEPT_RANGES), - ACCEPT(19, Header.ACCEPT), - ACCESS_CONTROL_ALLOW_ORIGIN(20, Header.ACCESS_CONTROL_ALLOW_ORIGIN), - AGE(21, Header.AGE), - ALLOW(22, Header.ALLOW), - AUTHORIZATION(23, Header.AUTHORIZATION), - CACHE_CONTROL(24, Header.CACHE_CONTROL), - CONTENT_DISPOSITION(25, Header.CONTENT_DISPOSITION), - CONTENT_ENCODING(26, Header.CONTENT_ENCODING), - CONTENT_LANGUAGE(27, Header.CONTENT_LANGUAGE), - CONTENT_LENGTH(28, Header.CONTENT_LENGTH), - CONTENT_LOCATION(29, Header.CONTENT_LOCATION), - CONTENT_RANGE(30, Header.CONTENT_RANGE), - CONTENT_TYPE(31, Header.CONTENT_TYPE), - COOKIE(32, Header.COOKIE), - DATE(33, Header.DATE), - ETAG(34, Header.ETAG), - EXPECT(35, Header.EXPECT), - EXPIRES(36, Header.EXPIRES), - FROM(37, Header.FROM), - HOST(38, Header.HOST), - IF_MATCH(39, Header.IF_MATCH), - IF_MODIFIED_SINCE(40, Header.IF_MODIFIED_SINCE), - IF_NONE_MATCH(41, Header.IF_NONE_MATCH), - IF_RANGE(42, Header.IF_RANGE), - IF_UNMODIFIED_SINCE(43, Header.IF_UNMODIFIED_SINCE), - LAST_MODIFIED(44, Header.LAST_MODIFIED), - LINK(45, Header.LINK), - LOCATION(46, Header.LOCATION), - MAX_FORWARDS(47, Header.MAX_FORWARDS), - PROXY_AUTHENTICATE(48, Header.PROXY_AUTHENTICATE), - PROXY_AUTHORIZATION(49, Header.PROXY_AUTHORIZATION), - RANGE(50, Header.CONTENT_LOCATION), - REFERER(51, Header.REFERER), - REFRESH(52, Header.REFRESH), - RETRY_AFTER(53, Header.RETRY_AFTER), - SERVER(54, Header.SERVER), - SET_COOKIE(55, Header.SET_COOKIE), - STRICT_TRANSPORT_SECURITY(56, Header.STRICT_TRANSPORT_SECURITY), - TRANSFER_ENCODING(57, Header.TRANSFER_ENCODING), - USER_AGENT(58, Header.USER_AGENT), - VARY(59, Header.VARY), - VIA(60, Header.VIA), - WWW_AUTHENTICATE(61, Header.WWW_AUTHENTICATE); + ACCEPT_CHARSET(15, HeaderNames.ACCEPT_CHARSET), + ACCEPT_ENCODING(16, Http.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), + 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_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), + 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), + IF_MODIFIED_SINCE(40, HeaderNames.IF_MODIFIED_SINCE), + IF_NONE_MATCH(41, HeaderNames.IF_NONE_MATCH), + IF_RANGE(42, Http.HeaderNames.IF_RANGE), + IF_UNMODIFIED_SINCE(43, HeaderNames.IF_UNMODIFIED_SINCE), + LAST_MODIFIED(44, Http.HeaderNames.LAST_MODIFIED), + LINK(45, HeaderNames.LINK), + LOCATION(46, HeaderNames.LOCATION), + MAX_FORWARDS(47, Http.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), + 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), + VARY(59, HeaderNames.VARY), + VIA(60, HeaderNames.VIA), + WWW_AUTHENTICATE(61, Http.HeaderNames.WWW_AUTHENTICATE); /** * Maximal index of the static table of headers. diff --git a/nima/http2/http2/src/test/java/io/helidon/nima/http2/DynamicTableTest.java b/nima/http2/http2/src/test/java/io/helidon/nima/http2/DynamicTableTest.java index 3bca1115c65..dee7ebf87bb 100644 --- a/nima/http2/http2/src/test/java/io/helidon/nima/http2/DynamicTableTest.java +++ b/nima/http2/http2/src/test/java/io/helidon/nima/http2/DynamicTableTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -16,7 +16,8 @@ package io.helidon.nima.http2; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http; +import io.helidon.common.http.Http.HeaderNames; import org.junit.jupiter.api.Test; @@ -37,18 +38,18 @@ void testDynamicTable() { assertThat(table.protocolMaxTableSize(), is(80L)); // index 1 - table.add(Header.create("a"), "b"); + table.add(Http.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(Header.create("b"), "c"); + table.add(Http.HeaderNames.create("b"), "c"); assertThat(table.currentTableSize(), is(68)); testRecord(table, Http2Headers.StaticHeader.MAX_INDEX + 1, "b", "c"); testRecord(table, Http2Headers.StaticHeader.MAX_INDEX + 2, "a", "b"); // replaces index 2 (evicts 2, creates new 2) - table.add(Header.create("c"), "de"); + table.add(HeaderNames.create("c"), "de"); assertThat(table.currentTableSize(), is(69)); testRecord(table, Http2Headers.StaticHeader.MAX_INDEX + 1, "c", "de"); testRecord(table, Http2Headers.StaticHeader.MAX_INDEX + 2, "b", "c"); diff --git a/nima/http2/http2/src/test/java/io/helidon/nima/http2/Http2HeadersTest.java b/nima/http2/http2/src/test/java/io/helidon/nima/http2/Http2HeadersTest.java index d41ec254b99..b144303521c 100644 --- a/nima/http2/http2/src/test/java/io/helidon/nima/http2/Http2HeadersTest.java +++ b/nima/http2/http2/src/test/java/io/helidon/nima/http2/Http2HeadersTest.java @@ -21,8 +21,8 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.WritableHeaders; import io.helidon.nima.http2.Http2Headers.DynamicTable; import io.helidon.nima.http2.Http2Headers.HeaderRecord; @@ -35,7 +35,7 @@ import static org.hamcrest.MatcherAssert.assertThat; class Http2HeadersTest { - private static final HeaderName CUSTOM_HEADER_NAME = Header.create("custom-key"); + private static final HeaderName CUSTOM_HEADER_NAME = HeaderNames.create("custom-key"); /* https://www.rfc-editor.org/rfc/rfc7541.html#appendix-C.2.1 @@ -46,7 +46,7 @@ void testC_2_1() { DynamicTable dynamicTable = DynamicTable.create(Http2Settings.create()); Headers requestHeaders = headers(hexEncoded, dynamicTable).httpHeaders(); - assertThat(requestHeaders.get(Header.create("custom-key")).value(), is("custom-header")); + assertThat(requestHeaders.get(HeaderNames.create("custom-key")).value(), is("custom-header")); } BufferData data(String hexEncoded) { @@ -76,7 +76,7 @@ void testC_2_3() { DynamicTable dynamicTable = DynamicTable.create(Http2Settings.create()); Headers requestHeaders = headers(hexEncoded, dynamicTable).httpHeaders(); - assertThat(requestHeaders.get(Header.create("password")).value(), is("secret")); + assertThat(requestHeaders.get(Http.HeaderNames.create("password")).value(), is("secret")); assertThat("Dynamic table should be empty", dynamicTable.currentTableSize(), is(0)); } @@ -124,13 +124,13 @@ void testC_3() { assertThat(http2Headers.scheme(), is("http")); assertThat(http2Headers.path(), is("/")); assertThat(http2Headers.authority(), is("www.example.com")); - assertThat(requestHeaders.get(Header.create("cache-control")).value(), is("no-cache")); + assertThat(requestHeaders.get(Http.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(Header.CACHE_CONTROL)); + assertThat(headerRecord.headerName(), is(Http.HeaderNames.CACHE_CONTROL)); assertThat(headerRecord.value(), is("no-cache")); headerRecord = dynamicTable.get(Http2Headers.StaticHeader.MAX_INDEX + 2); assertThat(headerRecord.headerName(), is(Http2Headers.AUTHORITY_NAME)); @@ -154,7 +154,7 @@ void testC_3() { assertThat(headerRecord.headerName(), is(CUSTOM_HEADER_NAME)); assertThat(headerRecord.value(), is("custom-value")); headerRecord = dynamicTable.get(Http2Headers.StaticHeader.MAX_INDEX + 2); - assertThat(headerRecord.headerName(), is(Header.CACHE_CONTROL)); + assertThat(headerRecord.headerName(), is(HeaderNames.CACHE_CONTROL)); assertThat(headerRecord.value(), is("no-cache")); headerRecord = dynamicTable.get(Http2Headers.StaticHeader.MAX_INDEX + 3); assertThat(headerRecord.headerName(), is(Http2Headers.AUTHORITY_NAME)); @@ -214,13 +214,13 @@ void testC_4() { assertThat(http2Headers.scheme(), is("http")); assertThat(http2Headers.path(), is("/")); assertThat(http2Headers.authority(), is("www.example.com")); - assertThat(requestHeaders.get(Header.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(Header.CACHE_CONTROL)); + assertThat(headerRecord.headerName(), is(Http.HeaderNames.CACHE_CONTROL)); assertThat(headerRecord.value(), is("no-cache")); headerRecord = dynamicTable.get(Http2Headers.StaticHeader.MAX_INDEX + 2); assertThat(headerRecord.headerName(), is(Http2Headers.AUTHORITY_NAME)); @@ -244,7 +244,7 @@ void testC_4() { assertThat(headerRecord.headerName(), is(CUSTOM_HEADER_NAME)); assertThat(headerRecord.value(), is("custom-value")); headerRecord = dynamicTable.get(Http2Headers.StaticHeader.MAX_INDEX + 2); - assertThat(headerRecord.headerName(), is(Header.CACHE_CONTROL)); + assertThat(headerRecord.headerName(), is(HeaderNames.CACHE_CONTROL)); assertThat(headerRecord.value(), is("no-cache")); headerRecord = dynamicTable.get(Http2Headers.StaticHeader.MAX_INDEX + 3); assertThat(headerRecord.headerName(), is(Http2Headers.AUTHORITY_NAME)); diff --git a/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2CallChainBase.java b/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2CallChainBase.java index 7ad74f25b43..58de9afbad3 100644 --- a/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2CallChainBase.java +++ b/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2CallChainBase.java @@ -43,7 +43,7 @@ import io.helidon.nima.webclient.http1.Http1ClientResponse; import io.helidon.nima.webclient.spi.WebClientService; -import static io.helidon.common.http.Http.Header.CONTENT_ENCODING; +import static io.helidon.common.http.Http.HeaderNames.CONTENT_ENCODING; import static io.helidon.nima.webclient.api.ClientRequestBase.USER_AGENT_HEADER; abstract class Http2CallChainBase implements WebClientService.Chain { @@ -82,8 +82,8 @@ public WebClientServiceResponse proceed(WebClientServiceRequest serviceRequest) ClientUri uri = serviceRequest.uri(); requestHeaders = serviceRequest.headers(); - requestHeaders.setIfAbsent(Http.Header.create(Http.Header.HOST, uri.authority())); - requestHeaders.remove(Http.Header.CONNECTION, LogHeaderConsumer.INSTANCE); + requestHeaders.setIfAbsent(Http.Headers.create(Http.HeaderNames.HOST, uri.authority())); + requestHeaders.remove(Http.HeaderNames.CONNECTION, LogHeaderConsumer.INSTANCE); requestHeaders.setIfAbsent(USER_AGENT_HEADER); Http2ConnectionAttemptResult result = Http2ConnectionCache.newStream(webClient, @@ -232,12 +232,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.HeaderValue httpHeader) { + public void accept(Http.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/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2CallEntityChain.java b/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2CallEntityChain.java index ac5a0ebd7f8..b7b3baefe35 100644 --- a/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2CallEntityChain.java +++ b/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2CallEntityChain.java @@ -59,7 +59,7 @@ protected WebClientServiceResponse doProceed(WebClientServiceRequest serviceRequ entityBytes = entityBytes(entity, headers); } - headers.set(Http.Header.create(Http.Header.CONTENT_LENGTH, entityBytes.length)); + headers.set(Http.Headers.create(Http.HeaderNames.CONTENT_LENGTH, entityBytes.length)); ClientUri uri = serviceRequest.uri(); diff --git a/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2ClientConnectionHandler.java b/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2ClientConnectionHandler.java index d964374ce71..b941e30fdaf 100644 --- a/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2ClientConnectionHandler.java +++ b/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2ClientConnectionHandler.java @@ -50,11 +50,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.HeaderValue CONNECTION_UPGRADE_HEADER = Http.Header.createCached(Http.Header.CONNECTION, - "Upgrade, HTTP2-Settings"); + private static final Http.Header CONNECTION_UPGRADE_HEADER = Http.Headers.createCached(Http.HeaderNames.CONNECTION, + "Upgrade, HTTP2-Settings"); // h2c stands for HTTP/2 plaintext protocol (only used without TLS) - private static final Http.HeaderValue UPGRADE_HEADER = Http.Header.createCached(Http.Header.UPGRADE, "h2c"); - private static final Http.HeaderName HTTP2_SETTINGS_HEADER = Http.Header.create("HTTP2-Settings"); + 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"); // todo requires handling of timeouts and removal from this queue private final Map h2ConnByConn = diff --git a/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2ClientRequestImpl.java b/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2ClientRequestImpl.java index 5947632fee4..add99954244 100644 --- a/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2ClientRequestImpl.java +++ b/nima/http2/webclient/src/main/java/io/helidon/nima/http2/webclient/Http2ClientRequestImpl.java @@ -164,11 +164,11 @@ private Http2ClientResponse invokeEntityFollowRedirects(Object entity) { int code = clientResponse.status().code(); if (code < 300 || code >= 400) { return clientResponse; - } else if (!clientResponse.headers().contains(Http.Header.LOCATION)) { - throw new IllegalStateException("There is no " + Http.Header.LOCATION + " header present in the response! " + } else if (!clientResponse.headers().contains(Http.HeaderNames.LOCATION)) { + throw new IllegalStateException("There is no " + Http.HeaderNames.LOCATION + " header present in the response! " + "It is not clear where to redirect."); } - String redirectedUri = clientResponse.headers().get(Http.Header.LOCATION).value(); + String redirectedUri = clientResponse.headers().get(Http.HeaderNames.LOCATION).value(); URI newUri = URI.create(redirectedUri); ClientUri redirectUri = ClientUri.create(newUri); diff --git a/nima/http2/webclient/src/test/java/io/helidon/nima/http2/webclient/Http2WebClientTest.java b/nima/http2/webclient/src/test/java/io/helidon/nima/http2/webclient/Http2WebClientTest.java index 4da52b83d71..ca4ffcdafe1 100644 --- a/nima/http2/webclient/src/test/java/io/helidon/nima/http2/webclient/Http2WebClientTest.java +++ b/nima/http2/webclient/src/test/java/io/helidon/nima/http2/webclient/Http2WebClientTest.java @@ -47,7 +47,7 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import static io.helidon.common.http.Http.Header.USER_AGENT; +import static io.helidon.common.http.Http.HeaderNames.USER_AGENT; import static io.helidon.common.http.Http.Method.GET; import static io.helidon.common.http.Http.Method.POST; import static io.helidon.common.http.Http.Method.PUT; @@ -57,10 +57,10 @@ @ServerTest class Http2WebClientTest { - private static final Http.HeaderName CLIENT_CUSTOM_HEADER_NAME = Http.Header.create("client-custom-header"); - private static final Http.HeaderName SERVER_CUSTOM_HEADER_NAME = Http.Header.create("server-custom-header"); - private static final Http.HeaderName SERVER_HEADER_FROM_PARAM_NAME = Http.Header.create("header-from-param"); - private static final Http.HeaderName CLIENT_USER_AGENT_HEADER_NAME = Http.Header.create("client-user-agent"); + 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 ExecutorService executorService; private static int plainPort; private static final LazyValue priorKnowledgeClient = LazyValue.create(() -> Http2Client.builder() diff --git a/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Connection.java b/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Connection.java index 44abe02eb47..61560c050f3 100755 --- a/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Connection.java +++ b/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Connection.java @@ -28,10 +28,8 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.buffers.DataReader; -import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.HttpPrologue; import io.helidon.common.task.InterruptableTask; import io.helidon.nima.http2.ConnectionFlowControl; @@ -533,9 +531,9 @@ private void ackSettings() { if (upgradeHeaders != null) { // initial request from outside - Headers httpHeaders = upgradeHeaders.httpHeaders(); - boolean hasEntity = httpHeaders.contains(Header.CONTENT_LENGTH) - || httpHeaders.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED); + io.helidon.common.http.Headers httpHeaders = upgradeHeaders.httpHeaders(); + boolean hasEntity = httpHeaders.contains(HeaderNames.CONTENT_LENGTH) + || httpHeaders.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED); // we now have all information needed to execute Http2Stream stream = stream(1).stream(); stream.prologue(upgradePrologue); diff --git a/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2ServerRequest.java b/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2ServerRequest.java index 0a9a551b9ee..c3ef1712a50 100644 --- a/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2ServerRequest.java +++ b/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2ServerRequest.java @@ -22,7 +22,7 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.context.Context; import io.helidon.common.context.Contexts; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http; import io.helidon.common.http.HttpPrologue; import io.helidon.common.http.RoutedPath; import io.helidon.common.http.ServerRequestHeaders; @@ -153,7 +153,7 @@ public String authority() { } @Override - public void header(HeaderValue header) { + public void header(Http.Header header) { if (writable == null) { writable = WritableHeaders.create(headers); } diff --git a/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2ServerResponse.java b/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2ServerResponse.java index 76b31c70acb..6a96dec0fab 100644 --- a/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2ServerResponse.java +++ b/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2ServerResponse.java @@ -23,8 +23,8 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.HeaderNames; +import io.helidon.common.http.Http.Headers; import io.helidon.common.http.ServerResponseHeaders; import io.helidon.nima.http2.FlowControl; import io.helidon.nima.http2.Http2Flag; @@ -65,7 +65,7 @@ class Http2ServerResponse extends ServerResponseBase { } @Override - public Http2ServerResponse header(HeaderValue header) { + public Http2ServerResponse header(Header header) { headers.set(header); return this; } @@ -84,11 +84,11 @@ public void send(byte[] entityBytes) { // handle content encoding byte[] bytes = entityBytes(entityBytes); - headers.setIfAbsent(Header.create(Header.CONTENT_LENGTH, - true, - false, - String.valueOf(bytes.length))); - headers.setIfAbsent(Header.create(Header.DATE, true, false, Http.DateTime.rfc1123String())); + headers.setIfAbsent(Headers.create(HeaderNames.CONTENT_LENGTH, + true, + false, + String.valueOf(bytes.length))); + headers.setIfAbsent(Headers.create(HeaderNames.DATE, true, false, Http.DateTime.rfc1123String())); Http2Headers http2Headers = Http2Headers.create(headers); http2Headers.status(status()); @@ -268,16 +268,16 @@ private void write(BufferData buffer) throws IOException { private void sendFirstChunkOnly() { int contentLength; if (firstBuffer == null) { - headers.set(HeaderValues.CONTENT_LENGTH_ZERO); + headers.set(Headers.CONTENT_LENGTH_ZERO); contentLength = 0; } else { - headers.set(Header.create(Header.CONTENT_LENGTH, - true, - false, - String.valueOf(firstBuffer.available()))); + headers.set(Headers.create(HeaderNames.CONTENT_LENGTH, + true, + false, + String.valueOf(firstBuffer.available()))); contentLength = firstBuffer.available(); } - headers.setIfAbsent(Header.create(Header.DATE, true, false, Http.DateTime.rfc1123String())); + headers.setIfAbsent(Headers.create(HeaderNames.DATE, true, false, Http.DateTime.rfc1123String())); Http2Headers http2Headers = Http2Headers.create(headers); http2Headers.status(status); @@ -307,7 +307,7 @@ private void sendFirstChunkOnly() { } private void sendHeadersAndPrepare() { - headers.setIfAbsent(Header.create(Header.DATE, true, false, Http.DateTime.rfc1123String())); + headers.setIfAbsent(Headers.create(HeaderNames.DATE, true, false, Http.DateTime.rfc1123String())); Http2Headers http2Headers = Http2Headers.create(headers); http2Headers.status(status); diff --git a/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Stream.java b/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Stream.java index f51cc9599a8..ca76b4df054 100644 --- a/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Stream.java +++ b/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Stream.java @@ -25,7 +25,7 @@ import io.helidon.common.http.DirectHandler; import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.HttpPrologue; import io.helidon.common.http.RequestException; import io.helidon.common.http.ServerResponseHeaders; @@ -293,7 +293,7 @@ public void run() { ServerResponseHeaders headers = response.headers(); byte[] message = response.entity().orElse(BufferData.EMPTY_BYTES); if (message.length != 0) { - headers.set(Header.create(Header.CONTENT_LENGTH, String.valueOf(message.length))); + headers.set(Http.Headers.create(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(message.length))); } Http2Headers http2Headers = Http2Headers.create(headers); if (message.length == 0) { @@ -351,8 +351,8 @@ private BufferData readEntityFromPipeline() { private void handle() { Headers httpHeaders = headers.httpHeaders(); - if (httpHeaders.contains(Header.CONTENT_LENGTH)) { - this.expectedLength = httpHeaders.get(Header.CONTENT_LENGTH).value(long.class); + if (httpHeaders.contains(Http.HeaderNames.CONTENT_LENGTH)) { + this.expectedLength = httpHeaders.get(HeaderNames.CONTENT_LENGTH).value(long.class); } subProtocolHandler = null; @@ -378,8 +378,8 @@ private void handle() { ContentEncodingContext contentEncodingContext = ctx.listenerContext().contentEncodingContext(); ContentDecoder decoder; if (contentEncodingContext.contentDecodingEnabled()) { - if (httpHeaders.contains(Header.CONTENT_ENCODING)) { - String contentEncoding = httpHeaders.get(Header.CONTENT_ENCODING).value(); + if (httpHeaders.contains(Http.HeaderNames.CONTENT_ENCODING)) { + String contentEncoding = httpHeaders.get(Http.HeaderNames.CONTENT_ENCODING).value(); if (contentEncodingContext.contentDecodingSupported(contentEncoding)) { decoder = contentEncodingContext.decoder(contentEncoding); } else { diff --git a/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Upgrader.java b/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Upgrader.java index 838e7ab8160..23395d6f3bd 100644 --- a/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Upgrader.java +++ b/nima/http2/webserver/src/main/java/io/helidon/nima/http2/webserver/Http2Upgrader.java @@ -22,7 +22,7 @@ import io.helidon.common.buffers.BufferData; import io.helidon.common.buffers.DataWriter; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http; import io.helidon.common.http.Http.HeaderName; import io.helidon.common.http.HttpPrologue; import io.helidon.common.http.WritableHeaders; @@ -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 = Header.create("HTTP2-Settings"); + private static final HeaderName HTTP2_SETTINGS_HEADER_NAME = Http.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(Header.HOST, + headers.remove(Http.HeaderNames.HOST, it -> http2Headers.authority(it.value())); http2Headers.scheme("http"); // TODO need to get if https (ctx)? diff --git a/nima/observe/log/src/main/java/io/helidon/nima/observe/log/LogService.java b/nima/observe/log/src/main/java/io/helidon/nima/observe/log/LogService.java index 00391fe9e58..93fb689aef0 100644 --- a/nima/observe/log/src/main/java/io/helidon/nima/observe/log/LogService.java +++ b/nima/observe/log/src/main/java/io/helidon/nima/observe/log/LogService.java @@ -38,6 +38,7 @@ import io.helidon.common.config.Config; import io.helidon.common.http.Http; import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.common.media.type.MediaType; import io.helidon.nima.http.media.EntityReader; import io.helidon.nima.http.media.EntityWriter; @@ -67,7 +68,7 @@ class LogService implements HttpService { private final AtomicBoolean logHandlingInitialized = new AtomicBoolean(); private final boolean permitAll; private final boolean logStreamEnabled; - private final Http.HeaderValue logStreamMediaTypeHeader; + private final Http.Header logStreamMediaTypeHeader; private final long logStreamSleepSeconds; private final int logStreamQueueSize; private final String logStreamIdleString; @@ -261,8 +262,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.HeaderValue logStreamMediaTypeHeader = Http.Header.create(Http.Header.CONTENT_TYPE, - HttpMediaType.PLAINTEXT_UTF_8.text()); + private Http.Header logStreamMediaTypeHeader = Http.Headers.create(Http.HeaderNames.CONTENT_TYPE, + HttpMediaTypes.PLAINTEXT_UTF_8.text()); private Charset logStreamCharset = StandardCharsets.UTF_8; private long logStreamSleepSeconds = 5L; private int logStreamQueueSize = 100; @@ -304,7 +305,7 @@ Builder logStreamEnabled(boolean logStreamAllow) { } Builder logStreamMediaType(HttpMediaType logStreamMediaType) { - this.logStreamMediaTypeHeader = Http.Header.createCached(Http.Header.CONTENT_TYPE, logStreamMediaType.text()); + this.logStreamMediaTypeHeader = Http.Headers.createCached(Http.HeaderNames.CONTENT_TYPE, logStreamMediaType.text()); this.logStreamCharset = logStreamMediaType.charset().map(Charset::forName).orElse(StandardCharsets.UTF_8); return this; } diff --git a/nima/observe/metrics/src/main/java/io/helidon/nima/observe/metrics/MetricsFeature.java b/nima/observe/metrics/src/main/java/io/helidon/nima/observe/metrics/MetricsFeature.java index 9b90e0eab81..01886bfdea1 100644 --- a/nima/observe/metrics/src/main/java/io/helidon/nima/observe/metrics/MetricsFeature.java +++ b/nima/observe/metrics/src/main/java/io/helidon/nima/observe/metrics/MetricsFeature.java @@ -194,7 +194,7 @@ private void getMatching(ServerRequest req, Iterable scopeSelection, Iterable nameSelection) { MediaType mediaType = bestAccepted(req); - res.header(Http.HeaderValues.CACHE_NO_CACHE); + res.header(Http.Headers.CACHE_NO_CACHE); if (mediaType == null) { res.status(Http.Status.NOT_ACCEPTABLE_406); res.send(); @@ -275,7 +275,7 @@ private void postRequestProcessing(PostRequestMetricsSupport prms, private void rejectOptions(ServerRequest req, ServerResponse res) { // Options used to return metadata but it's no longer supported unless we restore JSON support. - res.header(Http.Header.ALLOW, "GET"); + res.header(Http.HeaderNames.ALLOW, "GET"); res.status(Http.Status.METHOD_NOT_ALLOWED_405); res.send(); } diff --git a/nima/sse/sse/src/main/java/io/helidon/nima/sse/SseEvent.java b/nima/sse/sse/src/main/java/io/helidon/nima/sse/SseEvent.java index aec9adb8cc6..a9daa5745dd 100644 --- a/nima/sse/sse/src/main/java/io/helidon/nima/sse/SseEvent.java +++ b/nima/sse/sse/src/main/java/io/helidon/nima/sse/SseEvent.java @@ -128,7 +128,7 @@ public T data(Class clazz, MediaType mediaType) { WritableHeaders headers; if (!mediaType.equals(MediaTypes.WILDCARD)) { headers = WritableHeaders.create(); - headers.set(Http.Header.CONTENT_TYPE, mediaType.text()); + headers.set(Http.HeaderNames.CONTENT_TYPE, mediaType.text()); } else { headers = EMPTY_HEADERS; } diff --git a/nima/sse/webserver/src/main/java/io/helidon/nima/sse/webserver/SseSink.java b/nima/sse/webserver/src/main/java/io/helidon/nima/sse/webserver/SseSink.java index 7c006f069ff..09558b89a39 100644 --- a/nima/sse/webserver/src/main/java/io/helidon/nima/sse/webserver/SseSink.java +++ b/nima/sse/webserver/src/main/java/io/helidon/nima/sse/webserver/SseSink.java @@ -32,7 +32,7 @@ import io.helidon.nima.webserver.http.ServerResponse; import io.helidon.nima.webserver.http.spi.Sink; -import static io.helidon.common.http.Http.HeaderValues.CONTENT_TYPE_EVENT_STREAM; +import static io.helidon.common.http.Http.Headers.CONTENT_TYPE_EVENT_STREAM; /** * Implementation of an SSE sink. Emits {@link SseEvent}s. diff --git a/nima/tests/benchmark/jmh/src/main/java/io/helidon/nima/tests/benchmark/jmh/Http1ParsingJmhTest.java b/nima/tests/benchmark/jmh/src/main/java/io/helidon/nima/tests/benchmark/jmh/Http1ParsingJmhTest.java index 40850b916f8..e520cd14ca7 100644 --- a/nima/tests/benchmark/jmh/src/main/java/io/helidon/nima/tests/benchmark/jmh/Http1ParsingJmhTest.java +++ b/nima/tests/benchmark/jmh/src/main/java/io/helidon/nima/tests/benchmark/jmh/Http1ParsingJmhTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -21,7 +21,7 @@ import java.util.List; import io.helidon.common.buffers.DataReader; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http; import io.helidon.common.http.HttpPrologue; import io.helidon.common.http.WritableHeaders; import io.helidon.nima.webserver.http1.Http1Headers; @@ -96,8 +96,8 @@ private void readRequest(Blackhole bh, DataReader reader) { HttpPrologue httpPrologue = prologue.readPrologue(); WritableHeaders httpHeaders = headers.readHeaders(httpPrologue); - boolean hasContent = httpHeaders.contains(Header.CONTENT_LENGTH); - String authority = httpHeaders.get(Header.HOST).value(); + boolean hasContent = httpHeaders.contains(Http.HeaderNames.CONTENT_LENGTH); + String authority = httpHeaders.get(Http.HeaderNames.HOST).value(); bh.consume(hasContent); bh.consume(authority); diff --git a/nima/tests/benchmark/jmh/src/main/java/io/helidon/nima/tests/benchmark/jmh/HttpJmhTest.java b/nima/tests/benchmark/jmh/src/main/java/io/helidon/nima/tests/benchmark/jmh/HttpJmhTest.java index 9eab2058d0a..9eeb716d39d 100644 --- a/nima/tests/benchmark/jmh/src/main/java/io/helidon/nima/tests/benchmark/jmh/HttpJmhTest.java +++ b/nima/tests/benchmark/jmh/src/main/java/io/helidon/nima/tests/benchmark/jmh/HttpJmhTest.java @@ -25,8 +25,7 @@ import java.time.Duration; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.logging.common.LogConfig; import io.helidon.nima.webserver.WebServer; import io.helidon.nima.webserver.http.Handler; @@ -43,10 +42,10 @@ @State(Scope.Benchmark) public class HttpJmhTest { - private static final HeaderValue CONTENT_TYPE = Header.createCached(Header.CONTENT_TYPE, - "text/plain; charset=UTF-8"); - private static final HeaderValue CONTENT_LENGTH = Header.createCached(Header.CONTENT_LENGTH, "13"); - private static final HeaderValue SERVER = Header.createCached(Header.SERVER, "Nima"); + 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, "Nima"); private static final byte[] RESPONSE_BYTES = "Hello, World!".getBytes(StandardCharsets.UTF_8); private WebServer server; private int serverPort; diff --git a/nima/tests/integration/encoding/deflate/src/test/java/io/helidon/nima/tests/integration/encoding/deflate/DeflateEncodingTest.java b/nima/tests/integration/encoding/deflate/src/test/java/io/helidon/nima/tests/integration/encoding/deflate/DeflateEncodingTest.java index 1319ba758d6..60d23bd48de 100644 --- a/nima/tests/integration/encoding/deflate/src/test/java/io/helidon/nima/tests/integration/encoding/deflate/DeflateEncodingTest.java +++ b/nima/tests/integration/encoding/deflate/src/test/java/io/helidon/nima/tests/integration/encoding/deflate/DeflateEncodingTest.java @@ -53,7 +53,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.HeaderValue CONTENT_ENCODING_DEFLATE = Http.Header.create(Http.Header.CONTENT_ENCODING, "deflate"); + private static final Http.Header CONTENT_ENCODING_DEFLATE = Http.Headers.create(Http.HeaderNames.CONTENT_ENCODING, "deflate"); static { ByteArrayOutputStream baos; @@ -139,7 +139,7 @@ void testDeflateMultipleAcceptedEncodingsHttp2Client() { void testIt(io.helidon.nima.webclient.api.HttpClient client, String path, String acceptEncodingValue) { ClientResponseTyped response = client.put(path) - .header(Http.Header.ACCEPT_ENCODING, acceptEncodingValue) + .header(Http.HeaderNames.ACCEPT_ENCODING, acceptEncodingValue) .header(CONTENT_ENCODING_DEFLATE) .submit(DEFLATED_ENTITY, String.class); diff --git a/nima/tests/integration/encoding/gzip/src/test/java/io/helidon/nima/tests/integration/encoding/gzip/GzipEncodingTest.java b/nima/tests/integration/encoding/gzip/src/test/java/io/helidon/nima/tests/integration/encoding/gzip/GzipEncodingTest.java index e8d13843e21..6a5883e9435 100644 --- a/nima/tests/integration/encoding/gzip/src/test/java/io/helidon/nima/tests/integration/encoding/gzip/GzipEncodingTest.java +++ b/nima/tests/integration/encoding/gzip/src/test/java/io/helidon/nima/tests/integration/encoding/gzip/GzipEncodingTest.java @@ -52,7 +52,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.HeaderValue CONTENT_ENCODING_GZIP = Http.Header.create(Http.Header.CONTENT_ENCODING, "gzip"); + private static final Http.Header CONTENT_ENCODING_GZIP = Http.Headers.create(Http.HeaderNames.CONTENT_ENCODING, "gzip"); static { ByteArrayOutputStream baos; @@ -139,7 +139,7 @@ void testDeflateMultipleAcceptedEncodingsHttp2Client() { void testIt(io.helidon.nima.webclient.api.HttpClient client, String path, String acceptEncodingValue) { ClientResponseTyped response = client.put(path) - .header(Http.Header.ACCEPT_ENCODING, acceptEncodingValue) + .header(Http.HeaderNames.ACCEPT_ENCODING, acceptEncodingValue) .header(CONTENT_ENCODING_GZIP) .submit(GZIP_ENTITY, String.class); diff --git a/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/GetTest.java b/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/GetTest.java index 62a66446200..70ac77a068e 100644 --- a/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/GetTest.java +++ b/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/GetTest.java @@ -29,9 +29,8 @@ import java.util.Random; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.nima.http2.webserver.Http2Route; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; @@ -52,10 +51,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 = Header.create(REQUEST_HEADER_NAME_STRING); - private static final HeaderName RESPONSE_HEADER_NAME = Header.create(RESPONSE_HEADER_NAME_STRING); - private static final HeaderValue RESPONSE_HEADER_VALUE = Header.createCached(RESPONSE_HEADER_NAME, - RESPONSE_HEADER_VALUE_STRING); + private static final HeaderName REQUEST_HEADER_NAME = Http.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); static { Random random = new Random(); @@ -94,7 +93,7 @@ void testStringRoute() throws IOException, InterruptedException { assertThat(response.body(), is("Hello")); java.net.http.HttpHeaders headers = response.headers(); - assertThat(headers.firstValueAsLong(Header.CONTENT_LENGTH.defaultCase()), + assertThat(headers.firstValueAsLong(HeaderNames.CONTENT_LENGTH.defaultCase()), is(OptionalLong.of(5))); } @@ -109,7 +108,7 @@ void testByteRoute() throws IOException, InterruptedException { assertThat(response.statusCode(), is(Http.Status.OK_200.code())); assertThat(response.body(), is(BYTES)); java.net.http.HttpHeaders headers = response.headers(); - assertThat(headers.firstValueAsLong(Header.CONTENT_LENGTH.defaultCase()), + assertThat(headers.firstValueAsLong(HeaderNames.CONTENT_LENGTH.defaultCase()), is(OptionalLong.of(BYTES.length))); } @@ -125,7 +124,7 @@ void testChunkedRoute() throws IOException, InterruptedException { assertThat(response.statusCode(), is(Http.Status.OK_200.code())); assertThat(response.body(), is(BYTES)); java.net.http.HttpHeaders headers = response.headers(); - assertThat(headers.firstValueAsLong(Header.CONTENT_LENGTH.defaultCase()), + assertThat(headers.firstValueAsLong(HeaderNames.CONTENT_LENGTH.defaultCase()), is(OptionalLong.of(BYTES.length))); } @@ -143,7 +142,7 @@ void testHeadersRoute() throws IOException, InterruptedException { assertThat(response.body(), is("Hello")); java.net.http.HttpHeaders headers = response.headers(); - assertThat(headers.firstValueAsLong(Header.CONTENT_LENGTH.defaultCase()), + assertThat(headers.firstValueAsLong(Http.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/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/HeadersTest.java b/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/HeadersTest.java index f93f5caee0e..3ff80b74e4c 100644 --- a/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/HeadersTest.java +++ b/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/HeadersTest.java @@ -129,9 +129,9 @@ void trailerHeader() { .priorKnowledge(true) .request()) { Headers h = res.headers(); - assertThat(h.first(Http.Header.create("test")).orElse(null), is("before")); + assertThat(h.first(Http.HeaderNames.create("test")).orElse(null), is("before")); assertThat(res.as(String.class), is(DATA)); - assertThat(h.first(Http.Header.create("Trailer-header")).orElse(null), is("trailer-test")); + assertThat(h.first(Http.HeaderNames.create("Trailer-header")).orElse(null), is("trailer-test")); } } @@ -148,7 +148,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.Header.create(name)).orElse(null), is(DATA)); + assertThat("Headers " + name, h.first(Http.HeaderNames.create(name)).orElse(null), is(DATA)); } assertThat(res.as(String.class), is(DATA)); @@ -166,7 +166,7 @@ void continuationOutbound() { .priorKnowledge(true) .headers(hv -> { for (int i = 0; i < 500; i++) { - hv.add(Http.Header.createCached("test-header-" + i, DATA + i)); + hv.add(Http.Headers.createCached("test-header-" + i, DATA + i)); expected.add("test-header-" + i + "=" + DATA + i); } }) @@ -187,7 +187,7 @@ void continuationOutboundPost() { .priorKnowledge(true) .headers(hv -> { for (int i = 0; i < 500; i++) { - hv.add(Http.Header.createCached("test-header-" + i, DATA + i)); + hv.add(Http.Headers.createCached("test-header-" + i, DATA + i)); expected.add("test-header-" + i + "=" + DATA + i); } }) diff --git a/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/Http2ClientTest.java b/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/Http2ClientTest.java index 8bac7aa6829..8ced7156f88 100644 --- a/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/Http2ClientTest.java +++ b/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/Http2ClientTest.java @@ -19,7 +19,7 @@ import io.helidon.common.configurable.Resource; import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.pki.Keys; import io.helidon.nima.common.tls.Tls; import io.helidon.nima.http2.webclient.Http2Client; @@ -44,7 +44,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 HeaderValue TEST_HEADER = Header.create(Header.create(TEST_HEADER_NAME), TEST_HEADER_VALUE); + private static final Header TEST_HEADER = Http.Headers.create(HeaderNames.create(TEST_HEADER_NAME), TEST_HEADER_VALUE); private final Http1Client http1Client; private final Http2Client tlsClient; private final Http2Client plainClient; diff --git a/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/PostTest.java b/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/PostTest.java index 4c7466dad6d..980cf889f51 100644 --- a/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/PostTest.java +++ b/nima/tests/integration/http2/client/src/test/java/io/helidon/nima/tests/integration/http2/client/PostTest.java @@ -25,9 +25,8 @@ import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.nima.http2.webclient.Http2Client; import io.helidon.nima.http2.webclient.Http2ClientResponse; import io.helidon.nima.webserver.WebServer; @@ -45,13 +44,13 @@ class PostTest { private static final byte[] BYTES = new byte[256]; - private static final HeaderName REQUEST_HEADER_NAME = Header.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 HeaderValue REQUEST_HEADER_VALUE = Header.createCached(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); - private static final HeaderName RESPONSE_HEADER_NAME = Header.create("X-REsponSE-HeADER"); + private static final Http.Header REQUEST_HEADER_VALUE = Http.Headers.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 HeaderValue RESPONSE_HEADER_VALUE = Header.create(RESPONSE_HEADER_NAME, - RESPONSE_HEADER_VALUE_STRING); + private static final Http.Header RESPONSE_HEADER_VALUE = Http.Headers.create(RESPONSE_HEADER_NAME, + RESPONSE_HEADER_VALUE_STRING); private static WebServer server; private static Http2Client client; diff --git a/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/GetTest.java b/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/GetTest.java index b977a01fad5..157bb187f83 100644 --- a/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/GetTest.java +++ b/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/GetTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -29,9 +29,7 @@ import java.util.Random; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; import io.helidon.nima.webserver.http.HttpRouting; @@ -46,12 +44,12 @@ @ServerTest class GetTest { private static final byte[] BYTES = new byte[256]; - private static final HeaderName REQUEST_HEADER_NAME = Header.create("X-ReQUEst-header"); + private static final HeaderName REQUEST_HEADER_NAME = Http.HeaderNames.create("X-ReQUEst-header"); private static final String REQUEST_HEADER_VALUE = "some nice value"; - private static final HeaderName RESPONSE_HEADER_NAME = Header.create("X-REsponSE-HeADER"); + private static final HeaderName RESPONSE_HEADER_NAME = Http.HeaderNames.create("X-REsponSE-HeADER"); private static final String RESPONSE_HEADER_VALUE_STRING = "another nice value"; - private static final HeaderValue RESPONSE_HEADER_VALUE = Header.create(RESPONSE_HEADER_NAME, - RESPONSE_HEADER_VALUE_STRING); + private static final Http.Header RESPONSE_HEADER_VALUE = Http.Headers.create(RESPONSE_HEADER_NAME, + RESPONSE_HEADER_VALUE_STRING); static { Random random = new Random(); diff --git a/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/Http2ErrorHandlingWithOutputStreamTest.java b/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/Http2ErrorHandlingWithOutputStreamTest.java index e72242be334..8bb32414464 100644 --- a/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/Http2ErrorHandlingWithOutputStreamTest.java +++ b/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/Http2ErrorHandlingWithOutputStreamTest.java @@ -34,8 +34,8 @@ import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; import io.helidon.nima.testing.junit5.webserver.SetUpServer; -import io.helidon.nima.webserver.WebServerConfig; import io.helidon.nima.webserver.WebServer; +import io.helidon.nima.webserver.WebServerConfig; import io.helidon.nima.webserver.http.ErrorHandler; import io.helidon.nima.webserver.http.HttpRouting; import io.helidon.nima.webserver.http.ServerRequest; @@ -57,8 +57,8 @@ @ServerTest class Http2ErrorHandlingWithOutputStreamTest { - private static final Http.HeaderName MAIN_HEADER_NAME = Http.Header.create("main-handler"); - private static final Http.HeaderName ERROR_HEADER_NAME = Http.Header.create("error-handler"); + 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 HttpClient httpClient; private final int plainPort; private final int tlsPort; diff --git a/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/Http2ServerTest.java b/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/Http2ServerTest.java index f42a7376cd9..d17257c4da7 100644 --- a/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/Http2ServerTest.java +++ b/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/Http2ServerTest.java @@ -27,7 +27,7 @@ import io.helidon.common.configurable.Resource; import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.pki.Keys; import io.helidon.nima.common.tls.Tls; import io.helidon.nima.http2.webserver.Http2Route; @@ -36,8 +36,8 @@ import io.helidon.nima.testing.junit5.webserver.SetUpServer; import io.helidon.nima.webclient.http1.Http1Client; import io.helidon.nima.webclient.http1.Http1ClientResponse; -import io.helidon.nima.webserver.WebServerConfig; import io.helidon.nima.webserver.WebServer; +import io.helidon.nima.webserver.WebServerConfig; import io.helidon.nima.webserver.http.HttpRouting; import io.helidon.nima.webserver.http.ServerRequest; import io.helidon.nima.webserver.http.ServerResponse; @@ -53,7 +53,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 HeaderValue TEST_HEADER = Header.create(Header.create(TEST_HEADER_NAME), TEST_HEADER_VALUE); + private static final Header TEST_HEADER = Http.Headers.create(HeaderNames.create(TEST_HEADER_NAME), TEST_HEADER_VALUE); private final int plainPort; private final int tlsPort; private final Http1Client http1Client; diff --git a/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/PostTest.java b/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/PostTest.java index e95c8453fc9..f21d285d9aa 100644 --- a/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/PostTest.java +++ b/nima/tests/integration/http2/server/src/test/java/io/helidon/nima/tests/integration/http2/webserver/PostTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -30,9 +30,7 @@ import java.util.Random; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; import io.helidon.nima.webserver.http.Handler; @@ -48,13 +46,13 @@ @ServerTest class PostTest { private static final byte[] BYTES = new byte[256]; - private static final HeaderName REQUEST_HEADER_NAME = Header.create("X-REquEst-HEADeR"); + private static final HeaderName REQUEST_HEADER_NAME = Http.HeaderNames.create("X-REquEst-HEADeR"); private static final String REQUEST_HEADER_VALUE_STRING = "some nice value"; - private static final HeaderValue REQUEST_HEADER_VALUE = Header.create(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); - private static final HeaderName RESPONSE_HEADER_NAME = Header.create("X-REsponSE-HeADER"); + 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 String RESPONSE_HEADER_VALUE_STRING = "another nice value"; - private static final HeaderValue RESPONSE_HEADER_VALUE = Header.create(RESPONSE_HEADER_NAME, - RESPONSE_HEADER_VALUE_STRING); + private static final Http.Header RESPONSE_HEADER_VALUE = Http.Headers.create(RESPONSE_HEADER_NAME, + RESPONSE_HEADER_VALUE_STRING); static { Random random = new Random(); diff --git a/nima/tests/integration/media/string/src/test/java/io/helidon/nima/tests/integration/media/string/StringTest.java b/nima/tests/integration/media/string/src/test/java/io/helidon/nima/tests/integration/media/string/StringTest.java index 27649cbcc80..583df436295 100644 --- a/nima/tests/integration/media/string/src/test/java/io/helidon/nima/tests/integration/media/string/StringTest.java +++ b/nima/tests/integration/media/string/src/test/java/io/helidon/nima/tests/integration/media/string/StringTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -20,8 +20,8 @@ import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.common.media.type.MediaTypes; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; @@ -39,8 +39,8 @@ class StringTest { private static final HttpMediaType TEXT_ISO_8859_2 = HttpMediaType.create(MediaTypes.TEXT_PLAIN) .withCharset("ISO-8859-2"); - private static final HeaderValue ISO_8859_CONTENT_TYPE = Header.create(Header.CONTENT_TYPE, - TEXT_ISO_8859_2.text()); + private static final Header ISO_8859_CONTENT_TYPE = Http.Headers.create(Http.HeaderNames.CONTENT_TYPE, + TEXT_ISO_8859_2.text()); private static final String UTF_8_TEXT = "český řízný text"; private final Http1Client client; @@ -67,7 +67,7 @@ void testGetUtf8() { () -> assertThat(response.status(), is(Http.Status.OK_200)), () -> assertThat("Should contain content type plain/text; charset=UTF-8", response.headers().contentType(), - is(Optional.of(HttpMediaType.PLAINTEXT_UTF_8))), + is(Optional.of(HttpMediaTypes.PLAINTEXT_UTF_8))), () -> assertThat(response.as(String.class), is(UTF_8_TEXT))); } @@ -94,7 +94,7 @@ void testPostUtf8NoContentType() { () -> assertThat(response.status(), is(Http.Status.OK_200)), () -> assertThat("Should contain content type plain/text; charset=UTF-8", response.headers().contentType(), - is(Optional.of(HttpMediaType.PLAINTEXT_UTF_8))), - () -> assertThat(response.as(String.class), is(UTF_8_TEXT + ":" + HttpMediaType.PLAINTEXT_UTF_8.text()))); + is(Optional.of(HttpMediaTypes.PLAINTEXT_UTF_8))), + () -> assertThat(response.as(String.class), is(UTF_8_TEXT + ":" + HttpMediaTypes.PLAINTEXT_UTF_8.text()))); } } diff --git a/nima/tests/integration/observe/health/src/test/java/io/helidon/nima/tests/integration/observe/health/ObserveHealthTest.java b/nima/tests/integration/observe/health/src/test/java/io/helidon/nima/tests/integration/observe/health/ObserveHealthTest.java index d6cc23eab2f..4a27ad9791f 100644 --- a/nima/tests/integration/observe/health/src/test/java/io/helidon/nima/tests/integration/observe/health/ObserveHealthTest.java +++ b/nima/tests/integration/observe/health/src/test/java/io/helidon/nima/tests/integration/observe/health/ObserveHealthTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -17,7 +17,7 @@ package io.helidon.nima.tests.integration.observe.health; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.Headers; import io.helidon.nima.observe.ObserveFeature; import io.helidon.nima.observe.health.HealthFeature; import io.helidon.nima.observe.health.HealthObserveProvider; @@ -63,14 +63,14 @@ void testHealthAll() { .request()) { assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Http.Headers.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(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Http.Headers.CONTENT_LENGTH_ZERO)); } } @@ -80,7 +80,7 @@ void testHealthLive() { .request()) { assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Http.Headers.CONTENT_LENGTH_ZERO)); } healthCheck.status(DOWN); @@ -88,7 +88,7 @@ void testHealthLive() { .request()) { assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Http.Headers.CONTENT_LENGTH_ZERO)); } } @@ -98,7 +98,7 @@ void testHealthStart() { .request()) { assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); } healthCheck.status(DOWN); @@ -106,7 +106,7 @@ void testHealthStart() { .request()) { assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); } } @@ -116,14 +116,14 @@ void testHealthReady() { .request()) { assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Headers.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(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); } } @@ -133,14 +133,14 @@ void testHealthReadyOne() { .request()) { assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Http.Headers.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(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); } } @@ -150,14 +150,14 @@ void testHealthRootOne() { .request()) { assertThat(response.status(), is(Http.Status.NO_CONTENT_204)); - assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Headers.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(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); } } diff --git a/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseClientTest.java b/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseClientTest.java index 34b9707d1ce..5ef1165d01a 100644 --- a/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseClientTest.java +++ b/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseClientTest.java @@ -34,7 +34,7 @@ import jakarta.json.JsonObject; import org.junit.jupiter.api.Test; -import static io.helidon.common.http.Http.HeaderValues.ACCEPT_EVENT_STREAM; +import static io.helidon.common.http.Http.Headers.ACCEPT_EVENT_STREAM; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseServerMediaTest.java b/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseServerMediaTest.java index a9877e4d29c..f953b000e2b 100644 --- a/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseServerMediaTest.java +++ b/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseServerMediaTest.java @@ -44,7 +44,7 @@ import org.junit.jupiter.api.Test; -import static io.helidon.common.http.Http.HeaderValues.ACCEPT_EVENT_STREAM; +import static io.helidon.common.http.Http.Headers.ACCEPT_EVENT_STREAM; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseServerTest.java b/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseServerTest.java index 34ccf7902e1..bfa6d43d90a 100644 --- a/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseServerTest.java +++ b/nima/tests/integration/sse/server/src/test/java/io/helidon/nima/tests/integration/sse/webserver/SseServerTest.java @@ -22,10 +22,11 @@ import io.helidon.nima.webclient.http1.Http1Client; import io.helidon.nima.webclient.http1.Http1ClientResponse; import io.helidon.nima.webserver.http.HttpRules; + import org.junit.jupiter.api.Test; -import static io.helidon.common.http.Http.HeaderValues.ACCEPT_EVENT_STREAM; -import static io.helidon.common.http.Http.HeaderValues.ACCEPT_JSON; +import static io.helidon.common.http.Http.Headers.ACCEPT_EVENT_STREAM; +import static io.helidon.common.http.Http.Headers.ACCEPT_JSON; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; diff --git a/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/tests/integration/webclient/CookieTest.java b/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/tests/integration/webclient/CookieTest.java index d6c55e449f5..77b640c9646 100644 --- a/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/tests/integration/webclient/CookieTest.java +++ b/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/tests/integration/webclient/CookieTest.java @@ -88,12 +88,12 @@ void testCookiePut() { } private static void getHandler(ServerRequest req, ServerResponse res) { - if (req.headers().contains(Http.Header.COOKIE)) { - Http.HeaderValue cookies = req.headers().get(Http.Header.COOKIE); + if (req.headers().contains(Http.HeaderNames.COOKIE)) { + Http.Header cookies = req.headers().get(Http.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.Header.SET_COOKIE, "flavor1=chocolate", "flavor2=vanilla"); + res.header(Http.HeaderNames.SET_COOKIE, "flavor1=chocolate", "flavor2=vanilla"); res.status(Http.Status.OK_200).send(); } else { res.status(Http.Status.BAD_REQUEST_400).send(); @@ -104,8 +104,8 @@ private static void getHandler(ServerRequest req, ServerResponse res) { } private static void putHandler(ServerRequest req, ServerResponse res) { - if (req.headers().contains(Http.Header.COOKIE)) { - Http.HeaderValue cookies = req.headers().get(Http.Header.COOKIE); + if (req.headers().contains(Http.HeaderNames.COOKIE)) { + Http.Header cookies = req.headers().get(Http.HeaderNames.COOKIE); if (cookies.allValues().size() == 4 && cookies.allValues().contains("flavor1=chocolate") && cookies.allValues().contains("flavor2=vanilla") diff --git a/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/tests/integration/webclient/HeadersTest.java b/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/tests/integration/webclient/HeadersTest.java index 926942b7490..e86d028d86b 100644 --- a/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/tests/integration/webclient/HeadersTest.java +++ b/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/tests/integration/webclient/HeadersTest.java @@ -60,7 +60,7 @@ public void testInvalidContentType() { .path("/test/invalidContentType") .request()) { ClientResponseHeaders h = res.headers(); - Http.HeaderValue contentType = h.get(Http.Header.CONTENT_TYPE); + Http.Header contentType = h.get(Http.HeaderNames.CONTENT_TYPE); assertThat(res.status(), is(Http.Status.OK_200)); assertThat(contentType.value(), is(TestService.INVALID_CONTENT_TYPE_VALUE)); } @@ -75,7 +75,7 @@ public void testInvalidTextContentTypeStrict() { assertThat(res.status(), is(Http.Status.OK_200)); Headers h = res.headers(); // Raw protocol data value - Http.HeaderValue rawContentType = h.get(Http.Header.CONTENT_TYPE); + Http.Header rawContentType = h.get(Http.HeaderNames.CONTENT_TYPE); assertThat(rawContentType.value(), is(TestService.INVALID_CONTENT_TYPE_TEXT)); // Media type parsed value is invalid, IllegalArgumentException shall be thrown try { @@ -100,7 +100,7 @@ public void testInvalidTextContentTypeRelaxed() { assertThat(res.status(), is(Http.Status.OK_200)); Headers h = res.headers(); // Raw protocol data value - Http.HeaderValue rawContentType = h.get(Http.Header.CONTENT_TYPE); + Http.Header rawContentType = h.get(Http.HeaderNames.CONTENT_TYPE); assertThat(rawContentType.value(), is(TestService.INVALID_CONTENT_TYPE_TEXT)); // Media type parsed value Optional contentType = h.contentType(); @@ -124,7 +124,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.Header.CONTENT_TYPE, INVALID_CONTENT_TYPE_VALUE) + response.header(Http.HeaderNames.CONTENT_TYPE, INVALID_CONTENT_TYPE_VALUE) .send(); } @@ -133,7 +133,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.Header.CONTENT_TYPE, INVALID_CONTENT_TYPE_TEXT) + response.header(Http.HeaderNames.CONTENT_TYPE, INVALID_CONTENT_TYPE_TEXT) .send(); } diff --git a/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/webclient/http1/ClientRequestImplTest.java b/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/webclient/http1/ClientRequestImplTest.java index ae6d75f3ac5..fb832a5fc9f 100644 --- a/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/webclient/http1/ClientRequestImplTest.java +++ b/nima/tests/integration/webclient/webclient/src/test/java/io/helidon/nima/webclient/http1/ClientRequestImplTest.java @@ -66,11 +66,11 @@ */ @ServerTest class ClientRequestImplTest { - private static final Http.HeaderValue REQ_CHUNKED_HEADER = Http.Header.createCached( - Http.Header.create("X-Req-Chunked"), "true"); - private static final Http.HeaderValue REQ_EXPECT_100_HEADER_NAME = Http.Header.createCached( - Http.Header.create("X-Req-Expect100"), "true"); - private static final Http.HeaderName REQ_CONTENT_LENGTH_HEADER_NAME = Http.Header.create("X-Req-ContentLength"); + 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 String EXPECTED_GET_AFTER_REDIRECT_STRING = "GET after redirect endpoint reached"; private static final long NO_CONTENT_LENGTH = -1L; @@ -150,7 +150,7 @@ void testChunkAndChunkResponse() { HttpClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); validateChunkTransfer(response, true, NO_CONTENT_LENGTH, String.join("", requestEntityParts)); - assertThat(response.headers(), hasHeader(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED)); + assertThat(response.headers(), hasHeader(Http.Headers.TRANSFER_ENCODING_CHUNKED)); } @Test @@ -159,7 +159,7 @@ void testNoChunk() { long contentLength = requestEntityParts[0].length(); HttpClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test") - .header(Http.Header.CONTENT_LENGTH, String.valueOf(contentLength)); + .header(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(contentLength)); HttpClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); validateChunkTransfer(response, false, contentLength, requestEntityParts[0]); @@ -180,7 +180,7 @@ void testForcedChunkTransferEncodingChunked() { String[] requestEntityParts = {"First"}; HttpClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test") - .header(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED); + .header(Http.Headers.TRANSFER_ENCODING_CHUNKED); HttpClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); validateChunkTransfer(response, true, NO_CONTENT_LENGTH, requestEntityParts[0]); @@ -387,13 +387,13 @@ private static void validateChunkTransfer(HttpClientResponse response, boolean c private static void redirect(ServerRequest req, ServerResponse res) { res.status(Http.Status.FOUND_302) - .header(Http.Header.LOCATION, "/afterRedirect") + .header(Http.HeaderNames.LOCATION, "/afterRedirect") .send(); } private static void redirectKeepMethod(ServerRequest req, ServerResponse res) { res.status(Http.Status.TEMPORARY_REDIRECT_307) - .header(Http.Header.LOCATION, "/afterRedirect") + .header(Http.HeaderNames.LOCATION, "/afterRedirect") .send(); } @@ -432,13 +432,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.HeaderValues.EXPECT_100)) { + if (reqHeaders.contains(Http.Headers.EXPECT_100)) { res.headers().set(REQ_EXPECT_100_HEADER_NAME); } - if (reqHeaders.contains(Http.Header.CONTENT_LENGTH)) { - res.headers().set(REQ_CONTENT_LENGTH_HEADER_NAME, reqHeaders.get(Http.Header.CONTENT_LENGTH).value()); + if (reqHeaders.contains(Http.HeaderNames.CONTENT_LENGTH)) { + res.headers().set(REQ_CONTENT_LENGTH_HEADER_NAME, reqHeaders.get(Http.HeaderNames.CONTENT_LENGTH).value()); } - if (reqHeaders.contains(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED)) { + if (reqHeaders.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED)) { res.headers().set(REQ_CHUNKED_HEADER); } diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/BadRequestTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/BadRequestTest.java index 5bd3af05910..91febee3205 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/BadRequestTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/BadRequestTest.java @@ -21,7 +21,7 @@ import io.helidon.common.http.ClientResponseHeaders; import io.helidon.common.http.DirectHandler; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.ServerResponseHeaders; import io.helidon.common.testing.http.junit5.SocketHttpClient; import io.helidon.nima.testing.junit5.webserver.ServerTest; @@ -44,7 +44,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.HeaderValue LOCATION_ERROR_PAGE = Header.create(Header.LOCATION, "/errorPage"); + private static final Http.Header LOCATION_ERROR_PAGE = Http.Headers.create(Http.HeaderNames.LOCATION, "/errorPage"); private final Http1Client client; private final SocketHttpClient socketClient; @@ -153,7 +153,7 @@ private static DirectHandler.TransportResponse badRequestHandler(DirectHandler.T if (request.path().equals("/redirect")) { return DirectHandler.TransportResponse.builder() .status(Http.Status.TEMPORARY_REDIRECT_307) - .header(Header.LOCATION, "/errorPage") + .header(HeaderNames.LOCATION, "/errorPage") .build(); } return DirectHandler.TransportResponse.builder() diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ConfiguredLimitsTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ConfiguredLimitsTest.java index 4969f93bcca..6f0eb11bc08 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ConfiguredLimitsTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ConfiguredLimitsTest.java @@ -17,8 +17,8 @@ package io.helidon.nima.tests.integration.server; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.ServerRequestHeaders; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; @@ -48,7 +48,7 @@ */ @ServerTest class ConfiguredLimitsTest { - private static final HeaderName CUSTOM_HEADER = Header.create("X_HEADER"); + private static final HeaderName CUSTOM_HEADER = HeaderNames.create("X_HEADER"); private final Http1Client client; @@ -129,7 +129,7 @@ void testHeader(int size, boolean success) { String headerValue = "m".repeat(size); try (Http1ClientResponse response = client.get("any") - .header(Header.create(CUSTOM_HEADER, headerValue)) + .header(Http.Headers.create(CUSTOM_HEADER, headerValue)) .request()) { if (success) { assertThat("Header of size " + size + " should have passed", diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingContextTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingContextTest.java index 2a8cef1949f..6235ab27c61 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingContextTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingContextTest.java @@ -112,7 +112,7 @@ public ContentDecoder decoder(String encodingId) throws NoSuchElementException { @Override public ContentEncoder encoder(Headers headers) { - if (headers.contains(Http.Header.ACCEPT_ENCODING)) { + if (headers.contains(Http.HeaderNames.ACCEPT_ENCODING)) { ACCEPT_ENCODING_COUNT++; } else { NO_ACCEPT_ENCODING_COUNT++; diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingDisabledNoValidationTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingDisabledNoValidationTest.java index 06c1fdb1a1b..686cba84e15 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingDisabledNoValidationTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingDisabledNoValidationTest.java @@ -62,7 +62,7 @@ static void server(WebServerConfig.Builder server) { @Test void testContentEncodingHeader() { try (Http1ClientResponse response = client().method(Http.Method.POST) - .header(Http.Header.CONTENT_ENCODING, "data") + .header(Http.HeaderNames.CONTENT_ENCODING, "data") .submit("any")) { assertThat(response.status(), is(Http.Status.OK_200)); assertThat(response.as(String.class), is("response")); diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingDisabledTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingDisabledTest.java index 35d6ba4eba0..95274cf0664 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingDisabledTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ContentEncodingDisabledTest.java @@ -61,7 +61,7 @@ static void server(WebServerConfig.Builder server) { @Test void testContentEncodingHeader() { try (Http1ClientResponse response = client().method(Http.Method.POST) - .header(Http.Header.CONTENT_ENCODING, "data") + .header(Http.HeaderNames.CONTENT_ENCODING, "data") .submit("any")) { assertThat(response.status(), is(Http.Status.BAD_REQUEST_400)); assertThat(response.as(String.class), is("Content-Encoding header present when content encoding is disabled")); diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/Continue100ImmediatelyTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/Continue100ImmediatelyTest.java index 6a6dc0b3159..e7bf61ba598 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/Continue100ImmediatelyTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/Continue100ImmediatelyTest.java @@ -30,8 +30,8 @@ import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; import io.helidon.nima.testing.junit5.webserver.SetUpServer; -import io.helidon.nima.webserver.WebServerConfig; import io.helidon.nima.webserver.WebServer; +import io.helidon.nima.webserver.WebServerConfig; import io.helidon.nima.webserver.http.Handler; import io.helidon.nima.webserver.http.HttpRouting; import io.helidon.nima.webserver.http1.Http1Config; @@ -53,20 +53,20 @@ class Continue100ImmediatelyTest { private static final Handler ANY_HANDLER = (req, res) -> { if (Boolean.parseBoolean(req.headers() - .first(Http.Header.create("test-fail-before-read")) + .first(Http.HeaderNames.create("test-fail-before-read")) .orElse("false"))) { res.status(Http.Status.EXPECTATION_FAILED_417).send(); return; } if (Boolean.parseBoolean(req.headers() - .first(Http.Header.create("test-throw-before-read")) + .first(Http.HeaderNames.create("test-throw-before-read")) .orElse("false"))) { throw new RuntimeException("BOOM!!!"); } Optional blockId = req.headers() - .first(Http.Header.create("test-block-id")); + .first(Http.HeaderNames.create("test-block-id")); // Block request content dump if blocker assigned blockId.map(BLOCKER_MAP::get) .orElse(CompletableFuture.completedFuture("")) @@ -76,7 +76,7 @@ class Continue100ImmediatelyTest { String s = req.content().as(String.class); if (Boolean.parseBoolean(req.headers() - .first(Http.Header.create("test-throw-after-read")) + .first(Http.HeaderNames.create("test-throw-after-read")) .orElse("false"))) { throw new RuntimeException("BOOM!!!"); } @@ -105,10 +105,10 @@ static void routing(HttpRouting.Builder router) { PathMatchers.exact("/redirect"), (req, res) -> res.status(Http.Status.MOVED_PERMANENTLY_301) - .header(Http.Header.LOCATION, "/") + .header(Http.HeaderNames.LOCATION, "/") // force 301 to not use chunked encoding // https://github.com/helidon-io/helidon/issues/5713 - .header(Http.Header.CONTENT_LENGTH, "0") + .header(Http.HeaderNames.CONTENT_LENGTH, "0") .send() ) .route(Http.Method.predicate(Http.Method.PUT, Http.Method.POST), diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/Continue100Test.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/Continue100Test.java index 4ace9e21e44..805dc32645c 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/Continue100Test.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/Continue100Test.java @@ -15,16 +15,6 @@ */ package io.helidon.nima.tests.integration.server; -import io.helidon.common.http.Http; -import io.helidon.common.http.PathMatchers; -import io.helidon.common.testing.http.junit5.SocketHttpClient; -import io.helidon.nima.testing.junit5.webserver.ServerTest; -import io.helidon.nima.testing.junit5.webserver.SetUpRoute; -import io.helidon.nima.webserver.WebServer; -import io.helidon.nima.webserver.http.Handler; -import io.helidon.nima.webserver.http.HttpRouting; -import org.junit.jupiter.api.Test; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -36,6 +26,17 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import io.helidon.common.http.Http; +import io.helidon.common.http.PathMatchers; +import io.helidon.common.testing.http.junit5.SocketHttpClient; +import io.helidon.nima.testing.junit5.webserver.ServerTest; +import io.helidon.nima.testing.junit5.webserver.SetUpRoute; +import io.helidon.nima.webserver.WebServer; +import io.helidon.nima.webserver.http.Handler; +import io.helidon.nima.webserver.http.HttpRouting; + +import org.junit.jupiter.api.Test; + import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.endsWith; @@ -49,20 +50,20 @@ class Continue100Test { private static Handler anyHandler = (req, res) -> { if (Boolean.parseBoolean(req.headers() - .first(Http.Header.create("test-fail-before-read")) + .first(Http.HeaderNames.create("test-fail-before-read")) .orElse("false"))) { res.status(Http.Status.EXPECTATION_FAILED_417).send(); return; } if (Boolean.parseBoolean(req.headers() - .first(Http.Header.create("test-throw-before-read")) + .first(Http.HeaderNames.create("test-throw-before-read")) .orElse("false"))) { throw new RuntimeException("BOOM!!!"); } Optional blockId = req.headers() - .first(Http.Header.create("test-block-id")); + .first(Http.HeaderNames.create("test-block-id")); // Block request content dump if blocker assigned blockId.map(BLOCKER_MAP::get) .orElse(CompletableFuture.completedFuture("")) @@ -72,7 +73,7 @@ class Continue100Test { String s = req.content().as(String.class); if (Boolean.parseBoolean(req.headers() - .first(Http.Header.create("test-throw-after-read")) + .first(Http.HeaderNames.create("test-throw-after-read")) .orElse("false"))) { throw new RuntimeException("BOOM!!!"); } @@ -86,10 +87,10 @@ static void routing(HttpRouting.Builder router) { PathMatchers.exact("/redirect"), (req, res) -> res.status(Http.Status.MOVED_PERMANENTLY_301) - .header(Http.Header.LOCATION, "/") + .header(Http.HeaderNames.LOCATION, "/") // force 301 to not use chunked encoding // https://github.com/helidon-io/helidon/issues/5713 - .header(Http.Header.CONTENT_LENGTH, "0") + .header(Http.HeaderNames.CONTENT_LENGTH, "0") .send() ) .route(Http.Method.predicate(Http.Method.PUT, Http.Method.POST), diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ErrorHandlingTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ErrorHandlingTest.java index a31dcf9912a..5dfb6c6231d 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ErrorHandlingTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ErrorHandlingTest.java @@ -39,11 +39,11 @@ @RoutingTest class ErrorHandlingTest { - private static final Http.HeaderName CONTROL_HEADER = Http.Header.create("X-HELIDON-JUNIT"); - private static final Http.HeaderValue FIRST = Http.Header.create(CONTROL_HEADER, "first"); - private static final Http.HeaderValue SECOND = Http.Header.create(CONTROL_HEADER, "second"); - private static final Http.HeaderValue ROUTING = Http.Header.create(CONTROL_HEADER, "routing"); - private static final Http.HeaderValue CUSTOM = Http.Header.create(CONTROL_HEADER, "custom"); + 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 final Http1Client client; @@ -98,7 +98,7 @@ void testUnhandled() { .header(ROUTING) .request()) { assertThat(response.status(), is(Http.Status.INTERNAL_SERVER_ERROR_500)); - assertThat(response.headers(), hasHeader(Http.HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Http.Headers.CONTENT_LENGTH_ZERO)); } } diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ErrorHandlingWithOutputStreamTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ErrorHandlingWithOutputStreamTest.java index d03dd876837..c22a1ceb135 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ErrorHandlingWithOutputStreamTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ErrorHandlingWithOutputStreamTest.java @@ -39,8 +39,8 @@ @ServerTest class ErrorHandlingWithOutputStreamTest { - private static final Http.HeaderName MAIN_HEADER_NAME = Http.Header.create("main-handler"); - private static final Http.HeaderName ERROR_HEADER_NAME = Http.Header.create("error-handler"); + 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 final Http1Client client; diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/FormParamsSupportTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/FormParamsSupportTest.java index ac656f8c2cf..bbb6e784c2f 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/FormParamsSupportTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/FormParamsSupportTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022 Oracle and/or its affiliates. + * Copyright (c) 2019, 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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.helidon.nima.tests.integration.server; import java.util.HashMap; @@ -20,8 +21,7 @@ import java.util.Map; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.parameters.Parameters; import io.helidon.nima.testing.junit5.webserver.ServerTest; @@ -62,7 +62,7 @@ static void routing(HttpRules rules) { void urlEncodedTest() { String result = client.method(Http.Method.PUT) .path("/params") - .header(Header.CONTENT_TYPE, MediaTypes.APPLICATION_FORM_URLENCODED.text()) + .header(HeaderNames.CONTENT_TYPE, MediaTypes.APPLICATION_FORM_URLENCODED.text()) .submit("key1=val+1&key2=val2_1&key2=val2_2") .as(String.class); @@ -74,7 +74,7 @@ void urlEncodedTest() { void plainTextTest() { String result = client.method(Http.Method.PUT) .path("/params") - .header(HeaderValues.CONTENT_TYPE_TEXT_PLAIN) + .header(Http.Headers.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/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/GetTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/GetTest.java index 8849e06e260..40ad28ee4fc 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/GetTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/GetTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -22,12 +22,10 @@ import java.util.Optional; import java.util.Random; -import io.helidon.common.http.Headers; import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.Headers; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; import io.helidon.nima.webclient.http1.Http1Client; @@ -39,7 +37,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import static io.helidon.common.http.Http.Header.CONTENT_LENGTH; +import static io.helidon.common.http.Http.HeaderNames.CONTENT_LENGTH; import static io.helidon.common.http.Http.Method.GET; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; import static org.hamcrest.CoreMatchers.is; @@ -48,14 +46,14 @@ @ServerTest class GetTest { private static final byte[] BYTES = new byte[256]; - private static final HeaderName REQUEST_HEADER_NAME = Header.create("X-REquEst-HEADeR"); + private static final HeaderName REQUEST_HEADER_NAME = Http.HeaderNames.create("X-REquEst-HEADeR"); private static final String REQUEST_HEADER_VALUE_STRING = "some nice value"; - private static final HeaderValue REQUEST_HEADER_VALUE = Header.create(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); - private static final HeaderName RESPONSE_HEADER_NAME = Header.create("X-REsponSE-HeADER"); + 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 String RESPONSE_HEADER_VALUE_STRING = "another nice value"; - private static final HeaderValue RESPONSE_HEADER_VALUE = Header.create(RESPONSE_HEADER_NAME, - RESPONSE_HEADER_VALUE_STRING); - public static final HeaderValue CONTENT_LENGTH_5 = Header.create(CONTENT_LENGTH, "5"); + private static final Http.Header RESPONSE_HEADER_VALUE = Headers.create(RESPONSE_HEADER_NAME, + RESPONSE_HEADER_VALUE_STRING); + public static final Header CONTENT_LENGTH_5 = Headers.create(CONTENT_LENGTH, "5"); static { Random random = new Random(); @@ -86,9 +84,9 @@ void testStringRoute() { assertThat(response.status(), is(Http.Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); - Headers headers = response.headers(); + io.helidon.common.http.Headers headers = response.headers(); assertThat(headers, hasHeader(CONTENT_LENGTH_5)); - assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); } } @@ -100,9 +98,9 @@ void testByteRoute() { assertThat(response.status(), is(Http.Status.OK_200)); byte[] entity = response.entity().as(byte[].class); assertThat(entity, is(BYTES)); - Headers headers = response.headers(); - assertThat(headers, hasHeader(Header.create(CONTENT_LENGTH, String.valueOf(BYTES.length)))); - assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); + io.helidon.common.http.Headers headers = response.headers(); + assertThat(headers, hasHeader(Headers.create(CONTENT_LENGTH, String.valueOf(BYTES.length)))); + assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); } } @@ -115,9 +113,9 @@ void testChunkedRoute() { assertThat(response.status(), is(Http.Status.OK_200)); byte[] entity = response.entity().as(byte[].class); assertThat(entity, is(BYTES)); - Headers headers = response.headers(); - assertThat(headers, hasHeader(HeaderValues.TRANSFER_ENCODING_CHUNKED)); - assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); + io.helidon.common.http.Headers headers = response.headers(); + assertThat(headers, hasHeader(Http.Headers.TRANSFER_ENCODING_CHUNKED)); + assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); } } @@ -131,12 +129,12 @@ void testHeadersRoute() { assertThat(response.status(), is(Http.Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); - Headers headers = response.headers(); + io.helidon.common.http.Headers headers = response.headers(); 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(HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); } } @@ -148,9 +146,9 @@ void testCloseRoute() { assertThat(response.status(), is(Http.Status.OK_200)); String entity = response.entity().as(String.class); assertThat(entity, is("Hello")); - Headers headers = response.headers(); + io.helidon.common.http.Headers headers = response.headers(); assertThat(headers, hasHeader(CONTENT_LENGTH_5)); - assertThat(headers, hasHeader(HeaderValues.CONNECTION_CLOSE)); + assertThat(headers, hasHeader(Http.Headers.CONNECTION_CLOSE)); } } @@ -172,7 +170,7 @@ void testOptionalResponseEmpty() { .request()) { assertThat(response.status(), is(Http.Status.NOT_FOUND_404)); - assertThat(response.headers(), hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(response.headers(), hasHeader(Headers.CONTENT_LENGTH_ZERO)); } } @@ -188,7 +186,7 @@ public static void optional(ServerRequest req, ServerResponse res) { } private static void close(ServerRequest req, ServerResponse res) { - res.header(HeaderValues.CONNECTION_CLOSE); + res.header(Http.Headers.CONNECTION_CLOSE); res.send("Hello"); } diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/KeepAliveTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/KeepAliveTest.java index 428a62faa98..9f79318edc4 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/KeepAliveTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/KeepAliveTest.java @@ -21,7 +21,7 @@ import java.nio.charset.StandardCharsets; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.Headers; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; import io.helidon.nima.webclient.api.HttpClientResponse; @@ -75,7 +75,7 @@ static void router(HttpRouting.Builder router) { @RepeatedTest(100) void sendWithKeepAlive() { try (HttpClientResponse response = testCall(webClient, true, "/plain", OK_200)) { - assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(response.headers(), hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); } } @@ -83,7 +83,7 @@ void sendWithKeepAlive() { @RepeatedTest(100) void sendWithoutKeepAlive() { try (HttpClientResponse response = testCall(webClient, false, "/plain", OK_200)) { - assertThat(response.headers(), not(hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE))); + assertThat(response.headers(), not(hasHeader(Headers.CONNECTION_KEEP_ALIVE))); } } @@ -91,7 +91,7 @@ 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(HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(response.headers(), hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); } } @@ -104,7 +104,7 @@ private static HttpClientResponse testCall(Http1Client client, .uri(path); if (!keepAlive) { - request.header(HeaderValues.CONNECTION_CLOSE); + request.header(Http.Headers.CONNECTION_CLOSE); } Http1ClientResponse response = request diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/MaxPayloadSizeTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/MaxPayloadSizeTest.java index 6e3bef3478b..c161288cdf6 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/MaxPayloadSizeTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/MaxPayloadSizeTest.java @@ -22,7 +22,7 @@ import java.nio.charset.StandardCharsets; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.Headers; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; import io.helidon.nima.testing.junit5.webserver.SetUpServer; @@ -77,10 +77,10 @@ static void setupRoute(HttpRules rules) { void testContentLengthExceeded() { try (Http1ClientResponse response = client.method(Http.Method.POST) .path("/maxpayload") - .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) + .header(Http.Headers.CONTENT_TYPE_OCTET_STREAM) .submit(new byte[512])) { assertThat(response.status(), is(Http.Status.REQUEST_ENTITY_TOO_LARGE_413)); - assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_CLOSE)); + assertThat(response.headers(), hasHeader(Headers.CONNECTION_CLOSE)); } } @@ -91,10 +91,10 @@ void testContentLengthExceeded() { void testContentLengthExceededWithPayload() { try (Http1ClientResponse response = client.method(Http.Method.POST) .path("/maxpayload") - .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) + .header(Http.Headers.CONTENT_TYPE_OCTET_STREAM) .submit(PAYLOAD)) { assertThat(response.status(), is(Http.Status.REQUEST_ENTITY_TOO_LARGE_413)); - assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_CLOSE)); + assertThat(response.headers(), hasHeader(Headers.CONNECTION_CLOSE)); } } @@ -107,8 +107,8 @@ void testContentLengthExceededWithPayload() { void testActualLengthExceededWithPayload() { try (Http1ClientResponse response = client.method(Http.Method.POST) .path("/maxpayload") - .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) - .header(HeaderValues.TRANSFER_ENCODING_CHUNKED) + .header(Headers.CONTENT_TYPE_OCTET_STREAM) + .header(Headers.TRANSFER_ENCODING_CHUNKED) .outputStream(it -> { it.write(PAYLOAD_BYTES); it.write(PAYLOAD_BYTES); @@ -116,7 +116,7 @@ void testActualLengthExceededWithPayload() { it.close(); })) { assertThat(response.status(), is(Http.Status.REQUEST_ENTITY_TOO_LARGE_413)); - assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_CLOSE)); + assertThat(response.headers(), hasHeader(Http.Headers.CONNECTION_CLOSE)); } } @@ -127,26 +127,26 @@ void testActualLengthExceededWithPayload() { void testMixedGoodAndBadPayloads() { try (Http1ClientResponse response = client.method(Http.Method.POST) .path("/maxpayload") - .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) + .header(Http.Headers.CONTENT_TYPE_OCTET_STREAM) .submit(PAYLOAD.substring(0, 100))) { assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(response.headers(), hasHeader(Headers.CONNECTION_KEEP_ALIVE)); } try (Http1ClientResponse response = client.method(Http.Method.POST) .path("/maxpayload") - .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) + .header(Http.Headers.CONTENT_TYPE_OCTET_STREAM) .submit(PAYLOAD)) { assertThat(response.status(), is(Http.Status.REQUEST_ENTITY_TOO_LARGE_413)); - assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_CLOSE)); + assertThat(response.headers(), hasHeader(Http.Headers.CONNECTION_CLOSE)); } try (Http1ClientResponse response = client.method(Http.Method.POST) .path("/maxpayload") - .header(HeaderValues.CONTENT_TYPE_OCTET_STREAM) + .header(Http.Headers.CONTENT_TYPE_OCTET_STREAM) .submit(PAYLOAD.substring(0, (int) MAX_PAYLOAD_SIZE))) { assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers(), hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(response.headers(), hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); } } } diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/MultiPortTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/MultiPortTest.java index e914b6c4fa1..2a8a1fb590b 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/MultiPortTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/MultiPortTest.java @@ -17,7 +17,6 @@ package io.helidon.nima.tests.integration.server; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.nima.webclient.api.HttpClientResponse; import io.helidon.nima.webclient.api.WebClient; import io.helidon.nima.webserver.WebServer; @@ -150,7 +149,7 @@ void compositeRedirectServer() { listener.routing(routing -> routing .any((req, res) -> { res.status(Http.Status.MOVED_PERMANENTLY_301) - .header(Header.LOCATION, + .header(Http.HeaderNames.LOCATION, String.format("http://%s:%s%s", host(req.authority()), server.port(), @@ -167,7 +166,7 @@ void compositeRedirectServer() { .request()) { assertThat(response.status(), is(Http.Status.MOVED_PERMANENTLY_301)); assertThat(response.headers(), - hasHeader(Header.create(Header.LOCATION, "http://localhost:" + server.port() + "/foo"))); + hasHeader(Http.Headers.create(Http.HeaderNames.LOCATION, "http://localhost:" + server.port() + "/foo"))); } } diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/PostTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/PostTest.java index a6d5da1738a..6dc69e22641 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/PostTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/PostTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -22,12 +22,11 @@ import java.io.UncheckedIOException; import java.util.Random; -import io.helidon.common.http.Headers; import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.HeaderNames; +import io.helidon.common.http.Http.Headers; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; import io.helidon.nima.webclient.http1.Http1Client; @@ -40,7 +39,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import static io.helidon.common.http.Http.Header.CONTENT_LENGTH; +import static io.helidon.common.http.Http.HeaderNames.CONTENT_LENGTH; import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -49,13 +48,13 @@ @ServerTest class PostTest { private static final byte[] BYTES = new byte[256]; - private static final HeaderName REQUEST_HEADER_NAME = Header.create("X-REquEst-HEADeR"); + private static final HeaderName REQUEST_HEADER_NAME = Http.HeaderNames.create("X-REquEst-HEADeR"); private static final String REQUEST_HEADER_VALUE_STRING = "some nice value"; - private static final HeaderValue REQUEST_HEADER_VALUE = Header.create(REQUEST_HEADER_NAME, REQUEST_HEADER_VALUE_STRING); - private static final HeaderName RESPONSE_HEADER_NAME = Header.create("X-REsponSE-HeADER"); + private static final Header REQUEST_HEADER_VALUE = Headers.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 HeaderValue RESPONSE_HEADER_VALUE = Header.create(RESPONSE_HEADER_NAME, - RESPONSE_HEADER_VALUE_STRING); + private static final Http.Header RESPONSE_HEADER_VALUE = Headers.create(RESPONSE_HEADER_NAME, + RESPONSE_HEADER_VALUE_STRING); static { Random random = new Random(); @@ -79,7 +78,7 @@ static void routing(HttpRouting.Builder router) { @Test void testStringRoute() { - Headers headers; + io.helidon.common.http.Headers headers; try (Http1ClientResponse response = client.method(Http.Method.POST) .uri("/string") .submit("Hello")) { @@ -89,13 +88,13 @@ void testStringRoute() { assertThat(entity, is("Hello")); headers = response.headers(); } - assertThat(headers, hasHeader(Header.create(CONTENT_LENGTH, "5"))); - assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(Headers.create(CONTENT_LENGTH, "5"))); + assertThat(headers, hasHeader(Headers.CONNECTION_KEEP_ALIVE)); } @Test void testByteRoute() { - Headers headers; + io.helidon.common.http.Headers headers; try (Http1ClientResponse response = client.method(Http.Method.POST) .uri("/bytes") .submit(BYTES)) { @@ -105,14 +104,14 @@ void testByteRoute() { assertThat(entity, is(BYTES)); headers = response.headers(); } - assertThat(headers, hasHeader(Header.create(CONTENT_LENGTH, String.valueOf(BYTES.length)))); - assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(Headers.create(CONTENT_LENGTH, String.valueOf(BYTES.length)))); + assertThat(headers, hasHeader(Headers.CONNECTION_KEEP_ALIVE)); } @Test @Disabled("Optimization kicks in") void testChunkedRoute() { - Headers headers; + io.helidon.common.http.Headers headers; try (Http1ClientResponse response = client.method(Http.Method.POST) .uri("/chunked") .outputStream(outputStream -> { @@ -125,13 +124,13 @@ void testChunkedRoute() { assertThat(entity, is(BYTES)); headers = response.headers(); } - assertThat(headers, hasHeader(HeaderValues.TRANSFER_ENCODING_CHUNKED)); - assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(Http.Headers.TRANSFER_ENCODING_CHUNKED)); + assertThat(headers, hasHeader(Headers.CONNECTION_KEEP_ALIVE)); } @Test void testHeadersRoute() { - Headers headers; + io.helidon.common.http.Headers headers; try (Http1ClientResponse response = client.method(Http.Method.POST) .uri("/headers") .header(REQUEST_HEADER_VALUE) @@ -142,15 +141,15 @@ void testHeadersRoute() { assertThat(entity, is("Hello")); headers = response.headers(); } - assertThat(headers, hasHeader(Header.create(CONTENT_LENGTH, "5"))); - assertThat(headers, hasHeader(HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(Headers.create(CONTENT_LENGTH, "5"))); + assertThat(headers, hasHeader(Headers.CONNECTION_KEEP_ALIVE)); assertThat(headers, hasHeader(REQUEST_HEADER_VALUE)); assertThat(headers, hasHeader(RESPONSE_HEADER_VALUE)); } @Test void testCloseRoute() { - Headers headers; + io.helidon.common.http.Headers headers; try (Http1ClientResponse response = client.method(Http.Method.POST) .uri("/close") .submit("Hello")) { @@ -159,12 +158,12 @@ void testCloseRoute() { assertThrows(IllegalStateException.class, () -> response.entity().as(String.class)); headers = response.headers(); } - assertThat(headers, hasHeader(HeaderValues.CONNECTION_CLOSE)); + assertThat(headers, hasHeader(Headers.CONNECTION_CLOSE)); } private static class Routes { public static void close(ServerRequest req, ServerResponse res) { - res.header(HeaderValues.CONNECTION_CLOSE); + res.header(Headers.CONNECTION_CLOSE); res.status(Http.Status.NO_CONTENT_204); res.send(); } diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ReroutingAndNextingTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ReroutingAndNextingTest.java index cda863f156c..1e867ff5105 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ReroutingAndNextingTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/ReroutingAndNextingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -18,7 +18,6 @@ import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; import io.helidon.nima.webclient.http1.Http1Client; @@ -32,7 +31,7 @@ @ServerTest class ReroutingAndNextingTest { - private static final HeaderValue NEXTED_HEADER = Header.create(Header.create("NEXTED"), "yes"); + private static final Header NEXTED_HEADER = Http.Headers.create("NEXTED", "yes"); private final Http1Client client; diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/RoutingTestBase.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/RoutingTestBase.java index 1100da20fcc..9171334ee55 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/RoutingTestBase.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/RoutingTestBase.java @@ -21,26 +21,25 @@ import io.helidon.common.http.Http; import io.helidon.nima.webclient.http1.Http1Client; -import io.helidon.nima.webclient.http1.Http1ClientResponse; import io.helidon.nima.webclient.http1.Http1ClientRequest; +import io.helidon.nima.webclient.http1.Http1ClientResponse; import io.helidon.nima.webserver.http.ServerRequest; import io.helidon.nima.webserver.http.ServerResponse; -import static io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; - 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 io.helidon.common.testing.http.junit5.HttpHeaderMatcher.hasHeader; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.params.provider.Arguments.arguments; // Use by both RoutingTest and RulesTest to share the same test methods class RoutingTestBase { - private static final Http.HeaderValue MULTI_HANDLER = Http.Header.createCached( - Http.Header.create("X-Multi-Handler"), "true"); + private static final Http.Header MULTI_HANDLER = Http.Headers.createCached( + Http.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); diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/TransferEncodingTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/TransferEncodingTest.java index 76db09f3bd4..2a60ef41172 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/TransferEncodingTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/TransferEncodingTest.java @@ -18,8 +18,7 @@ import io.helidon.common.http.ClientResponseHeaders; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.Headers; import io.helidon.common.testing.http.junit5.SocketHttpClient; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; @@ -39,7 +38,7 @@ */ @ServerTest class TransferEncodingTest { - private static final Http.HeaderValue CONTENT_LENGTH_NINE = Header.create(Header.CONTENT_LENGTH, "9"); + private static final Http.Header CONTENT_LENGTH_NINE = Headers.create(Http.HeaderNames.CONTENT_LENGTH, "9"); private final SocketHttpClient socketHttpClient; TransferEncodingTest(SocketHttpClient socketHttpClient) { @@ -55,7 +54,7 @@ static void routing(HttpRules rules) { }) .get("/chunked", (req, res) -> { String payload = "It works!"; - res.headers().add(HeaderValues.TRANSFER_ENCODING_CHUNKED); + res.headers().add(Headers.TRANSFER_ENCODING_CHUNKED); res.send(payload); }) .get("/optimized", (req, res) -> { @@ -66,7 +65,7 @@ static void routing(HttpRules rules) { res.send(); }) .get("/emptychunked", (req, res) -> { - res.headers().add(HeaderValues.TRANSFER_ENCODING_CHUNKED); + res.headers().add(Headers.TRANSFER_ENCODING_CHUNKED); res.send(); }); } @@ -79,7 +78,7 @@ void testEmptyContentLength() { String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/empty", null); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); - assertThat(headers, hasHeader(HeaderValues.CONTENT_LENGTH_ZERO)); + assertThat(headers, hasHeader(Headers.CONTENT_LENGTH_ZERO)); } /** @@ -89,7 +88,7 @@ void testEmptyContentLength() { void testEmptyChunked() { String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/emptychunked", null); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); - assertThat(headers, hasHeader(HeaderValues.TRANSFER_ENCODING_CHUNKED)); + assertThat(headers, hasHeader(Headers.TRANSFER_ENCODING_CHUNKED)); } /** @@ -111,7 +110,7 @@ void testChunkedEncoding() { String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/chunked", null); assertThat(cutPayloadAndCheckHeadersFormat(s), is("9\nIt works!\n0\n\n")); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); - assertThat(headers, hasHeader(HeaderValues.TRANSFER_ENCODING_CHUNKED)); + assertThat(headers, hasHeader(Headers.TRANSFER_ENCODING_CHUNKED)); } /** diff --git a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/UriEncodingTest.java b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/UriEncodingTest.java index bd585bdaa39..d86b0bbc106 100644 --- a/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/UriEncodingTest.java +++ b/nima/tests/integration/webserver/webserver/src/test/java/io/helidon/nima/tests/integration/server/UriEncodingTest.java @@ -51,7 +51,7 @@ void testEncodedUrl() { String s = socketHttpClient.sendAndReceive(Http.Method.GET, "/f%6F%6F", null); assertThat(SocketHttpClient.entityFromResponse(s, true), is("It works!")); ClientResponseHeaders headers = SocketHttpClient.headersFromResponse(s); - assertThat(headers, hasHeader(Http.HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); } /** @@ -62,6 +62,6 @@ void testEncodedUrlParams() { String s = socketHttpClient.sendAndReceive(Http.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.HeaderValues.CONNECTION_KEEP_ALIVE)); + assertThat(headers, hasHeader(Http.Headers.CONNECTION_KEEP_ALIVE)); } } diff --git a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/ClientRequest.java b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/ClientRequest.java index 4518271efe3..d61770767ca 100644 --- a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/ClientRequest.java +++ b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/ClientRequest.java @@ -100,7 +100,7 @@ default T path(String uri) { * @param header header to set * @return updated request */ - T header(Http.HeaderValue header); + T header(Http.Header header); /** * Set an HTTP header. @@ -110,7 +110,7 @@ default T path(String uri) { * @return updated request */ default T header(Http.HeaderName name, String... values) { - return header(Http.Header.create(name, true, false, values)); + return header(Http.Headers.create(name, true, false, values)); } /** @@ -121,7 +121,7 @@ default T header(Http.HeaderName name, String... values) { * @return updated request */ default T header(Http.HeaderName name, List values) { - return header(Http.Header.create(name, values)); + return header(Http.Headers.create(name, values)); } /** diff --git a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/ClientRequestBase.java b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/ClientRequestBase.java index 1739e33852b..77a61a4114d 100644 --- a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/ClientRequestBase.java +++ b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/ClientRequestBase.java @@ -53,8 +53,8 @@ public abstract class ClientRequestBase, R extends Ht /** * Helidon user agent request header. */ - public static final Http.HeaderValue USER_AGENT_HEADER = Http.Header.create(Http.Header.USER_AGENT, - "Helidon " + Version.VERSION); + public static final Http.Header USER_AGENT_HEADER = Http.Headers.create(Http.HeaderNames.USER_AGENT, + "Helidon " + Version.VERSION); private static final Map COUNTERS = new ConcurrentHashMap<>(); private final Map pathParams = new HashMap<>(); @@ -152,14 +152,14 @@ public ClientRequestHeaders headers() { } @Override - public T header(Http.HeaderValue header) { + public T header(Http.Header header) { this.headers.set(header); return identity(); } @Override public T headers(Headers headers) { - for (Http.HeaderValue header : headers) { + for (Http.Header header : headers) { this.headers.add(header); } return identity(); diff --git a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/HttpClientConfigBlueprint.java b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/HttpClientConfigBlueprint.java index da9694253be..73cb39b79be 100644 --- a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/HttpClientConfigBlueprint.java +++ b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/HttpClientConfigBlueprint.java @@ -112,7 +112,7 @@ interface HttpClientConfigBlueprint extends HttpConfigBaseBlueprint { * @return default headers */ @Prototype.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/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/HttpClientConfigSupport.java b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/HttpClientConfigSupport.java index 6509853ed00..02760c75f6a 100644 --- a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/HttpClientConfigSupport.java +++ b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/HttpClientConfigSupport.java @@ -73,22 +73,77 @@ static void baseUri(HttpClientConfig.BuilderBase builder, String baseUri) */ @Prototype.BuilderMethod static void addHeader(HttpClientConfig.BuilderBase builder, Http.HeaderName name, String value) { - builder.addHeader(Http.Header.create(name, value)); + builder.addHeader(Http.Headers.create(name, value)); } + /** + * Add a default header value. + * + * @param builder builder to update + * @param name name of the header + * @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)); + } + + /** + * Add a default header value. + * + * @param builder builder to update + * @param name name of the header + * @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)); + } + + /** * 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.common.http.Http.HeaderName} - * or {@link io.helidon.common.http.Http.HeaderValue}. + * or {@link io.helidon.common.http.Http.Header}. * * @param builder builder to update * @param name name of the header * @param value value of the header - * @see #addHeader(Http.HeaderValue) + * @see #addHeader(io.helidon.common.http.Http.Header) */ @Prototype.BuilderMethod static void addHeader(HttpClientConfig.BuilderBase builder, String name, String value) { - builder.addHeader(Http.Header.create(Http.Header.create(name), value)); + builder.addHeader(Http.Headers.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.common.http.Http.HeaderName} + * or {@link io.helidon.common.http.Http.Header}. + * + * @param builder builder to update + * @param name name of the header + * @param value value of the header + * @see #addHeader(io.helidon.common.http.Http.Header) + */ + @Prototype.BuilderMethod + static void addHeader(HttpClientConfig.BuilderBase builder, String name, int value) { + builder.addHeader(Http.Headers.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.common.http.Http.HeaderName} + * or {@link io.helidon.common.http.Http.Header}. + * + * @param builder builder to update + * @param name name of the header + * @param value value of the header + * @see #addHeader(io.helidon.common.http.Http.Header) + */ + @Prototype.BuilderMethod + static void addHeader(HttpClientConfig.BuilderBase builder, String name, long value) { + builder.addHeader(Http.Headers.create(name, value)); } } @@ -115,7 +170,7 @@ public void decorate(HttpClientConfig.BuilderBase target) { } target.defaultHeadersMap() - .forEach((key, value) -> target.addHeader(Http.Header.create(Http.Header.create(key), value))); + .forEach(target::addHeader); if (!target.mediaSupports().isEmpty()) { target.mediaContext(MediaContext.builder() diff --git a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/Proxy.java b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/Proxy.java index 44b089b4952..4c225a8bf58 100644 --- a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/Proxy.java +++ b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/Proxy.java @@ -41,8 +41,7 @@ import io.helidon.common.config.Config; import io.helidon.common.configurable.LruCache; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.media.type.MediaTypes; import io.helidon.common.socket.SocketOptions; import io.helidon.config.metadata.Configured; @@ -55,8 +54,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 HeaderValue PROXY_CONNECTION = - Header.create(Http.Header.create("Proxy-Connection"), "keep-alive"); + private static final Http.Header PROXY_CONNECTION = + Http.Headers.create("Proxy-Connection", "keep-alive"); /** * No proxy instance. @@ -86,7 +85,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(); @@ -113,7 +112,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(Header.create(Header.PROXY_AUTHORIZATION, "Basic " + b64)); + this.proxyAuthHeader = Optional.of(Http.Headers.create(HeaderNames.PROXY_AUTHORIZATION, "Basic " + b64)); } else { this.proxyAuthHeader = Optional.empty(); } @@ -455,10 +454,10 @@ private static Socket connectToProxy(WebClient webClient, .connection(connection) .uri("http://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort()) .protocolId("http/1.1") // MUST be 1.1, if not available, proxy connection will fail - .header(Http.Header.HOST, targetAddress.getHostName() + ":" + targetAddress.getPort()) + .header(HeaderNames.HOST, targetAddress.getHostName() + ":" + targetAddress.getPort()) .accept(MediaTypes.WILDCARD); if (clientConfig.keepAlive()) { - request.header(Http.HeaderValues.CONNECTION_KEEP_ALIVE) + request.header(Http.Headers.CONNECTION_KEEP_ALIVE) .header(PROXY_CONNECTION); } proxy.proxyAuthHeader.ifPresent(request::header); diff --git a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/WebClientCookieManager.java b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/WebClientCookieManager.java index 45290452ed8..b05b9327deb 100644 --- a/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/WebClientCookieManager.java +++ b/nima/webclient/api/src/main/java/io/helidon/nima/webclient/api/WebClientCookieManager.java @@ -36,9 +36,9 @@ @RuntimeType.PrototypedBy(WebClientCookieManagerConfig.class) public class WebClientCookieManager extends CookieManager implements RuntimeType.Api { - private static final String COOKIE = Http.Header.COOKIE.defaultCase(); - private static final String SET_COOKIE = Http.Header.SET_COOKIE.defaultCase(); - private static final String SET_COOKIE2 = Http.Header.SET_COOKIE2.defaultCase(); + 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 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.Header.COOKIE, cookies.toArray(new String[0])); + requestHeaders.add(Http.HeaderNames.COOKIE, cookies.toArray(new String[0])); } } else if (!defaultCookies.isEmpty()) { - requestHeaders.add(Http.Header.COOKIE, defaultCookies.toArray(new String[0])); + requestHeaders.add(Http.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.Header.SET_COOKIE)) { + if (headers.contains(Http.HeaderNames.SET_COOKIE)) { cookies = new HashMap<>(); - cookies.put(SET_COOKIE, headers.values(Http.Header.SET_COOKIE)); + cookies.put(SET_COOKIE, headers.values(Http.HeaderNames.SET_COOKIE)); } - if (headers.contains(Http.Header.SET_COOKIE2)) { + if (headers.contains(Http.HeaderNames.SET_COOKIE2)) { cookies = cookies == null ? new HashMap<>() : cookies; - cookies.put(SET_COOKIE2, headers.values(Http.Header.SET_COOKIE2)); + cookies.put(SET_COOKIE2, headers.values(Http.HeaderNames.SET_COOKIE2)); } if (cookies != null) { diff --git a/nima/webclient/api/src/test/java/io/helidon/nima/webclient/api/HttpClientTest.java b/nima/webclient/api/src/test/java/io/helidon/nima/webclient/api/HttpClientTest.java index c1007e40fa8..8de8efaff12 100644 --- a/nima/webclient/api/src/test/java/io/helidon/nima/webclient/api/HttpClientTest.java +++ b/nima/webclient/api/src/test/java/io/helidon/nima/webclient/api/HttpClientTest.java @@ -135,7 +135,7 @@ public FakeHttpClientRequest maxRedirects(int maxRedirects) { } @Override - public FakeHttpClientRequest header(Http.HeaderValue header) { + public FakeHttpClientRequest header(Http.Header header) { return this; } diff --git a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallChainBase.java b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallChainBase.java index 5d1fd8e7726..f6117f10dfa 100644 --- a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallChainBase.java +++ b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallChainBase.java @@ -31,7 +31,7 @@ import io.helidon.common.http.ClientResponseHeaders; import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.Http.Method; import io.helidon.common.http.Http1HeadersParser; import io.helidon.common.http.WritableHeaders; @@ -83,7 +83,7 @@ abstract class Http1CallChainBase implements WebClientService.Chain { } static void writeHeaders(Headers headers, BufferData bufferData, boolean validate) { - for (Http.HeaderValue header : headers) { + for (Http.Header header : headers) { if (validate) { header.validate(); } @@ -106,7 +106,7 @@ public WebClientServiceResponse proceed(WebClientServiceRequest serviceRequest) writeBuffer.clear(); prologue(writeBuffer, serviceRequest, uri); - headers.setIfAbsent(Http.Header.create(Http.Header.HOST, uri.authority())); + headers.setIfAbsent(Http.Headers.create(Http.HeaderNames.HOST, uri.authority())); return doProceed(effectiveConnection, serviceRequest, headers, writer, reader, writeBuffer); } @@ -123,7 +123,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(Header.HOST).value() + + request.headers().get(Http.HeaderNames.HOST).value() + " HTTP/1.1\r\n"); } else { String schemeHostPort = clientConfig.relativeUris() ? "" : uri.scheme() + "://" + uri.host() + ":" + uri.port(); @@ -202,8 +202,8 @@ private InputStream inputStream(HelidonSocket helidonSocket, ContentDecoder decoder; - if (encodingSupport.contentDecodingEnabled() && responseHeaders.contains(Http.Header.CONTENT_ENCODING)) { - String contentEncoding = responseHeaders.get(Http.Header.CONTENT_ENCODING).value(); + if (encodingSupport.contentDecodingEnabled() && responseHeaders.contains(Http.HeaderNames.CONTENT_ENCODING)) { + String contentEncoding = responseHeaders.get(HeaderNames.CONTENT_ENCODING).value(); if (encodingSupport.contentDecodingSupported(contentEncoding)) { decoder = encodingSupport.decoder(contentEncoding); } else { @@ -214,10 +214,10 @@ private InputStream inputStream(HelidonSocket helidonSocket, } else { decoder = ContentDecoder.NO_OP; } - if (responseHeaders.contains(Http.Header.CONTENT_LENGTH)) { + 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.HeaderValues.TRANSFER_ENCODING_CHUNKED)) { + } else if (responseHeaders.contains(Http.Headers.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. @@ -226,15 +226,15 @@ private InputStream inputStream(HelidonSocket helidonSocket, } private boolean mayHaveEntity(Http.Status responseStatus, ClientResponseHeaders responseHeaders) { - if (responseHeaders.contains(Http.HeaderValues.CONTENT_LENGTH_ZERO)) { + if (responseHeaders.contains(Http.Headers.CONTENT_LENGTH_ZERO)) { return false; } if (responseStatus == Http.Status.NO_CONTENT_204) { return false; } if (( - responseHeaders.contains(Http.Header.UPGRADE) - && !responseHeaders.contains(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED))) { + responseHeaders.contains(HeaderNames.UPGRADE) + && !responseHeaders.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED))) { // this is an upgrade response and there is no entity return false; } diff --git a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallEntityChain.java b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallEntityChain.java index 8dcc25942fa..efd1b7eea12 100644 --- a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallEntityChain.java +++ b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallEntityChain.java @@ -69,7 +69,7 @@ public WebClientServiceResponse doProceed(ClientConnection connection, entityBytes = entityBytes(entity, headers); } - headers.set(Http.Header.create(Http.Header.CONTENT_LENGTH, entityBytes.length)); + headers.set(Http.Headers.create(Http.HeaderNames.CONTENT_LENGTH, entityBytes.length)); writeHeaders(headers, writeBuffer, protocolConfig().validateHeaders()); // we have completed writing the headers diff --git a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallOutputStreamChain.java b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallOutputStreamChain.java index af281bde8db..714fa6f289b 100644 --- a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallOutputStreamChain.java +++ b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1CallOutputStreamChain.java @@ -124,7 +124,7 @@ private ClientConnectionOutputStream(DataWriter writer, this.clientConfig = clientConfig; this.protocolConfig = protocolConfig; this.contentLength = headers.contentLength().orElse(-1); - this.chunked = contentLength == -1 || headers.contains(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED); + this.chunked = contentLength == -1 || headers.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED); this.request = request; this.whenSent = whenSent; } @@ -175,9 +175,9 @@ public void close() throws IOException { } writer.write(BufferData.create(TERMINATING_CHUNK)); } else { - headers.remove(Http.Header.TRANSFER_ENCODING); + headers.remove(Http.HeaderNames.TRANSFER_ENCODING); if (noData) { - headers.set(Http.HeaderValues.CONTENT_LENGTH_ZERO); + headers.set(Http.Headers.CONTENT_LENGTH_ZERO); contentLength = 0; } if (noData || firstPacket != null) { @@ -223,20 +223,20 @@ private void writeContent(BufferData buffer) throws IOException { private void sendPrologueAndHeader() { boolean expects100Continue = clientConfig.sendExpectContinue() && !noData; if (expects100Continue) { - headers.add(Http.HeaderValues.EXPECT_100); + headers.add(Http.Headers.EXPECT_100); } if (chunked) { // Add chunked encoding, if there is no other transfer-encoding headers - if (!headers.contains(Http.Header.TRANSFER_ENCODING)) { - headers.set(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED); + if (!headers.contains(Http.HeaderNames.TRANSFER_ENCODING)) { + headers.set(Http.Headers.TRANSFER_ENCODING_CHUNKED); } else { // Add chunked encoding, if it's not part of existing transfer-encoding headers - if (!headers.contains(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED)) { - headers.add(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED); + if (!headers.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED)) { + headers.add(Http.Headers.TRANSFER_ENCODING_CHUNKED); } } - headers.remove(Http.Header.CONTENT_LENGTH); + headers.remove(Http.HeaderNames.CONTENT_LENGTH); } writer.writeNow(prologue); diff --git a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ClientRequestImpl.java b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ClientRequestImpl.java index 4cf10c55af5..2af8bbc5028 100644 --- a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ClientRequestImpl.java +++ b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ClientRequestImpl.java @@ -84,10 +84,10 @@ public Http1ClientResponse doOutputStream(OutputStreamHandler streamHandler) { @Override public UpgradeResponse upgrade(String protocol) { - if (!headers().contains(Http.Header.UPGRADE)) { - headers().set(Http.Header.UPGRADE, protocol); + if (!headers().contains(Http.HeaderNames.UPGRADE)) { + headers().set(Http.HeaderNames.UPGRADE, protocol); } - Http.HeaderValue requestedUpgrade = headers().get(Http.Header.UPGRADE); + Http.Header requestedUpgrade = headers().get(Http.HeaderNames.UPGRADE); Http1ClientResponseImpl response; if (followRedirects()) { @@ -140,11 +140,11 @@ private Http1ClientResponseImpl invokeWithFollowRedirectsEntity(Object entity) { int code = clientResponse.status().code(); if (code < 300 || code >= 400) { return clientResponse; - } else if (!clientResponse.headers().contains(Http.Header.LOCATION)) { - throw new IllegalStateException("There is no " + Http.Header.LOCATION + " header present in the response! " + } else if (!clientResponse.headers().contains(Http.HeaderNames.LOCATION)) { + throw new IllegalStateException("There is no " + Http.HeaderNames.LOCATION + " header present in the response! " + "It is not clear where to redirect."); } - String redirectedUri = clientResponse.headers().get(Http.Header.LOCATION).value(); + String redirectedUri = clientResponse.headers().get(Http.HeaderNames.LOCATION).value(); URI newUri = URI.create(redirectedUri); ClientUri redirectUri = ClientUri.create(newUri); diff --git a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ClientResponseImpl.java b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ClientResponseImpl.java index 94dd864c8cc..5702f11f5df 100644 --- a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ClientResponseImpl.java +++ b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ClientResponseImpl.java @@ -28,8 +28,8 @@ import io.helidon.common.http.ClientRequestHeaders; import io.helidon.common.http.ClientResponseHeaders; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.HeaderNames; +import io.helidon.common.http.Http.Headers; import io.helidon.common.http.Http1HeadersParser; import io.helidon.common.http.WritableHeaders; import io.helidon.common.media.type.ParserMode; @@ -89,14 +89,14 @@ class Http1ClientResponseImpl implements Http1ClientResponse { this.lastEndpointUri = lastEndpointUri; this.whenComplete = whenComplete; - if (responseHeaders.contains(Header.CONTENT_LENGTH)) { - this.entityLength = Long.parseLong(responseHeaders.get(Header.CONTENT_LENGTH).value()); - } else if (responseHeaders.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED)) { + if (responseHeaders.contains(HeaderNames.CONTENT_LENGTH)) { + this.entityLength = Long.parseLong(responseHeaders.get(HeaderNames.CONTENT_LENGTH).value()); + } else if (responseHeaders.contains(Headers.TRANSFER_ENCODING_CHUNKED)) { this.entityLength = -1; } - if (responseHeaders.contains(Header.TRAILER)) { + if (responseHeaders.contains(Http.HeaderNames.TRAILER)) { this.hasTrailers = true; - this.trailerNames = responseHeaders.get(Header.TRAILER).allValues(true); + this.trailerNames = responseHeaders.get(HeaderNames.TRAILER).allValues(true); } else { this.hasTrailers = false; this.trailerNames = List.of(); @@ -122,7 +122,7 @@ public ReadableEntity entity() { public void close() { if (closed.compareAndSet(false, true)) { try { - if (headers().contains(HeaderValues.CONNECTION_CLOSE)) { + if (headers().contains(Http.Headers.CONNECTION_CLOSE)) { connection.closeResource(); } else { if (entityFullyRead || entityLength == 0) { diff --git a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ConnectionCache.java b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ConnectionCache.java index e0cc0c8d998..15c24c51f6a 100644 --- a/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ConnectionCache.java +++ b/nima/webclient/http1/src/main/java/io/helidon/nima/webclient/http1/Http1ConnectionCache.java @@ -68,17 +68,17 @@ static ClientConnection connection(WebClient webClient, } private static boolean handleKeepAlive(boolean defaultKeepAlive, WritableHeaders headers) { - if (headers.contains(Http.HeaderValues.CONNECTION_CLOSE)) { + if (headers.contains(Http.Headers.CONNECTION_CLOSE)) { return false; } if (defaultKeepAlive) { - headers.setIfAbsent(Http.HeaderValues.CONNECTION_KEEP_ALIVE); + headers.setIfAbsent(Http.Headers.CONNECTION_KEEP_ALIVE); return true; } - if (headers.contains(Http.HeaderValues.CONNECTION_KEEP_ALIVE)) { + if (headers.contains(Http.Headers.CONNECTION_KEEP_ALIVE)) { return true; } - headers.set(Http.HeaderValues.CONNECTION_CLOSE); + headers.set(Http.Headers.CONNECTION_CLOSE); return false; } diff --git a/nima/webclient/http1/src/test/java/io/helidon/nima/webclient/http1/ClientRequestImplTest.java b/nima/webclient/http1/src/test/java/io/helidon/nima/webclient/http1/ClientRequestImplTest.java index bcb30fbd1ef..c368cb99659 100644 --- a/nima/webclient/http1/src/test/java/io/helidon/nima/webclient/http1/ClientRequestImplTest.java +++ b/nima/webclient/http1/src/test/java/io/helidon/nima/webclient/http1/ClientRequestImplTest.java @@ -67,12 +67,11 @@ class ClientRequestImplTest { 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.HeaderValue REQ_CHUNKED_HEADER = Http.Header.create( - Http.Header.create("X-Req-Chunked"), "true"); - private static final Http.HeaderValue REQ_EXPECT_100_HEADER_NAME = Http.Header.create( - Http.Header.create("X-Req-Expect100"), "true"); - private static final Http.HeaderName REQ_CONTENT_LENGTH_HEADER_NAME = Http.Header.create("X-Req-ContentLength"); - private static final Http.HeaderName BAD_HEADER_NAME = Http.Header.create("Bad-Header"); + 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 long NO_CONTENT_LENGTH = -1L; private static final Http1Client client = Http1Client.builder() .sendExpectContinue(false) @@ -136,7 +135,7 @@ void testNoChunk() { long contentLength = requestEntityParts[0].length(); Http1ClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test") - .header(Http.Header.CONTENT_LENGTH, String.valueOf(contentLength)); + .header(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(contentLength)); request.connection(new FakeHttp1ClientConnection()); Http1ClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); @@ -159,7 +158,7 @@ void testForcedChunkTransferEncodingChunked() { String[] requestEntityParts = {"First"}; Http1ClientRequest request = getHttp1ClientRequest(Http.Method.PUT, "/test") - .header(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED); + .header(Http.Headers.TRANSFER_ENCODING_CHUNKED); request.connection(new FakeHttp1ClientConnection()); Http1ClientResponse response = getHttp1ClientResponseFromOutputStream(request, requestEntityParts); @@ -241,7 +240,7 @@ void testRelativeUris(boolean relativeUris, boolean outputStream, String request @MethodSource("headerValues") void testHeaderValues(List headerValues, boolean expectsValid) { Http1ClientRequest request = client.get("http://localhost:" + dummyPort + "/test"); - request.header(Http.Header.create(Http.Header.create("HeaderName"), headerValues)); + request.header(Http.Headers.create("HeaderName", headerValues)); request.connection(new FakeHttp1ClientConnection()); if (expectsValid) { HttpClientResponse response = request.request(); @@ -253,7 +252,7 @@ void testHeaderValues(List headerValues, boolean expectsValid) { @ParameterizedTest @MethodSource("headers") - void testHeaders(Http.HeaderValue header, boolean expectsValid) { + void testHeaders(Http.Header header, boolean expectsValid) { Http1ClientRequest request = client.get("http://localhost:" + dummyPort + "/test"); request.connection(new FakeHttp1ClientConnection()); request.header(header); @@ -267,7 +266,7 @@ void testHeaders(Http.HeaderValue header, boolean expectsValid) { @ParameterizedTest @MethodSource("headers") - void testDisableHeaderValidation(Http.HeaderValue header, boolean expectsValid) { + void testDisableHeaderValidation(Http.Header header, boolean expectsValid) { Http1Client clientWithNoHeaderValidation = Http1Client.builder() .protocolConfig(it -> it.validateHeaders(false)) .build(); @@ -291,7 +290,7 @@ void testHeadersFromResponse(String headerName, String headerValue, boolean expe if (expectsValid) { HttpClientResponse response = request.submit(headerNameAndValue); assertThat(response.status(), is(Http.Status.OK_200)); - String responseHeaderValue = response.headers().get(Http.Header.create(headerName)).values(); + String responseHeaderValue = response.headers().get(Http.HeaderNames.create(headerName)).values(); assertThat(responseHeaderValue, is(headerValue.trim())); } else { assertThrows(IllegalArgumentException.class, () -> request.submit(headerNameAndValue)); @@ -308,7 +307,7 @@ void testDisableValidationForHeadersFromResponse(String headerName, String heade 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.Header.create(headerName)).values(); + String responseHeaderValue = response.headers().get(Http.HeaderNames.create(headerName)).values(); assertThat(responseHeaderValue, is(headerValue.trim())); } @@ -405,31 +404,31 @@ private static Stream headerValues() { private static Stream headers() { return Stream.of( // Valid headers - arguments(Http.HeaderValues.ACCEPT_RANGES_BYTES, true), - arguments(Http.HeaderValues.CONNECTION_KEEP_ALIVE, true), - arguments(Http.HeaderValues.CONTENT_TYPE_TEXT_PLAIN, true), - arguments(Http.HeaderValues.ACCEPT_TEXT, true), - arguments(Http.HeaderValues.CACHE_NO_CACHE, true), - arguments(Http.HeaderValues.TE_TRAILERS, true), - arguments(Http.Header.create(Http.Header.create("!#$Custom~%&\'*Header+^`|"), "!Header\tValue~"), true), - arguments(Http.Header.create(Http.Header.create("Custom_0-9_a-z_A-Z_Header"), - "\u0080Header Value\u00ff"), true), + 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", + "\u0080Header Value\u00ff"), true), // Invalid headers - arguments(Http.Header.create(Http.Header.create(VALID_HEADER_NAME), "H\u001ceaderValue1"), false), - arguments(Http.Header.create(Http.Header.create(VALID_HEADER_NAME), - "HeaderValue1, Header\u007fValue"), false), - arguments(Http.Header.create(Http.Header.create(VALID_HEADER_NAME), - "HeaderValue1\u001f, HeaderValue2"), false), - arguments(Http.Header.create(Http.Header.create("Header\u001aName"), VALID_HEADER_VALUE), false), - arguments(Http.Header.create(Http.Header.create("Header\u000EName"), VALID_HEADER_VALUE), false), - arguments(Http.Header.create(Http.Header.create("HeaderName\r\n"), VALID_HEADER_VALUE), false), - arguments(Http.Header.create(Http.Header.create("HeaderName\u00FF\u0124"), VALID_HEADER_VALUE), false), - arguments(Http.Header.create(Http.Header.create("(Header:Name)"), VALID_HEADER_VALUE), false), - arguments(Http.Header.create(Http.Header.create(""), VALID_HEADER_VALUE), false), - arguments(Http.Header.create(Http.Header.create("{Header=Name}"), VALID_HEADER_VALUE), false), - arguments(Http.Header.create(Http.Header.create("\"HeaderName\""), VALID_HEADER_VALUE), false), - arguments(Http.Header.create(Http.Header.create("[\\HeaderName]"), VALID_HEADER_VALUE), false), - arguments(Http.Header.create(Http.Header.create("@Header,Name;"), VALID_HEADER_VALUE), false) + arguments(Http.Headers.create(VALID_HEADER_NAME, "H\u001ceaderValue1"), false), + arguments(Http.Headers.create(VALID_HEADER_NAME, + "HeaderValue1, Header\u007fValue"), false), + arguments(Http.Headers.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) ); } @@ -625,8 +624,8 @@ private void webServerHandle() { WritableHeaders reqHeaders = null; try { reqHeaders = Http1HeadersParser.readHeaders(serverReader, 16384, false); - for (Iterator it = reqHeaders.iterator(); it.hasNext(); ) { - Http.HeaderValue header = it.next(); + for (Iterator it = reqHeaders.iterator(); it.hasNext(); ) { + Http.Header header = it.next(); header.validate(); } } catch (IllegalArgumentException e) { @@ -635,9 +634,9 @@ private void webServerHandle() { int entitySize = 0; if (!requestFailed) { - if (reqHeaders.contains(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED)) { + if (reqHeaders.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED)) { // Send 100-Continue if requested - if (reqHeaders.contains(Http.HeaderValues.EXPECT_100)) { + if (reqHeaders.contains(Http.Headers.EXPECT_100)) { serverWriter.write( BufferData.create("HTTP/1.1 100 Continue\r\n".getBytes(StandardCharsets.UTF_8))); } @@ -655,8 +654,8 @@ private void webServerHandle() { serverReader.skip(2); entitySize += chunkLength; } - } else if (reqHeaders.contains(Http.Header.CONTENT_LENGTH)) { - entitySize = reqHeaders.get(Http.Header.CONTENT_LENGTH).value(int.class); + } else if (reqHeaders.contains(Http.HeaderNames.CONTENT_LENGTH)) { + entitySize = reqHeaders.get(Http.HeaderNames.CONTENT_LENGTH).value(int.class); if (entitySize > 0) { entity.write(serverReader.getBuffer(entitySize)); } @@ -664,17 +663,17 @@ private void webServerHandle() { } WritableHeaders resHeaders = WritableHeaders.create(); - resHeaders.add(Http.HeaderValues.CONNECTION_KEEP_ALIVE); + resHeaders.add(Http.Headers.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.HeaderValues.EXPECT_100)) { + if (reqHeaders.contains(Http.Headers.EXPECT_100)) { resHeaders.set(REQ_EXPECT_100_HEADER_NAME); } - if (reqHeaders.contains(Http.Header.CONTENT_LENGTH)) { - resHeaders.set(REQ_CONTENT_LENGTH_HEADER_NAME, reqHeaders.get(Http.Header.CONTENT_LENGTH).value()); + if (reqHeaders.contains(Http.HeaderNames.CONTENT_LENGTH)) { + resHeaders.set(REQ_CONTENT_LENGTH_HEADER_NAME, reqHeaders.get(Http.HeaderNames.CONTENT_LENGTH).value()); } - if (reqHeaders.contains(Http.HeaderValues.TRANSFER_ENCODING_CHUNKED)) { + if (reqHeaders.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED)) { resHeaders.set(REQ_CHUNKED_HEADER); } } @@ -682,16 +681,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.Header.create(Http.Header.create(header[0]), header[1])); + resHeaders.add(Http.Headers.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.Header.CONTENT_LENGTH, Integer.toString(entitySize)); + resHeaders.add(Http.HeaderNames.CONTENT_LENGTH, Integer.toString(entitySize)); BufferData entityBuffer = BufferData.growing(128); - for (Http.HeaderValue header : resHeaders) { + for (Http.Header header : resHeaders) { header.writeHttp1Header(entityBuffer); } entityBuffer.write(Bytes.CR_BYTE); diff --git a/nima/webclient/security/src/main/java/io/helidon/nima/webclient/security/WebClientSecurity.java b/nima/webclient/security/src/main/java/io/helidon/nima/webclient/security/WebClientSecurity.java index 2f3adf92667..d8e63c25dbf 100644 --- a/nima/webclient/security/src/main/java/io/helidon/nima/webclient/security/WebClientSecurity.java +++ b/nima/webclient/security/src/main/java/io/helidon/nima/webclient/security/WebClientSecurity.java @@ -185,7 +185,7 @@ private WebClientServiceResponse processResponse(WebClientServiceRequest request } //replace existing - Http.HeaderName headerName = Http.Header.create(entry.getKey()); + Http.HeaderName headerName = Http.HeaderNames.create(entry.getKey()); clientHeaders.set(headerName, entry.getValue().toArray(new String[0])); } span.end(); diff --git a/nima/webclient/tracing/src/main/java/io/helidon/nima/webclient/tracing/WebClientTracing.java b/nima/webclient/tracing/src/main/java/io/helidon/nima/webclient/tracing/WebClientTracing.java index 4082e84e18f..00149d7b65e 100644 --- a/nima/webclient/tracing/src/main/java/io/helidon/nima/webclient/tracing/WebClientTracing.java +++ b/nima/webclient/tracing/src/main/java/io/helidon/nima/webclient/tracing/WebClientTracing.java @@ -127,34 +127,37 @@ private ClientHeaderConsumer(ClientRequestHeaders headers) { @Override public void setIfAbsent(String key, String... values) { - headers.setIfAbsent(Http.Header.create(Http.Header.create(key), values)); + Http.HeaderName name = Http.HeaderNames.create(key); + if (!headers.contains(name)) { + headers.set(name, values); + } } @Override public void set(String key, String... values) { - headers.set(Http.Header.create(Http.Header.create(key), values)); + headers.set(Http.Headers.create(key, values)); } @Override public Iterable keys() { return headers.stream() - .map(Http.HeaderValue::name) + .map(Http.Header::name) .toList(); } @Override public Optional get(String key) { - return headers.first(Http.Header.create(key)); + return headers.first(Http.HeaderNames.create(key)); } @Override public Iterable getAll(String key) { - return headers.all(Http.Header.create(key), List::of); + return headers.all(Http.HeaderNames.create(key), List::of); } @Override public boolean contains(String key) { - return headers.contains(Http.Header.create(key)); + return headers.contains(Http.HeaderNames.create(key)); } } } diff --git a/nima/webserver/access-log/src/main/java/io/helidon/nima/webserver/accesslog/HeaderLogEntry.java b/nima/webserver/access-log/src/main/java/io/helidon/nima/webserver/accesslog/HeaderLogEntry.java index 67e18cc2daf..e0486c14dee 100644 --- a/nima/webserver/access-log/src/main/java/io/helidon/nima/webserver/accesslog/HeaderLogEntry.java +++ b/nima/webserver/access-log/src/main/java/io/helidon/nima/webserver/accesslog/HeaderLogEntry.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022 Oracle and/or its affiliates. + * Copyright (c) 2019, 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. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package io.helidon.nima.webserver.accesslog; import java.util.List; @@ -81,7 +82,7 @@ public static final class Builder extends AbstractLogEntry.Builder= fileLength || last < offset) { - res.header(Header.CONTENT_RANGE, "*/" + fileLength); + res.header(HeaderNames.CONTENT_RANGE, "*/" + fileLength); throw new HttpException("Wrong range", Http.Status.REQUESTED_RANGE_NOT_SATISFIABLE_416, true); } diff --git a/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/CachedHandlerInMemory.java b/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/CachedHandlerInMemory.java index d61415dc912..bf860a1105c 100644 --- a/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/CachedHandlerInMemory.java +++ b/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/CachedHandlerInMemory.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -38,7 +38,7 @@ record CachedHandlerInMemory(MediaType mediaType, BiConsumer setLastModifiedHeader, byte[] bytes, int contentLength, - Http.HeaderValue contentLengthHeader) implements CachedHandler { + Http.Header contentLengthHeader) implements CachedHandler { @Override public boolean handle(LruCache cache, @@ -67,11 +67,11 @@ public boolean handle(LruCache cache, private void send(ServerRequest request, ServerResponse response) { ServerRequestHeaders headers = request.headers(); - if (headers.contains(Http.Header.RANGE)) { + if (headers.contains(Http.HeaderNames.RANGE)) { long contentLength = contentLength(); List ranges = ByteRangeRequest.parse(request, response, - headers.get(Http.Header.RANGE).values(), + headers.get(Http.HeaderNames.RANGE).values(), contentLength); if (ranges.size() == 1) { // single response diff --git a/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/CachedHandlerRedirect.java b/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/CachedHandlerRedirect.java index 3a25d43415a..41eed3d8137 100644 --- a/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/CachedHandlerRedirect.java +++ b/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/CachedHandlerRedirect.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -41,7 +41,7 @@ public boolean handle(LruCache cache, } response.status(Http.Status.MOVED_PERMANENTLY_301); - response.headers().set(Http.Header.LOCATION, locationWithQuery); + response.headers().set(Http.HeaderNames.LOCATION, locationWithQuery); response.send(); return true; } diff --git a/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/ClassPathContentHandler.java b/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/ClassPathContentHandler.java index 86f519ac953..ff4431b6238 100644 --- a/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/ClassPathContentHandler.java +++ b/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/ClassPathContentHandler.java @@ -243,10 +243,10 @@ private Optional jarHandler(String requestedResource, URL url) { null)); } else { // we can cache this, as this is a jar record - Http.HeaderValue lastModifiedHeader = Http.Header.create(Http.Header.LAST_MODIFIED, - true, - false, - formatLastModified(lastModified)); + Http.Header lastModifiedHeader = Http.Headers.create(Http.HeaderNames.LAST_MODIFIED, + true, + false, + formatLastModified(lastModified)); return Optional.of(new CachedHandlerJar(extrEntry.tempFile, detectType(extrEntry.entryName), extrEntry.lastModified(), diff --git a/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/FileBasedContentHandler.java b/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/FileBasedContentHandler.java index 8043598fcd2..f7ecba07716 100644 --- a/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/FileBasedContentHandler.java +++ b/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/FileBasedContentHandler.java @@ -32,7 +32,8 @@ import java.util.Objects; import java.util.Optional; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.ServerRequestHeaders; import io.helidon.common.http.ServerResponseHeaders; import io.helidon.common.media.type.MediaType; @@ -60,7 +61,7 @@ static String fileName(Path path) { } static void processContentLength(Path path, ServerResponseHeaders headers) { - headers.set(Header.create(Header.CONTENT_LENGTH, contentLength(path))); + headers.set(Http.Headers.create(HeaderNames.CONTENT_LENGTH, contentLength(path))); } static long contentLength(Path path) { @@ -73,11 +74,11 @@ static long contentLength(Path path) { static void send(ServerRequest request, ServerResponse response, Path path) throws IOException { ServerRequestHeaders headers = request.headers(); - if (headers.contains(Header.RANGE)) { + if (headers.contains(HeaderNames.RANGE)) { long contentLength = contentLength(path); List ranges = ByteRangeRequest.parse(request, response, - headers.get(Header.RANGE).values(), + headers.get(Http.HeaderNames.RANGE).values(), contentLength); if (ranges.size() == 1) { // single response diff --git a/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/StaticContentHandler.java b/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/StaticContentHandler.java index daa419fabf7..ecbd9414404 100644 --- a/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/StaticContentHandler.java +++ b/nima/webserver/static-content/src/main/java/io/helidon/nima/webserver/staticcontent/StaticContentHandler.java @@ -33,7 +33,7 @@ import io.helidon.common.configurable.LruCache; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.HttpException; import io.helidon.common.http.InternalServerException; import io.helidon.common.http.NotFoundException; @@ -78,10 +78,10 @@ static void processEtag(String etag, ServerRequestHeaders requestHeaders, Server } etag = unquoteETag(etag); // Put ETag into the response - responseHeaders.set(Header.ETAG, '"' + etag + '"'); + responseHeaders.set(HeaderNames.ETAG, '"' + etag + '"'); // Process If-None-Match header - if (requestHeaders.contains(Header.IF_NONE_MATCH)) { - List ifNoneMatches = requestHeaders.get(Header.IF_NONE_MATCH).allValues(); + if (requestHeaders.contains(Http.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)) { @@ -91,9 +91,9 @@ static void processEtag(String etag, ServerRequestHeaders requestHeaders, Server } } - if (requestHeaders.contains(Header.IF_MATCH)) { + if (requestHeaders.contains(Http.HeaderNames.IF_MATCH)) { // Process If-Match header - List ifMatches = requestHeaders.get(Header.IF_MATCH).allValues(); + List ifMatches = requestHeaders.get(HeaderNames.IF_MATCH).allValues(); if (!ifMatches.isEmpty()) { boolean ifMatchChecked = false; for (String ifMatch : ifMatches) { @@ -312,7 +312,7 @@ private static String unquoteETag(String etag) { void cacheInMemory(String resource, MediaType contentType, byte[] bytes, Optional lastModified) { int contentLength = bytes.length; - Http.HeaderValue contentLengthHeader = Http.Header.create(Http.Header.CONTENT_LENGTH, contentLength); + Http.Header contentLengthHeader = Http.Headers.create(HeaderNames.CONTENT_LENGTH, contentLength); CachedHandlerInMemory inMemoryResource; if (lastModified.isEmpty()) { @@ -324,10 +324,10 @@ void cacheInMemory(String resource, MediaType contentType, byte[] bytes, Optiona contentLengthHeader); } else { // we can cache this, as this is a jar record - Http.HeaderValue lastModifiedHeader = Http.Header.create(Http.Header.LAST_MODIFIED, - true, - false, - formatLastModified(lastModified.get())); + Http.Header lastModifiedHeader = Http.Headers.create(HeaderNames.LAST_MODIFIED, + true, + false, + formatLastModified(lastModified.get())); inMemoryResource = new CachedHandlerInMemory(contentType, lastModified.get(), diff --git a/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/ByteRangeRequestTest.java b/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/ByteRangeRequestTest.java index 0771836e53c..011ac337b28 100644 --- a/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/ByteRangeRequestTest.java +++ b/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/ByteRangeRequestTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Oracle and/or its affiliates. + * Copyright (c) 2022, 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. @@ -18,8 +18,9 @@ import java.util.List; +import io.helidon.common.http.Http; import io.helidon.common.http.Http.Header; -import io.helidon.common.http.Http.HeaderValue; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.nima.webserver.http.ServerRequest; import io.helidon.nima.webserver.http.ServerResponse; @@ -33,7 +34,7 @@ class ByteRangeRequestTest { @Test void testFromUntilEnd() { - HeaderValue header = Header.create(Header.RANGE, "bytes=49-"); + Http.Header header = Http.Headers.create(HeaderNames.RANGE, "bytes=49-"); ServerRequest req = Mockito.mock(ServerRequest.class); ServerResponse res = Mockito.mock(ServerResponse.class); @@ -48,7 +49,7 @@ void testFromUntilEnd() { @Test void testFromUntil() { - HeaderValue header = Header.create(Header.RANGE, "bytes=49-49"); + Http.Header header = Http.Headers.create(Http.HeaderNames.RANGE, "bytes=49-49"); ServerRequest req = Mockito.mock(ServerRequest.class); ServerResponse res = Mockito.mock(ServerResponse.class); @@ -63,7 +64,7 @@ void testFromUntil() { @Test void testLast() { - HeaderValue header = Header.create(Header.RANGE, "bytes=-1"); + Header header = Http.Headers.create(Http.HeaderNames.RANGE, "bytes=-1"); ServerRequest req = Mockito.mock(ServerRequest.class); ServerResponse res = Mockito.mock(ServerResponse.class); @@ -78,7 +79,7 @@ void testLast() { @Test void testMultiRangeMultiValue() { - HeaderValue header = Header.create(Header.RANGE, "bytes=-1", "bytes=47-48", "bytes=0-"); + Header header = Http.Headers.create(Http.HeaderNames.RANGE, "bytes=-1", "bytes=47-48", "bytes=0-"); ServerRequest req = Mockito.mock(ServerRequest.class); ServerResponse res = Mockito.mock(ServerResponse.class); @@ -103,7 +104,7 @@ void testMultiRangeMultiValue() { @Test void testMultiRangeSingleValue() { - HeaderValue header = Header.create(Header.RANGE, "bytes=-1, bytes=47-48, s bytes=0-"); + Http.Header header = Http.Headers.create(Http.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/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/CachedHandlerTest.java b/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/CachedHandlerTest.java index 92a703daa39..429930879e0 100644 --- a/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/CachedHandlerTest.java +++ b/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/CachedHandlerTest.java @@ -48,8 +48,8 @@ class CachedHandlerTest { private static final MediaType MEDIA_TYPE_ICON = MediaTypes.create("image/x-icon"); - private static final Http.HeaderValue ICON_TYPE = Http.Header.create(Http.Header.CONTENT_TYPE, MEDIA_TYPE_ICON.text()); - private static final Http.HeaderValue RESOURCE_CONTENT_LENGTH = Http.Header.create(Http.Header.CONTENT_LENGTH, 7); + 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 ClassPathContentHandler classpathHandler; private static FileSystemContentHandler fsHandler; @@ -101,8 +101,8 @@ void testClasspathFromInMemory() throws IOException, URISyntaxException { assertThat("Handler should have found favicon.ico", result, is(true)); assertThat(responseHeaders, hasHeader(ICON_TYPE)); - assertThat(responseHeaders, hasHeader(Http.Header.ETAG)); - assertThat(responseHeaders, hasHeader(Http.Header.LAST_MODIFIED)); + assertThat(responseHeaders, hasHeader(Http.HeaderNames.ETAG)); + assertThat(responseHeaders, hasHeader(Http.HeaderNames.LAST_MODIFIED)); } @Test @@ -120,10 +120,10 @@ void testClasspathCacheFound() throws IOException, URISyntaxException { boolean result = classpathHandler.doHandle(Http.Method.GET, "resource.txt", req, res, false); assertThat("Handler should have found resource.txt", result, is(true)); - assertThat(responseHeaders, hasHeader(Http.HeaderValues.CONTENT_TYPE_TEXT_PLAIN)); + assertThat(responseHeaders, hasHeader(Http.Headers.CONTENT_TYPE_TEXT_PLAIN)); assertThat(responseHeaders, hasHeader(RESOURCE_CONTENT_LENGTH)); - assertThat(responseHeaders, hasHeader(Http.Header.ETAG)); - assertThat(responseHeaders, hasHeader(Http.Header.LAST_MODIFIED)); + assertThat(responseHeaders, hasHeader(Http.HeaderNames.ETAG)); + assertThat(responseHeaders, hasHeader(Http.HeaderNames.LAST_MODIFIED)); // now make sure it is cached Optional cachedHandler = classpathHandler.cacheHandler("web/resource.txt"); @@ -153,7 +153,7 @@ void testClasspathCacheRedirectFound() throws IOException, URISyntaxException { boolean result = classpathHandler.doHandle(Http.Method.GET, "/nested", req, res, false); assertThat("Handler should have redirected", result, is(true)); - assertThat(responseHeaders, hasHeader(Http.Header.LOCATION, "/nested/")); + assertThat(responseHeaders, hasHeader(Http.HeaderNames.LOCATION, "/nested/")); // now make sure it is cached Optional cachedHandler = classpathHandler.cacheHandler("web/nested"); @@ -196,9 +196,9 @@ void testFsFromInMemory() throws IOException { boolean result = fsHandler.doHandle(Http.Method.GET, "nested/resource.txt", req, res, false); assertThat("Handler should have found nested/resource.txt", result, is(true)); - assertThat(responseHeaders, hasHeader(Http.HeaderValues.CONTENT_TYPE_TEXT_PLAIN)); - assertThat(responseHeaders, hasHeader(Http.Header.ETAG)); - assertThat(responseHeaders, hasHeader(Http.Header.LAST_MODIFIED)); + assertThat(responseHeaders, hasHeader(Http.Headers.CONTENT_TYPE_TEXT_PLAIN)); + assertThat(responseHeaders, hasHeader(Http.HeaderNames.ETAG)); + assertThat(responseHeaders, hasHeader(Http.HeaderNames.LAST_MODIFIED)); } @Test @@ -216,10 +216,10 @@ void testFsCacheFound() throws IOException { boolean result = fsHandler.doHandle(Http.Method.GET, "resource.txt", req, res, false); assertThat("Handler should have found resource.txt", result, is(true)); - assertThat(responseHeaders, hasHeader(Http.HeaderValues.CONTENT_TYPE_TEXT_PLAIN)); + assertThat(responseHeaders, hasHeader(Http.Headers.CONTENT_TYPE_TEXT_PLAIN)); assertThat(responseHeaders, hasHeader(RESOURCE_CONTENT_LENGTH)); - assertThat(responseHeaders, hasHeader(Http.Header.ETAG)); - assertThat(responseHeaders, hasHeader(Http.Header.LAST_MODIFIED)); + assertThat(responseHeaders, hasHeader(Http.HeaderNames.ETAG)); + assertThat(responseHeaders, hasHeader(Http.HeaderNames.LAST_MODIFIED)); // now make sure it is cached Optional cachedHandler = fsHandler.cacheHandler("resource.txt"); @@ -249,7 +249,7 @@ void testFsCacheRedirectFound() throws IOException { boolean result = fsHandler.doHandle(Http.Method.GET, "nested", req, res, false); assertThat("Handler should have redirected", result, is(true)); - assertThat(responseHeaders, hasHeader(Http.Header.LOCATION, "/nested/")); + assertThat(responseHeaders, hasHeader(Http.HeaderNames.LOCATION, "/nested/")); // now make sure it is cached Optional cachedHandler = fsHandler.cacheHandler("nested"); diff --git a/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/StaticContentHandlerTest.java b/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/StaticContentHandlerTest.java index 191464d8910..a07e510f2fd 100644 --- a/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/StaticContentHandlerTest.java +++ b/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/StaticContentHandlerTest.java @@ -26,7 +26,6 @@ import io.helidon.common.configurable.LruCache; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.common.http.HttpException; import io.helidon.common.http.HttpPrologue; import io.helidon.common.http.RoutedPath; @@ -42,10 +41,10 @@ import org.junit.jupiter.api.Test; import org.mockito.Mockito; -import static io.helidon.common.http.Http.Header.ETAG; -import static io.helidon.common.http.Http.Header.IF_MATCH; -import static io.helidon.common.http.Http.Header.IF_NONE_MATCH; -import static io.helidon.common.http.Http.Header.LOCATION; +import static io.helidon.common.http.Http.HeaderNames.ETAG; +import static io.helidon.common.http.Http.HeaderNames.IF_MATCH; +import static io.helidon.common.http.Http.HeaderNames.IF_NONE_MATCH; +import static io.helidon.common.http.Http.HeaderNames.LOCATION; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; @@ -64,7 +63,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(Header.create(IF_NONE_MATCH, "\"ccc\"", "\"ddd\"")); + when(req.get(IF_NONE_MATCH)).thenReturn(Http.Headers.create(IF_NONE_MATCH, "\"ccc\"", "\"ddd\"")); ServerResponseHeaders res = mock(ServerResponseHeaders.class); StaticContentHandler.processEtag("aaa", req, res); verify(res).set(ETAG, ETAG_VALUE); @@ -75,7 +74,7 @@ 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(Header.create(IF_NONE_MATCH, "\"ccc\"", "W/\"aaa\"")); + when(req.get(IF_NONE_MATCH)).thenReturn(Http.Headers.create(IF_NONE_MATCH, "\"ccc\"", "W/\"aaa\"")); ServerResponseHeaders res = mock(ServerResponseHeaders.class); assertHttpException(() -> StaticContentHandler.processEtag("aaa", req, res), Http.Status.NOT_MODIFIED_304); verify(res).set(ETAG, ETAG_VALUE); @@ -86,7 +85,7 @@ 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(Header.create(IF_MATCH, "\"ccc\"", "\"ddd\"")); + when(req.get(IF_MATCH)).thenReturn(Http.Headers.create(IF_MATCH, "\"ccc\"", "\"ddd\"")); ServerResponseHeaders res = mock(ServerResponseHeaders.class); assertHttpException(() -> StaticContentHandler.processEtag("aaa", req, res), Http.Status.PRECONDITION_FAILED_412); verify(res).set(ETAG, ETAG_VALUE); @@ -97,7 +96,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(Header.create(IF_MATCH, "\"ccc\"", "\"aaa\"")); + when(req.get(IF_MATCH)).thenReturn(Http.Headers.create(IF_MATCH, "\"ccc\"", "\"aaa\"")); ServerResponseHeaders res = mock(ServerResponseHeaders.class); StaticContentHandler.processEtag("aaa", req, res); verify(res).set(ETAG, ETAG_VALUE); diff --git a/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/StaticContentTest.java b/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/StaticContentTest.java index 4accd60276f..c98e7238fce 100644 --- a/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/StaticContentTest.java +++ b/nima/webserver/static-content/src/test/java/io/helidon/nima/webserver/staticcontent/StaticContentTest.java @@ -20,7 +20,7 @@ import java.nio.file.Path; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.testing.http.junit5.HttpHeaderMatcher; import io.helidon.nima.testing.junit5.webserver.DirectClient; import io.helidon.nima.testing.junit5.webserver.RoutingTest; @@ -69,7 +69,7 @@ void testClasspathFavicon() { .request()) { assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers(), HttpHeaderMatcher.hasHeader(Header.CONTENT_TYPE, "image/x-icon")); + assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "image/x-icon")); } } @@ -79,7 +79,7 @@ void testClasspathNested() { .request()) { assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers(), HttpHeaderMatcher.hasHeader(Header.CONTENT_TYPE, "text/plain")); + assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "text/plain")); assertThat(response.as(String.class), is("Nested content")); } } @@ -90,7 +90,7 @@ void testClasspathSingleFile() { .request()) { assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers(), HttpHeaderMatcher.hasHeader(Header.CONTENT_TYPE, "text/plain")); + assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "text/plain")); assertThat(response.as(String.class), is("Content")); } } @@ -101,7 +101,7 @@ void testFileSystemFavicon() { .request()) { assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers(), HttpHeaderMatcher.hasHeader(Header.CONTENT_TYPE, "image/x-icon")); + assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "image/x-icon")); } } @@ -111,7 +111,7 @@ void testFileSystemNested() { .request()) { assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers(), HttpHeaderMatcher.hasHeader(Header.CONTENT_TYPE, "text/plain")); + assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "text/plain")); assertThat(response.as(String.class), is("Nested content")); } } @@ -122,7 +122,7 @@ void testFileSystemSingleFile() { .request()) { assertThat(response.status(), is(Http.Status.OK_200)); - assertThat(response.headers(), HttpHeaderMatcher.hasHeader(Header.CONTENT_TYPE, "text/plain")); + assertThat(response.headers(), HttpHeaderMatcher.hasHeader(HeaderNames.CONTENT_TYPE, "text/plain")); assertThat(response.as(String.class), is("Content")); } } diff --git a/nima/webserver/tracing/src/main/java/io/helidon/nima/webserver/tracing/TracingFeature.java b/nima/webserver/tracing/src/main/java/io/helidon/nima/webserver/tracing/TracingFeature.java index 485c2c85e5e..248a5a12013 100644 --- a/nima/webserver/tracing/src/main/java/io/helidon/nima/webserver/tracing/TracingFeature.java +++ b/nima/webserver/tracing/src/main/java/io/helidon/nima/webserver/tracing/TracingFeature.java @@ -367,7 +367,7 @@ private NimaHeaderProvider(ServerRequest request) { @Override public Iterable keys() { List result = new LinkedList<>(); - for (Http.HeaderValue header : request.headers()) { + for (Http.Header header : request.headers()) { result.add(header.headerName().lowerCase()); } return result; @@ -375,17 +375,17 @@ public Iterable keys() { @Override public Optional get(String key) { - return request.headers().first(Http.Header.create(key)); + return request.headers().first(Http.HeaderNames.create(key)); } @Override public Iterable getAll(String key) { - return request.headers().all(Http.Header.create(key), List::of); + return request.headers().all(Http.HeaderNames.create(key), List::of); } @Override public boolean contains(String key) { - return request.headers().contains(Http.Header.create(key)); + return request.headers().contains(Http.HeaderNames.create(key)); } } } diff --git a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/ListenerConfigBlueprint.java b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/ListenerConfigBlueprint.java index 980ff95197b..613e2924edf 100644 --- a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/ListenerConfigBlueprint.java +++ b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/ListenerConfigBlueprint.java @@ -132,8 +132,8 @@ interface ListenerConfigBlueprint { /** * Maximal number of bytes an entity may have. - * If {@link io.helidon.common.http.Http.Header#CONTENT_LENGTH} is used, this is checked immediately, - * if {@link io.helidon.common.http.Http.HeaderValues#TRANSFER_ENCODING_CHUNKED} is used, we will fail when the + * If {@link io.helidon.common.http.Http.HeaderNames#CONTENT_LENGTH} is used, this is checked immediately, + * if {@link io.helidon.common.http.Http.Headers#TRANSFER_ENCODING_CHUNKED} is used, we will fail when the * number of bytes read would exceed the max payload size. * Defaults to unlimited ({@code -1}). * diff --git a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/DirectHandlers.java b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/DirectHandlers.java index dd0dca72a4d..0611d5fcbaa 100644 --- a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/DirectHandlers.java +++ b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/DirectHandlers.java @@ -89,7 +89,7 @@ public void handle(RequestException httpException, ServerResponse res, boolean k response.headers() .forEach(res::header); if (!keepAlive) { - res.header(Http.HeaderValues.CONNECTION_CLOSE); + res.header(Http.Headers.CONNECTION_CLOSE); } if (res.isSent()) { diff --git a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/ErrorHandlers.java b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/ErrorHandlers.java index 8d4485b8052..da0d8e25a28 100644 --- a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/ErrorHandlers.java +++ b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/ErrorHandlers.java @@ -157,7 +157,7 @@ private void handleRequestException(ConnectionContext ctx, boolean keepAlive = e.keepAlive(); if (keepAlive && !request.content().consumed()) { // there is a chance, that the 100-Continue was already sent! In such a case, we MUST consume entity - if (request.headers().contains(Http.HeaderValues.EXPECT_100) && !request.continueSent()) { + if (request.headers().contains(Http.Headers.EXPECT_100) && !request.continueSent()) { // No content is coming, reset connection request.reset(); } else { diff --git a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/HttpRequest.java b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/HttpRequest.java index 6243605bb8f..eed3b4607a0 100644 --- a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/HttpRequest.java +++ b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/HttpRequest.java @@ -72,7 +72,7 @@ public interface HttpRequest { PeerInfo localPeer(); /** - * The content of the {@link io.helidon.common.http.Http.Header#HOST} header + * The content of the {@link io.helidon.common.http.Http.HeaderNames#HOST} header * or {@code authority} pseudo header (HTTP/2). * * @return authority of this request @@ -85,7 +85,7 @@ public interface HttpRequest { * * @param header header to set */ - void header(Http.HeaderValue header); + void header(Http.Header header); /** * Request ID on this connection. @@ -100,8 +100,8 @@ public interface HttpRequest { /** * URI as requested by the originating client (to the best of our ability to compute it). - * By default, the URI is from the {@link Http.Header#HOST} header on the current request. - * If requested URI discovery is enabled by configuration, additional headers (such as {@link Http.Header#FORWARDED}) + * By default, the URI is from the {@link io.helidon.common.http.Http.HeaderNames#HOST} header on the current request. + * If requested URI discovery is enabled by configuration, additional headers (such as {@link io.helidon.common.http.Http.HeaderNames#FORWARDED}) * may be used to derive the originally-requested URI. * * @return uri info that can be used for redirects diff --git a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/ServerResponse.java b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/ServerResponse.java index ae562e8cf56..8a36c9ec2d2 100644 --- a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/ServerResponse.java +++ b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http/ServerResponse.java @@ -58,21 +58,21 @@ default ServerResponse status(int status) { /** * Set a header. If the values are constant, please use - * {@link io.helidon.common.http.Http.Header#create(io.helidon.common.http.Http.HeaderName, String...)} and store the header - * in a constant field and call {@link #header(Http.HeaderValue)}. + * {@link io.helidon.common.http.Http.Headers#create(io.helidon.common.http.Http.HeaderName, String...)} and store the header + * in a constant field and call {@link #header(io.helidon.common.http.Http.Header)}. * * @param name header name * @param values value(s) of the header * @return this instance */ default ServerResponse header(HeaderName name, String... values) { - return header(Http.Header.create(name, values)); + return header(Http.Headers.create(name, values)); } /** * Not optimized method for setting a header. * Use for unknown headers, where {@link HeaderName} cannot be cached. - * Use {@link #header(Http.HeaderValue)} or {@link #header(HeaderName, String...)} + * Use {@link #header(io.helidon.common.http.Http.Header)} or {@link #header(HeaderName, String...)} * otherwise. * * @param name name of the header @@ -80,7 +80,7 @@ default ServerResponse header(HeaderName name, String... values) { * @return this instance */ default ServerResponse header(String name, String... values) { - return header(Http.Header.create(Http.Header.create(name), values)); + return header(Http.Headers.create(name, values)); } /** @@ -90,7 +90,7 @@ default ServerResponse header(String name, String... values) { * @return this instance * @see HeaderName */ - ServerResponse header(Http.HeaderValue header); + ServerResponse header(Http.Header header); /** * Send a response with no entity. @@ -202,7 +202,7 @@ default void send(Optional entity) { * @param length content length */ default void contentLength(long length) { - header(Http.Header.create(Http.Header.CONTENT_LENGTH, true, false, String.valueOf(length))); + header(Http.Headers.create(Http.HeaderNames.CONTENT_LENGTH, true, false, String.valueOf(length))); } /** diff --git a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1Connection.java b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1Connection.java index 6b4137f806a..3f7435b8645 100644 --- a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1Connection.java +++ b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1Connection.java @@ -31,7 +31,7 @@ import io.helidon.common.http.DirectHandler; import io.helidon.common.http.DirectHandler.EventType; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.HeaderValues; +import io.helidon.common.http.Http.Headers; import io.helidon.common.http.HttpPrologue; import io.helidon.common.http.InternalServerException; import io.helidon.common.http.RequestException; @@ -139,8 +139,8 @@ public void handle(Semaphore requestSemaphore) throws InterruptedException { recvListener.headers(ctx, headers); if (canUpgrade) { - if (headers.contains(Http.Header.UPGRADE)) { - Http1Upgrader upgrader = upgradeProviderMap.get(headers.get(Http.Header.UPGRADE).value()); + if (headers.contains(Http.HeaderNames.UPGRADE)) { + Http1Upgrader upgrader = upgradeProviderMap.get(headers.get(Http.HeaderNames.UPGRADE).value()); if (upgrader != null) { ServerConnection upgradeConnection = upgrader.upgrade(ctx, prologue, headers); // upgrader may decide not to upgrade this connection @@ -282,12 +282,12 @@ private BufferData readLengthEntity() { private void route(HttpPrologue prologue, WritableHeaders headers) { EntityStyle entity = EntityStyle.NONE; - if (headers.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED)) { + if (headers.contains(Headers.TRANSFER_ENCODING_CHUNKED)) { entity = EntityStyle.CHUNKED; this.currentEntitySize = -1; - } else if (headers.contains(Http.Header.CONTENT_LENGTH)) { + } else if (headers.contains(Http.HeaderNames.CONTENT_LENGTH)) { try { - this.currentEntitySize = headers.get(Http.Header.CONTENT_LENGTH).value(long.class); + this.currentEntitySize = headers.get(Http.HeaderNames.CONTENT_LENGTH).value(long.class); if (maxPayloadSize != -1 && currentEntitySize > maxPayloadSize) { throw RequestException.builder() .type(EventType.BAD_REQUEST) @@ -319,7 +319,7 @@ private void route(HttpPrologue prologue, WritableHeaders headers) { writer, request, !request.headers() - .contains(HeaderValues.CONNECTION_CLOSE)); + .contains(Headers.CONNECTION_CLOSE)); routing.route(ctx, request, response); // we have handled a request without request entity @@ -329,7 +329,7 @@ private void route(HttpPrologue prologue, WritableHeaders headers) { boolean expectContinue = false; // Expect: 100-continue - if (headers.contains(HeaderValues.EXPECT_100)) { + if (headers.contains(Headers.EXPECT_100)) { if (this.http1Config.continueImmediately()) { writer.writeNow(BufferData.create(CONTINUE_100)); } @@ -339,8 +339,8 @@ private void route(HttpPrologue prologue, WritableHeaders headers) { ContentDecoder decoder; if (contentEncodingContext.contentDecodingEnabled()) { // there may be some decoder used - if (headers.contains(Http.Header.CONTENT_ENCODING)) { - String contentEncoding = headers.get(Http.Header.CONTENT_ENCODING).value(); + if (headers.contains(Http.HeaderNames.CONTENT_ENCODING)) { + String contentEncoding = headers.get(Http.HeaderNames.CONTENT_ENCODING).value(); if (contentEncodingContext.contentDecodingSupported(contentEncoding)) { decoder = contentEncodingContext.decoder(contentEncoding); } else { @@ -355,7 +355,7 @@ private void route(HttpPrologue prologue, WritableHeaders headers) { } } else { // Check whether Content-Encoding header is present when headers validation is enabled - if (http1Config.validateHeaders() && headers.contains(Http.Header.CONTENT_ENCODING)) { + if (http1Config.validateHeaders() && headers.contains(Http.HeaderNames.CONTENT_ENCODING)) { throw RequestException.builder() .type(EventType.BAD_REQUEST) .request(DirectTransportRequest.create(prologue, headers)) @@ -382,7 +382,7 @@ private void route(HttpPrologue prologue, WritableHeaders headers) { writer, request, !request.headers() - .contains(HeaderValues.CONNECTION_CLOSE)); + .contains(Headers.CONNECTION_CLOSE)); routing.route(ctx, request, response); @@ -400,7 +400,7 @@ private void route(HttpPrologue prologue, WritableHeaders headers) { } private void consumeEntity(Http1ServerRequest request, Http1ServerResponse response) { - if (response.headers().contains(HeaderValues.CONNECTION_CLOSE) || request.content().consumed()) { + if (response.headers().contains(Headers.CONNECTION_CLOSE) || request.content().consumed()) { // we do not care about request entity if connection is getting closed return; } @@ -408,7 +408,7 @@ private void consumeEntity(Http1ServerRequest request, Http1ServerResponse respo try { request.content().consume(); } catch (Exception e) { - boolean keepAlive = request.content().consumed() && response.headers().contains(HeaderValues.CONNECTION_KEEP_ALIVE); + boolean keepAlive = request.content().consumed() && response.headers().contains(Headers.CONNECTION_KEEP_ALIVE); // we must close connection, as we could not consume request if (!response.isSent()) { throw new InternalServerException(e.getMessage(), e, keepAlive); @@ -431,10 +431,10 @@ private void handleRequestException(RequestException e) { BufferData buffer = BufferData.growing(128); ServerResponseHeaders headers = response.headers(); if (!e.keepAlive()) { - headers.set(HeaderValues.CONNECTION_CLOSE); + headers.set(Http.Headers.CONNECTION_CLOSE); } byte[] message = response.entity().orElse(BufferData.EMPTY_BYTES); - headers.set(Http.Header.create(Http.Header.CONTENT_LENGTH, String.valueOf(message.length))); + headers.set(Headers.create(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(message.length))); Http1ServerResponse.nonEntityBytes(headers, response.status(), buffer, response.keepAlive()); if (message.length != 0) { diff --git a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1ServerRequest.java b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1ServerRequest.java index aca2b734ff5..6554c1f0247 100644 --- a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1ServerRequest.java +++ b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1ServerRequest.java @@ -172,11 +172,11 @@ public PeerInfo localPeer() { @Override public String authority() { - return headers.get(Http.Header.HOST).value(); + return headers.get(Http.HeaderNames.HOST).value(); } @Override - public void header(Http.HeaderValue header) { + public void header(Http.Header header) { if (writable == null) { writable = WritableHeaders.create(headers); } diff --git a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1ServerResponse.java b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1ServerResponse.java index 12a3d98a054..de20d0e71c3 100644 --- a/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1ServerResponse.java +++ b/nima/webserver/webserver/src/main/java/io/helidon/nima/webserver/http1/Http1ServerResponse.java @@ -29,12 +29,10 @@ import io.helidon.common.HelidonServiceLoader; import io.helidon.common.buffers.BufferData; import io.helidon.common.buffers.DataWriter; -import io.helidon.common.http.Headers; import io.helidon.common.http.Http; import io.helidon.common.http.Http.DateTime; +import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; -import io.helidon.common.http.Http.HeaderValue; -import io.helidon.common.http.Http.HeaderValues; import io.helidon.common.http.HttpException; import io.helidon.common.http.ServerResponseHeaders; import io.helidon.common.http.WritableHeaders; @@ -55,10 +53,10 @@ class Http1ServerResponse extends ServerResponseBase { private static final byte[] OK_200 = "HTTP/1.1 200 OK\r\n".getBytes(StandardCharsets.UTF_8); private static final byte[] DATE = "Date: ".getBytes(StandardCharsets.UTF_8); private static final byte[] TERMINATING_CHUNK = "0\r\n\r\n".getBytes(StandardCharsets.UTF_8); - private static final HeaderName STREAM_STATUS_NAME = Http.Header.create("stream-status"); - private static final HeaderName STREAM_RESULT_NAME = Http.Header.create("stream-result"); - private static final HeaderValue STREAM_TRAILERS = - Http.Header.create(Http.Header.TRAILER, STREAM_STATUS_NAME.defaultCase() + private static final HeaderName STREAM_STATUS_NAME = Http.HeaderNames.create("stream-status"); + private static final HeaderName STREAM_RESULT_NAME = Http.HeaderNames.create("stream-result"); + private static final Header STREAM_TRAILERS = + Http.Headers.create(Http.HeaderNames.TRAILER, STREAM_STATUS_NAME.defaultCase() + "," + STREAM_RESULT_NAME.defaultCase()); private static final List SINK_PROVIDERS @@ -110,7 +108,7 @@ static void nonEntityBytes(ServerResponseHeaders headers, buffer.write('\n'); } // date header - if (!headers.contains(Http.Header.DATE)) { + if (!headers.contains(Http.HeaderNames.DATE)) { buffer.write(DATE); byte[] dateBytes = DateTime.http1Bytes(); buffer.write(dateBytes); @@ -119,10 +117,10 @@ static void nonEntityBytes(ServerResponseHeaders headers, // either content-length or chunked encoding // if content length - make sure to compare it when writing actual entity (streaming and send(entity)) if (keepAlive) { - headers.setIfAbsent(HeaderValues.CONNECTION_KEEP_ALIVE); + headers.setIfAbsent(Http.Headers.CONNECTION_KEEP_ALIVE); } else { // we must override even if user sets keep alive, as close was requested - headers.set(HeaderValues.CONNECTION_CLOSE); + headers.set(Http.Headers.CONNECTION_CLOSE); } // write headers followed by empty line @@ -133,7 +131,7 @@ static void nonEntityBytes(ServerResponseHeaders headers, } @Override - public Http1ServerResponse header(HeaderValue header) { + public Http1ServerResponse header(Header header) { this.headers.set(header); return this; } @@ -259,7 +257,7 @@ private void handleSinkData(Object data, MediaType mediaType) { } else { GenericType type = GenericType.create(data); WritableHeaders resHeaders = WritableHeaders.create(); - resHeaders.set(Http.Header.CONTENT_TYPE, mediaType.text()); + resHeaders.set(Http.HeaderNames.CONTENT_TYPE, mediaType.text()); EntityWriter writer = mediaContext.writer(type, EMPTY_HEADERS, resHeaders); writer.write(type, data, outputStream, EMPTY_HEADERS, resHeaders); } @@ -269,8 +267,8 @@ private void handleSinkData(Object data, MediaType mediaType) { } } - private static void writeHeaders(Headers headers, BufferData buffer) { - for (HeaderValue header : headers) { + private static void writeHeaders(io.helidon.common.http.Headers headers, BufferData buffer) { + for (Header header : headers) { header.writeHttp1Header(buffer); } } @@ -285,9 +283,9 @@ private BufferData responseBuffer(byte[] bytes) { } isSent = true; - headers.setIfAbsent(HeaderValues.CONNECTION_KEEP_ALIVE); - if (!headers.contains(Http.Header.CONTENT_LENGTH)) { - headers.set(Http.Header.create(Http.Header.CONTENT_LENGTH, String.valueOf(bytes.length))); + headers.setIfAbsent(Http.Headers.CONNECTION_KEEP_ALIVE); + if (!headers.contains(Http.HeaderNames.CONTENT_LENGTH)) { + headers.set(Http.Headers.create(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(bytes.length))); } sendListener.headers(ctx, headers); @@ -345,11 +343,11 @@ private BlockingOutputStream(ServerResponseHeaders headers, this.responseCloseRunnable = responseCloseRunnable; this.ctx = ctx; this.sendListener = sendListener; - this.isChunked = !headers.contains(Http.Header.CONTENT_LENGTH); + this.isChunked = !headers.contains(Http.HeaderNames.CONTENT_LENGTH); this.contentLength = headers.contentLength().orElse(-1); this.request = request; this.keepAlive = keepAlive; - this.forcedChunked = headers.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED); + this.forcedChunked = headers.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED); } @Override @@ -419,7 +417,7 @@ void commit() { } if (isChunked || forcedChunked) { - if (request.headers().contains(HeaderValues.TE_TRAILERS)) { + if (request.headers().contains(Http.Headers.TE_TRAILERS)) { // not optimized, trailers enabled: we need to write trailers trailers.set(STREAM_STATUS_NAME, String.valueOf(status.get().code())); trailers.set(STREAM_RESULT_NAME, streamResult.get()); @@ -484,7 +482,7 @@ private void write(BufferData buffer) throws IOException { } if (firstByte) { - if (request.headers().contains(HeaderValues.TE_TRAILERS)) { + if (request.headers().contains(Http.Headers.TE_TRAILERS)) { // proper stream with multiple buffers, write status amd headers headers.add(STREAM_TRAILERS); } @@ -501,14 +499,14 @@ private void write(BufferData buffer) throws IOException { private void sendFirstChunkOnly() { int contentLength; if (firstBuffer == null) { - headers.set(HeaderValues.CONTENT_LENGTH_ZERO); + headers.set(Http.Headers.CONTENT_LENGTH_ZERO); contentLength = 0; } else { - headers.set(Http.Header.create(Http.Header.CONTENT_LENGTH, String.valueOf(firstBuffer.available()))); + headers.set(Http.Headers.create(Http.HeaderNames.CONTENT_LENGTH, String.valueOf(firstBuffer.available()))); contentLength = firstBuffer.available(); } isChunked = false; - headers.remove(Http.Header.TRANSFER_ENCODING); + headers.remove(Http.HeaderNames.TRANSFER_ENCODING); // at this moment, we must send headers sendListener.headers(ctx, headers); @@ -525,18 +523,18 @@ private void sendFirstChunkOnly() { } private void sendHeadersAndPrepare() { - if (headers.contains(Http.Header.CONTENT_LENGTH)) { + if (headers.contains(Http.HeaderNames.CONTENT_LENGTH)) { contentLength = headers.contentLength().orElse(-1); isChunked = false; } else { contentLength = -1; // Add chunked encoding, if there is no other transfer-encoding headers - if (!headers.contains(Http.Header.TRANSFER_ENCODING)) { - headers.set(HeaderValues.TRANSFER_ENCODING_CHUNKED); + if (!headers.contains(Http.HeaderNames.TRANSFER_ENCODING)) { + headers.set(Http.Headers.TRANSFER_ENCODING_CHUNKED); } else { // Add chunked encoding, if it's not part of existing transfer-encoding headers - if (!headers.contains(HeaderValues.TRANSFER_ENCODING_CHUNKED)) { - headers.add(HeaderValues.TRANSFER_ENCODING_CHUNKED); + if (!headers.contains(Http.Headers.TRANSFER_ENCODING_CHUNKED)) { + headers.add(Http.Headers.TRANSFER_ENCODING_CHUNKED); } } } diff --git a/nima/websocket/client/src/main/java/io/helidon/nima/websocket/client/WsClientImpl.java b/nima/websocket/client/src/main/java/io/helidon/nima/websocket/client/WsClientImpl.java index ea923979dab..55bb0f23c11 100644 --- a/nima/websocket/client/src/main/java/io/helidon/nima/websocket/client/WsClientImpl.java +++ b/nima/websocket/client/src/main/java/io/helidon/nima/websocket/client/WsClientImpl.java @@ -28,7 +28,6 @@ import io.helidon.common.http.ClientRequestHeaders; import io.helidon.common.http.ClientResponseHeaders; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.common.socket.SocketContext; import io.helidon.common.uri.UriInfo; import io.helidon.nima.webclient.api.ClientConnection; @@ -45,15 +44,15 @@ class WsClientImpl implements WsClient { * Supported WebSocket version. */ static final String SUPPORTED_VERSION = "13"; - static final Http.HeaderValue HEADER_UPGRADE_WS = Http.Header.createCached(Http.Header.UPGRADE, "websocket"); - static final Http.HeaderName HEADER_WS_PROTOCOL = Http.Header.create("Sec-WebSocket-Protocol"); - private static final Http.HeaderValue HEADER_WS_VERSION = Http.Header.createCached(Http.Header.create( + 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( "Sec-WebSocket-Version"), SUPPORTED_VERSION); private static final System.Logger LOGGER = System.getLogger(WsClient.class.getName()); - private static final Http.HeaderValue HEADER_CONN_UPGRADE = Header.create(Header.CONNECTION, "Upgrade"); - private static final Http.HeaderName HEADER_WS_ACCEPT = Header.create("Sec-WebSocket-Accept"); - private static final Http.HeaderName HEADER_WS_KEY = Header.create("Sec-WebSocket-Key"); + 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 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 +71,7 @@ class WsClientImpl implements WsClient { ClientRequestHeaders headers = http1Client.prototype().defaultRequestHeaders(); headers.set(HEADER_UPGRADE_WS); headers.set(HEADER_WS_VERSION); - headers.set(Http.HeaderValues.CONTENT_LENGTH_ZERO); + headers.set(Http.Headers.CONTENT_LENGTH_ZERO); if (clientConfig.protocolConfig().subProtocols().isEmpty()) { headers.remove(HEADER_WS_PROTOCOL); } else { @@ -101,7 +100,7 @@ public void connect(URI uri, WsListener listener) { upgradeRequest.uri(ClientUri.create(resolvedUri).scheme("https")); } - upgradeRequest.headers(headers -> headers.setIfAbsent(Header.create(Header.HOST, resolvedUri + upgradeRequest.headers(headers -> headers.setIfAbsent(Http.Headers.create(Http.HeaderNames.HOST, resolvedUri .authority()))); UpgradeResponse upgradeResponse = upgradeRequest.upgrade("websocket"); diff --git a/nima/websocket/webserver/src/main/java/io/helidon/nima/websocket/webserver/WsUpgrader.java b/nima/websocket/webserver/src/main/java/io/helidon/nima/websocket/webserver/WsUpgrader.java index 16885a68cc2..8f08678c1a8 100644 --- a/nima/websocket/webserver/src/main/java/io/helidon/nima/websocket/webserver/WsUpgrader.java +++ b/nima/websocket/webserver/src/main/java/io/helidon/nima/websocket/webserver/WsUpgrader.java @@ -28,8 +28,8 @@ import io.helidon.common.http.DirectHandler; import io.helidon.common.http.Headers; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; import io.helidon.common.http.Http.HeaderName; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.http.HttpPrologue; import io.helidon.common.http.NotFoundException; import io.helidon.common.http.RequestException; @@ -49,22 +49,22 @@ public class WsUpgrader implements Http1Upgrader { /** * Websocket key header name. */ - public static final HeaderName WS_KEY = Header.create("Sec-WebSocket-Key"); + public static final HeaderName WS_KEY = HeaderNames.create("Sec-WebSocket-Key"); /** * Websocket version header name. */ - public static final HeaderName WS_VERSION = Header.create("Sec-WebSocket-Version"); + public static final HeaderName WS_VERSION = HeaderNames.create("Sec-WebSocket-Version"); /** * Websocket protocol header name. */ - public static final HeaderName PROTOCOL = Header.create("Sec-WebSocket-Protocol"); + public static final HeaderName PROTOCOL = HeaderNames.create("Sec-WebSocket-Protocol"); /** * Websocket protocol header name. */ - public static final HeaderName EXTENSIONS = Header.create("Sec-WebSocket-Extensions"); + public static final HeaderName EXTENSIONS = HeaderNames.create("Sec-WebSocket-Extensions"); /** * Switching response prefix. @@ -87,7 +87,7 @@ public class WsUpgrader implements Http1Upgrader { /** * Supported version header. */ - protected static final Http.HeaderValue SUPPORTED_VERSION_HEADER = Header.create(WS_VERSION, SUPPORTED_VERSION); + protected static final Http.Header SUPPORTED_VERSION_HEADER = Http.Headers.create(WS_VERSION, SUPPORTED_VERSION); static final Headers EMPTY_HEADERS = WritableHeaders.create(); private static final System.Logger LOGGER = System.getLogger(WsUpgrader.class.getName()); private static final byte[] KEY_SUFFIX = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".getBytes(US_ASCII); @@ -153,8 +153,8 @@ public ServerConnection upgrade(ConnectionContext ctx, HttpPrologue prologue, Wr } if (!anyOrigin()) { - if (headers.contains(Header.ORIGIN)) { - String origin = headers.get(Header.ORIGIN).value(); + if (headers.contains(Http.HeaderNames.ORIGIN)) { + String origin = headers.get(Http.HeaderNames.ORIGIN).value(); if (!origins().contains(origin)) { throw RequestException.builder() .message("Invalid Origin") diff --git a/openapi/src/main/java/io/helidon/openapi/OpenApiFeature.java b/openapi/src/main/java/io/helidon/openapi/OpenApiFeature.java index 4fe11787e83..26eb77c631e 100644 --- a/openapi/src/main/java/io/helidon/openapi/OpenApiFeature.java +++ b/openapi/src/main/java/io/helidon/openapi/OpenApiFeature.java @@ -390,7 +390,7 @@ private Optional chooseResponseMediaType(ServerRequest req) { ServerRequestHeaders headersToCheck = req.headers(); if (headersToCheck.acceptedTypes().isEmpty()) { WritableHeaders writableHeaders = WritableHeaders.create(headersToCheck); - writableHeaders.add(Http.Header.ACCEPT, DEFAULT_RESPONSE_MEDIA_TYPE.toString()); + writableHeaders.add(Http.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 cf7c8d54d06..3e2b527161d 100644 --- a/openapi/src/main/java/io/helidon/openapi/OpenApiUiBase.java +++ b/openapi/src/main/java/io/helidon/openapi/OpenApiUiBase.java @@ -139,7 +139,7 @@ protected Map options() { protected boolean sendStaticText(ServerRequest request, ServerResponse response, HttpMediaType mediaType) { try { response - .header(Http.Header.CONTENT_TYPE, mediaType.toString()) + .header(Http.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); diff --git a/security/integration/nima/src/main/java/io/helidon/security/integration/nima/SecurityHandler.java b/security/integration/nima/src/main/java/io/helidon/security/integration/nima/SecurityHandler.java index 6830e94171a..e2fdcbcda89 100644 --- a/security/integration/nima/src/main/java/io/helidon/security/integration/nima/SecurityHandler.java +++ b/security/integration/nima/src/main/java/io/helidon/security/integration/nima/SecurityHandler.java @@ -619,7 +619,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.Header.create(Http.Header.create(key), value))); + .forEach((key, value) -> res.headers().set(Http.Headers.create(key, value))); switch (response.status()) { case SUCCESS: @@ -671,7 +671,7 @@ private boolean atnAbstainFailure(ServerResponse res, AuthenticationResponse res abortRequest(res, response, Http.Status.UNAUTHORIZED_401.code(), - Map.of(Http.Header.WWW_AUTHENTICATE, + Map.of(Http.HeaderNames.WWW_AUTHENTICATE, List.of("Basic realm=\"Security Realm\""))); return true; } @@ -705,7 +705,7 @@ private void abortRequest(ServerResponse res, } else { Map> tmpHeaders = new HashMap<>(); response.responseHeaders() - .forEach((key, value) -> tmpHeaders.put(Http.Header.create(key), value)); + .forEach((key, value) -> tmpHeaders.put(Http.HeaderNames.create(key), value)); responseHeaders = tmpHeaders; } diff --git a/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityBuilderGateDefaultsTest.java b/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityBuilderGateDefaultsTest.java index e358f950f4c..1f461a88bf7 100644 --- a/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityBuilderGateDefaultsTest.java +++ b/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityBuilderGateDefaultsTest.java @@ -22,7 +22,7 @@ import io.helidon.common.context.Context; import io.helidon.common.context.Contexts; import io.helidon.common.http.Http; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.config.Config; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpServer; @@ -106,7 +106,7 @@ public static void setup(WebServerConfig.Builder serverBuilder) { .get("/{*}", (req, res) -> { Optional securityContext = Contexts.context() .flatMap(it -> it.get(SecurityContext.class)); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Hello, you are: \n" + securityContext .map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()) .orElse("Security context is null")); @@ -173,13 +173,13 @@ void basicTest401() { is(Http.Status.UNAUTHORIZED_401)); } - assertThat(response.headers().first(Http.Header.WWW_AUTHENTICATE), + assertThat(response.headers().first(Http.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.Header.WWW_AUTHENTICATE), + assertThat(response.headers().first(Http.HeaderNames.WWW_AUTHENTICATE), optionalValue(is("Basic realm=\"mic\""))); } diff --git a/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityFromConfigTest.java b/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityFromConfigTest.java index edd9f667d3c..dae5e7fe2f4 100644 --- a/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityFromConfigTest.java +++ b/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityFromConfigTest.java @@ -20,7 +20,7 @@ import io.helidon.common.context.Context; import io.helidon.common.context.Contexts; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.config.Config; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpServer; @@ -59,7 +59,7 @@ public static void setup(WebServerConfig.Builder serverBuilder) { .get("/*", (req, res) -> { Optional securityContext = Contexts.context() .flatMap(ctx -> ctx.get(SecurityContext.class)); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Hello, you are: \n" + securityContext .map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()) .orElse("Security context is null")); diff --git a/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityProgrammaticTest.java b/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityProgrammaticTest.java index 43893cdd8b4..0b1490688c5 100644 --- a/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityProgrammaticTest.java +++ b/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityProgrammaticTest.java @@ -22,7 +22,7 @@ import io.helidon.common.context.Context; import io.helidon.common.context.Contexts; import io.helidon.common.http.Http; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.http.HttpMediaTypes; import io.helidon.config.Config; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpServer; @@ -86,7 +86,7 @@ public static void setup(WebServerConfig.Builder serverBuilder) { .get("/{*}", (req, res) -> { Optional securityContext = Contexts.context() .flatMap(it -> it.get(SecurityContext.class)); - res.headers().contentType(HttpMediaType.PLAINTEXT_UTF_8); + res.headers().contentType(HttpMediaTypes.PLAINTEXT_UTF_8); res.send("Hello, you are: \n" + securityContext .map(ctx -> ctx.user().orElse(SecurityContext.ANONYMOUS).toString()) .orElse("Security context is null")); diff --git a/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityTests.java b/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityTests.java index ff35a0d3c42..5c2737dfdfb 100644 --- a/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityTests.java +++ b/security/integration/nima/src/test/java/io/helidon/security/integration/nima/WebSecurityTests.java @@ -102,9 +102,9 @@ void basicTest401() { assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); String header = response.headers() - .first(Http.Header.WWW_AUTHENTICATE) + .first(Http.HeaderNames.WWW_AUTHENTICATE) .orElseThrow(() -> new IllegalStateException( - "Header " + Http.Header.WWW_AUTHENTICATE + " is" + " not present in response!")); + "Header " + Http.HeaderNames.WWW_AUTHENTICATE + " is" + " not present in response!")); assertThat(header.toLowerCase(), is("basic realm=\"mic\"")); } @@ -113,9 +113,9 @@ void basicTest401() { assertThat(response.status(), is(Http.Status.UNAUTHORIZED_401)); String header = response.headers() - .first(Http.Header.WWW_AUTHENTICATE) + .first(Http.HeaderNames.WWW_AUTHENTICATE) .orElseThrow(() -> new IllegalStateException( - "Header " + Http.Header.WWW_AUTHENTICATE + " is" + " not present in response!")); + "Header " + Http.HeaderNames.WWW_AUTHENTICATE + " is" + " not present in response!")); assertThat(header.toLowerCase(), is("basic realm=\"mic\"")); } } 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 c078ccf9604..4a6dc751912 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 @@ -257,7 +257,7 @@ protected List getGrantsFromServer(String idcsTenantId, .post() .uri(multitenantEndpoints.assertEndpoint(idcsTenantId)) .headers(it -> { - it.add(Http.Header.AUTHORIZATION, "Bearer " + appToken); + it.add(Http.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 55cd6dc1793..27fbc238334 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 @@ -196,7 +196,7 @@ private List obtainGrantsFromServer(String subjectName, String .post() .uri(asserterUri) .headers(it -> { - it.add(Http.Header.AUTHORIZATION, "Bearer " + appToken); + it.add(Http.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 c0ecc281b86..faac6177cef 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 @@ -450,7 +450,7 @@ private AppTokenData fromServer(RoleMapTracing tracing) { HttpClientRequest request = webClient.post() .uri(tokenEndpointUri) - .header(Http.HeaderValues.ACCEPT_JSON); + .header(Http.Headers.ACCEPT_JSON); try (HttpClientResponse response = request.submit(params)) { if (response.status().family() == Http.Status.Family.SUCCESSFUL) { 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 bc81386c836..595e2a49e27 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 @@ -50,7 +50,7 @@ static JwkKeys signJwk(WebClient appWebClient, try (HttpClientResponse response = appWebClient.post() .uri(tokenEndpointUri) - .header(Http.HeaderValues.ACCEPT_JSON) + .header(Http.Headers.ACCEPT_JSON) .submit(form)) { if (response.status().family() == Http.Status.Family.SUCCESSFUL) { @@ -61,7 +61,7 @@ static JwkKeys signJwk(WebClient appWebClient, // get the jwk from server JsonObject jwkJson = generalClient.get() .uri(signJwkUri) - .header(Http.Header.AUTHORIZATION, "Bearer " + accessToken) + .header(Http.HeaderNames.AUTHORIZATION, "Bearer " + accessToken) .requestEntity(JsonObject.class); return JwkKeys.create(jwkJson); diff --git a/security/providers/oidc-common/src/main/java/io/helidon/security/providers/oidc/common/Tenant.java b/security/providers/oidc-common/src/main/java/io/helidon/security/providers/oidc/common/Tenant.java index 09194748ba0..c0a7c6b3bf7 100644 --- a/security/providers/oidc-common/src/main/java/io/helidon/security/providers/oidc/common/Tenant.java +++ b/security/providers/oidc-common/src/main/java/io/helidon/security/providers/oidc/common/Tenant.java @@ -126,7 +126,7 @@ public static Tenant create(OidcConfig oidcConfig, TenantConfig tenantConfig) { //This is workaround for missing Níma client security. This adds Authorization header to be used in every request. byte[] byteArray = (tenantConfig.clientId() + ":" + tenantConfig.clientSecret()).getBytes(StandardCharsets.UTF_8); String base64 = Base64.getEncoder().encodeToString(byteArray); - webClientBuilder.addHeader(Http.Header.AUTHORIZATION, "Basic " + base64); + webClientBuilder.addHeader(Http.HeaderNames.AUTHORIZATION, "Basic " + base64); } WebClient appWebClient = webClientBuilder.build(); 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 5bbdc9bb378..ce7e0cf6326 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 @@ -61,7 +61,7 @@ import jakarta.json.JsonObject; -import static io.helidon.common.http.Http.Header.HOST; +import static io.helidon.common.http.Http.HeaderNames.HOST; import static io.helidon.security.providers.oidc.common.spi.TenantConfigFinder.DEFAULT_TENANT_ID; /** @@ -320,7 +320,7 @@ private void logoutWithTenant(ServerRequest req, ServerResponse res, Tenant tena headers.addCookie(tenantCookieHandler.removeCookie().build()); res.status(Http.Status.TEMPORARY_REDIRECT_307) - .header(Http.Header.LOCATION, sb.toString()) + .header(Http.HeaderNames.LOCATION, sb.toString()) .send(); } catch (Exception e) { sendError(res, e); @@ -379,7 +379,7 @@ private void processCodeWithTenant(String code, ServerRequest req, ServerRespons HttpClientRequest post = webClient.post() .uri(tenant.tokenEndpointUri()) - .header(Http.HeaderValues.ACCEPT_JSON); + .header(Http.Headers.ACCEPT_JSON); OidcUtil.updateRequest(OidcConfig.RequestType.CODE_TO_TOKEN, tenantConfig, form); @@ -461,7 +461,7 @@ private String processJsonResponse(ServerRequest req, } state = increaseRedirectCounter(state); - res.headers().add(Http.Header.LOCATION, state); + res.headers().add(Http.HeaderNames.LOCATION, state); if (oidcConfig.useCookie()) { try { 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 6837039ec5a..e0d9eefa596 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,6 +34,7 @@ import io.helidon.common.Errors; import io.helidon.common.http.Http; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.common.parameters.Parameters; import io.helidon.nima.webclient.api.HttpClientRequest; import io.helidon.nima.webclient.api.HttpClientResponse; @@ -117,8 +118,8 @@ class TenantAuthenticationHandler { HttpClientRequest post = tenant.appWebClient() .post() .uri(tenant.introspectUri()) - .header(Http.HeaderValues.ACCEPT_JSON) - .headers(it -> it.add(Http.Header.CACHE_CONTROL, "no-cache, no-store, must-revalidate")); + .header(Http.Headers.ACCEPT_JSON) + .headers(it -> it.add(HeaderNames.CACHE_CONTROL, "no-cache, no-store, must-revalidate")); OidcUtil.updateRequest(OidcConfig.RequestType.INTROSPECT_JWT, tenantConfig, form); @@ -364,14 +365,15 @@ private AuthenticationResponse errorResponseNoRedirect(String code, String descr return AuthenticationResponse.builder() .status(SecurityResponse.SecurityStatus.FAILURE) .statusCode(Http.Status.UNAUTHORIZED_401.code()) - .responseHeader(Http.Header.WWW_AUTHENTICATE.defaultCase(), "Bearer realm=\"" + tenantConfig.realm() + "\"") + .responseHeader(HeaderNames.WWW_AUTHENTICATE.defaultCase(), + "Bearer realm=\"" + tenantConfig.realm() + "\"") .description(description) .build(); } else { return AuthenticationResponse.builder() .status(SecurityResponse.SecurityStatus.FAILURE) .statusCode(status.code()) - .responseHeader(Http.Header.WWW_AUTHENTICATE.defaultCase(), errorHeader(code, description)) + .responseHeader(HeaderNames.WWW_AUTHENTICATE.defaultCase(), errorHeader(code, description)) .description(description) .build(); } 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 26eab9d5a6f..3dad8ca4569 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 @@ -352,7 +352,7 @@ private void runMetricsAndHealthTest(String edition, String jsonLibrary, boolean String payload = webClient.get() .path("/metrics") - .header(Http.Header.ACCEPT, MediaTypes.WILDCARD.text()) + .header(Http.HeaderNames.ACCEPT, MediaTypes.WILDCARD.text()) .requestEntity(String.class); assertThat("Making sure we got Prometheus format", payload, anyOf(startsWith("# TYPE"), startsWith("# HELP"))); @@ -362,7 +362,7 @@ private void runMetricsAndHealthTest(String edition, String jsonLibrary, boolean if (!Objects.equals(jsonLibrary, "jackson")) { jsonObject = webClient.get() .path("/metrics") - .header(Http.Header.ACCEPT, MediaTypes.APPLICATION_JSON.text()) + .header(Http.HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) .requestEntity(JsonObject.class); assertThat("Checking request count", jsonObject.getJsonObject("vendor").getInt("requests.count"), greaterThan(0)); @@ -370,7 +370,7 @@ private void runMetricsAndHealthTest(String edition, String jsonLibrary, boolean jsonObject = webClient.get() .path("/health") - .header(Http.Header.ACCEPT, MediaTypes.APPLICATION_JSON.text()) + .header(Http.HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) .requestEntity(JsonObject.class); assertThat("Checking health status", jsonObject.getString("status"), is("UP")); if (edition.equals("mp")) { @@ -393,7 +393,7 @@ void routing(String edition) throws Exception { HttpClientResponse response = webClient.get() .path("/badurl") - .header(Http.Header.ACCEPT, MediaTypes.APPLICATION_JSON.text()) + .header(Http.HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) .request(); assertThat("Checking encode URL response", response.status(), is(Http.Status.NOT_FOUND_404)); } finally { 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 b83093e2abb..012de981a1f 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 @@ -24,7 +24,7 @@ @RequestScoped public class TenantContext { - private static final Http.HeaderName TENANT_ID = Http.Header.create("x-tenant-id"); + private static final Http.HeaderName TENANT_ID = Http.HeaderNames.create("x-tenant-id"); @Context private ServerRequest request; diff --git a/tests/integration/dbclient/app/src/main/java/io/helidon/tests/integration/dbclient/app/tools/ExitService.java b/tests/integration/dbclient/app/src/main/java/io/helidon/tests/integration/dbclient/app/tools/ExitService.java index ba20f056861..9a1295ebda7 100644 --- a/tests/integration/dbclient/app/src/main/java/io/helidon/tests/integration/dbclient/app/tools/ExitService.java +++ b/tests/integration/dbclient/app/src/main/java/io/helidon/tests/integration/dbclient/app/tools/ExitService.java @@ -15,7 +15,7 @@ */ package io.helidon.tests.integration.dbclient.app.tools; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.media.type.MediaTypes; import io.helidon.nima.webserver.WebServer; import io.helidon.nima.webserver.http.HttpRules; import io.helidon.nima.webserver.http.HttpService; @@ -44,7 +44,7 @@ public void setServer(WebServer server) { } private void exit(ServerRequest request, ServerResponse response) { - response.headers().contentType(HttpMediaType.TEXT_PLAIN); + response.headers().contentType(MediaTypes.TEXT_PLAIN); response.send("Testing web application shutting down."); server.stop(); } diff --git a/tests/integration/harness/src/main/java/io/helidon/tests/integration/harness/TestClient.java b/tests/integration/harness/src/main/java/io/helidon/tests/integration/harness/TestClient.java index 590ab2b780f..8e68e2bf5c3 100644 --- a/tests/integration/harness/src/main/java/io/helidon/tests/integration/harness/TestClient.java +++ b/tests/integration/harness/src/main/java/io/helidon/tests/integration/harness/TestClient.java @@ -26,7 +26,7 @@ import java.util.Map; import java.util.Objects; -import io.helidon.common.http.HttpMediaType; +import io.helidon.common.media.type.MediaTypes; import io.helidon.nima.http.media.jsonp.JsonpSupport; import io.helidon.nima.webclient.http1.Http1Client; import io.helidon.nima.webclient.http1.Http1ClientRequest; @@ -154,7 +154,7 @@ public JsonValue callServiceAndGetData(String service, String method) { */ public JsonObject callServiceAndGetRawData(String service, String method, Map params) { Http1ClientRequest rb = clientGetBuilderWithPath(service, method); - rb.headers().accept(HttpMediaType.APPLICATION_JSON); + rb.headers().accept(MediaTypes.APPLICATION_JSON); return callService(rb, params); } 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 e4315d8ce7e..e3756362e70 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 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021, 2022 Oracle and/or its affiliates. + * Copyright (c) 2021, 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. @@ -86,7 +86,7 @@ void testSecuredCallout() { String response = webTarget.path("/test/secured") .queryParam("port", port) .request() - .header(Http.Header.AUTHORIZATION.defaultCase(), "Bearer " + tokenContent) + .header(Http.HeaderNames.AUTHORIZATION.defaultCase(), "Bearer " + tokenContent) .get(String.class); assertThat(response, is("hello")); diff --git a/tests/integration/native-image/nima-1/src/main/java/io/helidon/tests/integration/nativeimage/nima1/WebClientService.java b/tests/integration/native-image/nima-1/src/main/java/io/helidon/tests/integration/nativeimage/nima1/WebClientService.java index e890a338d82..9d187949241 100644 --- a/tests/integration/native-image/nima-1/src/main/java/io/helidon/tests/integration/nativeimage/nima1/WebClientService.java +++ b/tests/integration/native-image/nima-1/src/main/java/io/helidon/tests/integration/nativeimage/nima1/WebClientService.java @@ -48,7 +48,7 @@ public WebClientService(Config config, MockZipkinService zipkinService) { this.context = "http://localhost:" + config.get("port").asInt().orElse(7076); client = WebClient.builder() .baseUri(context) - .addHeader(Http.Header.ACCEPT, MediaTypes.APPLICATION_JSON.text()) + .addHeader(Http.HeaderNames.ACCEPT, MediaTypes.APPLICATION_JSON.text()) .config(config.get("client")) .build(); } @@ -63,12 +63,12 @@ public void routing(HttpRules rules) { private void redirect(ServerRequest request, ServerResponse response) { - response.headers().add(Http.Header.LOCATION, context + "/wc/endpoint"); + response.headers().add(Http.HeaderNames.LOCATION, context + "/wc/endpoint"); response.status(Http.Status.MOVED_PERMANENTLY_301).send(); } private void redirectInfinite(ServerRequest serverRequest, ServerResponse response) { - response.headers().add(Http.Header.LOCATION, context + "/wc/redirect/infinite"); + response.headers().add(Http.HeaderNames.LOCATION, context + "/wc/redirect/infinite"); response.status(Http.Status.MOVED_PERMANENTLY_301).send(); } diff --git a/tests/integration/webclient/src/main/java/io/helidon/tests/integration/webclient/GreetService.java b/tests/integration/webclient/src/main/java/io/helidon/tests/integration/webclient/GreetService.java index 028fcfeecd0..0a037cac585 100644 --- a/tests/integration/webclient/src/main/java/io/helidon/tests/integration/webclient/GreetService.java +++ b/tests/integration/webclient/src/main/java/io/helidon/tests/integration/webclient/GreetService.java @@ -104,8 +104,8 @@ public void routing(HttpRules rules) { private void contentLength(ServerRequest serverRequest, ServerResponse serverResponse) { serverRequest.headers().contentLength() - .ifPresentOrElse(value -> serverResponse.send(Http.Header.CONTENT_LENGTH + " is " + value), - () -> serverResponse.send("No " + Http.Header.CONTENT_LENGTH + " has been set")); + .ifPresentOrElse(value -> serverResponse.send(Http.HeaderNames.CONTENT_LENGTH + " is " + value), + () -> serverResponse.send("No " + Http.HeaderNames.CONTENT_LENGTH + " has been set")); } private void basicAuthOutbound(ServerRequest request, ServerResponse response) { @@ -167,17 +167,17 @@ private void getDefaultMessageHandler(ServerRequest request, * @param response the server response */ private void redirect(ServerRequest request, ServerResponse response) { - response.headers().add(Http.Header.LOCATION, "http://localhost:" + request.requestedUri().port() + "/greet"); + response.headers().add(Http.HeaderNames.LOCATION, "http://localhost:" + request.requestedUri().port() + "/greet"); response.status(Http.Status.MOVED_PERMANENTLY_301).send(); } private void redirectPath(ServerRequest request, ServerResponse response) { - response.headers().add(Http.Header.LOCATION, "/greet"); + response.headers().add(Http.HeaderNames.LOCATION, "/greet"); response.status(Http.Status.MOVED_PERMANENTLY_301).send(); } private void redirectInfinite(ServerRequest request, ServerResponse response) { - response.headers().add(Http.Header.LOCATION, "http://localhost:" + request.requestedUri().port() + "/greet/redirect/infinite"); + response.headers().add(Http.HeaderNames.LOCATION, "http://localhost:" + request.requestedUri().port() + "/greet/redirect/infinite"); response.status(Http.Status.MOVED_PERMANENTLY_301).send(); } diff --git a/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/FormTest.java b/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/FormTest.java index 8f462934e4f..8aaa9c5115b 100644 --- a/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/FormTest.java +++ b/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/FormTest.java @@ -26,7 +26,6 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import static io.helidon.common.http.HttpMediaType.TEXT_PLAIN; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; @@ -66,7 +65,7 @@ public void testHelloWorld() { @Test public void testSpecificContentType() { try (Http1ClientResponse res = client.post("/form") - .contentType(TEXT_PLAIN) + .contentType(MediaTypes.TEXT_PLAIN) .submit(TEST_FORM)) { assertThat(res.as(String.class), is("Hi David Tester")); } diff --git a/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/HeaderTest.java b/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/HeaderTest.java index 8a5e2bad4b4..e91b14f70e9 100644 --- a/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/HeaderTest.java +++ b/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/HeaderTest.java @@ -49,7 +49,7 @@ public void userAgentNotOverridden() { Http1Client webClient = createNewClient(new HeaderTestService(TEST_USER)); webClient.get() - .header(Http.Header.USER_AGENT, TEST_USER) + .header(Http.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.Header.CONTENT_LENGTH + " is 0")); + assertThat(contentLength, is(Http.HeaderNames.CONTENT_LENGTH + " is 0")); } try (Http1ClientResponse res = webClient.post("contentLength").request()) { String contentLength = res.as(String.class); - assertThat(contentLength, is(Http.Header.CONTENT_LENGTH + " is 0")); + assertThat(contentLength, is(Http.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.Header.CONTENT_LENGTH + " is " + sampleSmallEntity.length())); + assertThat(contentLength, is(Http.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.Header.CONTENT_LENGTH + " is " + sampleSmallEntity.length())); + assertThat(contentLength, is(Http.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.Header.USER_AGENT, List::of); + List userAgent = request.headers().all(Http.HeaderNames.USER_AGENT, List::of); assertThat(userAgent, hasSize(1)); assertThat(userAgent, contains(user)); return chain.proceed(request); diff --git a/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/MutualTlsTest.java b/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/MutualTlsTest.java index 6716297d9d3..a71521ed731 100644 --- a/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/MutualTlsTest.java +++ b/tests/integration/webclient/src/test/java/io/helidon/tests/integration/webclient/MutualTlsTest.java @@ -188,7 +188,7 @@ private static void mTlsRouting(HttpRouting.Builder routing) { .orElse("Unknown CN"); // close to avoid re-using cached connections on the client side - res.header(Http.HeaderValues.CONNECTION_CLOSE); + res.header(Http.Headers.CONNECTION_CLOSE); res.send("Hello " + cn + "!"); }); } diff --git a/tests/integration/webserver/upgrade/src/test/java/io/helidon/integration/webserver/upgrade/test/CompressionTest.java b/tests/integration/webserver/upgrade/src/test/java/io/helidon/integration/webserver/upgrade/test/CompressionTest.java index 0fca34da67f..c3d5cae23e9 100644 --- a/tests/integration/webserver/upgrade/src/test/java/io/helidon/integration/webserver/upgrade/test/CompressionTest.java +++ b/tests/integration/webserver/upgrade/src/test/java/io/helidon/integration/webserver/upgrade/test/CompressionTest.java @@ -17,7 +17,7 @@ package io.helidon.integration.webserver.upgrade.test; import io.helidon.common.http.Http; -import io.helidon.common.http.Http.Header; +import io.helidon.common.http.Http.HeaderNames; import io.helidon.nima.testing.junit5.webserver.ServerTest; import io.helidon.nima.testing.junit5.webserver.SetUpRoute; import io.helidon.nima.webclient.http1.Http1Client; @@ -36,8 +36,8 @@ */ @ServerTest public class CompressionTest { - private static final Http.HeaderValue CONTENT_ENCODING_GZIP = Header.create(Header.CONTENT_ENCODING, "gzip"); - private static final Http.HeaderValue CONTENT_ENCODING_DEFLATE = Header.create(Header.CONTENT_ENCODING, "deflate"); + 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 final Http1Client webClient; @@ -56,7 +56,7 @@ public static void routing(HttpRules rules) { @Test public void testGzip() { Http1ClientRequest request = webClient.get(); - request.header(Header.create(Header.ACCEPT_ENCODING, "gzip")); + request.header(Http.Headers.create(Http.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 +69,7 @@ public void testGzip() { @Test public void testDeflateContent() { Http1ClientRequest builder = webClient.get(); - builder.header(Header.create(Header.ACCEPT_ENCODING, "deflate")); + builder.header(Http.Headers.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/tests/integration/webserver/upgrade/src/test/java/io/helidon/integration/webserver/upgrade/test/UpgradeCodecsCompositionTest.java b/tests/integration/webserver/upgrade/src/test/java/io/helidon/integration/webserver/upgrade/test/UpgradeCodecsCompositionTest.java index 70c16eeb496..4031c49f3b2 100644 --- a/tests/integration/webserver/upgrade/src/test/java/io/helidon/integration/webserver/upgrade/test/UpgradeCodecsCompositionTest.java +++ b/tests/integration/webserver/upgrade/src/test/java/io/helidon/integration/webserver/upgrade/test/UpgradeCodecsCompositionTest.java @@ -138,7 +138,7 @@ public CompletionStage onText(WebSocket webSocket, CharSequence data, boolean }) void genericHttp20(String url) throws IOException, InterruptedException { assertThat(httpClient(GET, url, HTTP_2).body(), is("HTTP Version 2.0\n")); - try (HttpClientResponse response = webClient(GET, url, Http.Version.V2_0)) { + try (HttpClientResponse response = doRequest(webClient2, GET, url)) { assertThat(response.entity().as(String.class), is("HTTP Version 2.0\n")); } } @@ -150,7 +150,7 @@ void genericHttp20(String url) throws IOException, InterruptedException { }) void genericHttp11(String url) throws IOException, InterruptedException { assertThat(httpClient(GET, url, HTTP_1_1).body(), is("HTTP Version 1.1\n")); - try (HttpClientResponse response = webClient(GET, url, Http.Version.V1_1)) { + try (HttpClientResponse response = doRequest(webClient1, GET, url)) { assertThat(response.entity().as(String.class), is("HTTP Version 1.1\n")); } } @@ -162,7 +162,7 @@ void genericHttp11(String url) throws IOException, InterruptedException { }) void versionSpecificHttp11(String url) throws IOException, InterruptedException { assertThat(httpClient(GET, url, HTTP_1_1).body(), is("HTTP/1.1 route\n")); - try (HttpClientResponse response = webClient(GET, url, Http.Version.V1_1)) { + try (HttpClientResponse response = doRequest(webClient1, GET, url)) { assertThat(response.entity().as(String.class), is("HTTP/1.1 route\n")); } } @@ -174,7 +174,7 @@ void versionSpecificHttp11(String url) throws IOException, InterruptedException }) void versionSpecificHttp20(String url) throws IOException, InterruptedException { assertThat(httpClient(GET, url, HTTP_2).body(), is("HTTP/2.0 route\n")); - try (HttpClientResponse response = webClient(GET, url, Http.Version.V2_0)) { + try (HttpClientResponse response = doRequest(webClient2, GET, url)) { assertThat(response.entity().as(String.class), is("HTTP/2.0 route\n")); } } @@ -186,7 +186,7 @@ void versionSpecificHttp20(String url) throws IOException, InterruptedException }) void versionSpecificHttp11Negative(String url) throws IOException, InterruptedException { assertThat(httpClient(GET, url, HTTP_2).statusCode(), is(404)); - try (HttpClientResponse response = webClient(GET, url, Http.Version.V2_0)) { + try (HttpClientResponse response = doRequest(webClient2, GET, url)) { assertThat(response.status().code(), is(404)); } } @@ -198,7 +198,7 @@ void versionSpecificHttp11Negative(String url) throws IOException, InterruptedEx }) void versionSpecificHttp20Negative(String url) throws IOException, InterruptedException { assertThat(httpClient(GET, url, HTTP_1_1).statusCode(), is(404)); - try (HttpClientResponse response = webClient(GET, url, Http.Version.V1_1)) { + try (HttpClientResponse response = doRequest(webClient1, GET, url)) { assertThat(response.status().code(), is(404)); } } @@ -221,8 +221,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(), is(expectedResponse)); - try (HttpClientResponse response = webClient(Http.Method.create(method), url, Http.Version.create(version))) { + assertThat(httpClient(Http.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)) { assertThat(response.entity().as(String.class), is(expectedResponse)); } } @@ -261,19 +263,16 @@ private HttpResponse httpClient(Http.Method method, body = HttpRequest.BodyPublishers.ofString("test"); } return httpClient.send(HttpRequest.newBuilder() - .version(version) - .uri(resolveUri(url)) - .method(method.text(), body) - .build(), HttpResponse.BodyHandlers.ofString()); + .version(version) + .uri(resolveUri(url)) + .method(method.text(), body) + .build(), HttpResponse.BodyHandlers.ofString()); } - private HttpClientResponse webClient(Http.Method method, String url, Http.Version version) { - if (version == Http.Version.V2_0) { - return webClient2.method(method) - .uri(resolveUri(url)) - .request(); - } - return webClient1.method(method) + private HttpClientResponse doRequest(io.helidon.nima.webclient.api.HttpClient client, + Http.Method method, + String url) { + return client.method(method) .uri(resolveUri(url)) .request(); }