Use URI#create instead of URI constructor where feasible in spring-web

This commit is contained in:
Sam Brannen
2022-12-09 13:26:01 -05:00
parent a1a140f7d5
commit 1b57f2bda5
31 changed files with 163 additions and 178 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -109,8 +109,8 @@ public class HttpEntityTests {
headers.setContentType(MediaType.TEXT_PLAIN);
String body = "foo";
HttpEntity<String> httpEntity = new HttpEntity<>(body, headers);
RequestEntity<String> requestEntity = new RequestEntity<>(body, headers, HttpMethod.GET, new URI("/"));
RequestEntity<String> requestEntity2 = new RequestEntity<>(body, headers, HttpMethod.GET, new URI("/"));
RequestEntity<String> requestEntity = new RequestEntity<>(body, headers, HttpMethod.GET, URI.create("/"));
RequestEntity<String> requestEntity2 = new RequestEntity<>(body, headers, HttpMethod.GET, URI.create("/"));
assertThat(requestEntity.getBody()).isEqualTo(body);
assertThat(requestEntity.getHeaders().getContentType()).isEqualTo(MediaType.TEXT_PLAIN);

View File

@@ -153,7 +153,7 @@ public class HttpHeadersTests {
@Test
void location() throws URISyntaxException {
URI location = new URI("https://www.example.com/hotels");
URI location = URI.create("https://www.example.com/hotels");
headers.setLocation(location);
assertThat(headers.getLocation()).as("Invalid Location header").isEqualTo(location);
assertThat(headers.getFirst("Location")).as("Invalid Location header").isEqualTo("https://www.example.com/hotels");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* 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,6 @@
package org.springframework.http;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
@@ -41,10 +40,10 @@ import static org.assertj.core.api.Assertions.assertThat;
class RequestEntityTests {
@Test
void normal() throws URISyntaxException {
void normal() {
String headerName = "My-Custom-Header";
String headerValue = "HeaderValue";
URI url = new URI("https://example.com");
URI url = URI.create("https://example.com");
Integer entity = 42;
RequestEntity<Object> requestEntity =
@@ -59,14 +58,14 @@ class RequestEntityTests {
}
@Test
void uriVariablesExpansion() throws URISyntaxException {
void uriVariablesExpansion() {
URI uri = UriComponentsBuilder.fromUriString("https://example.com/{foo}").buildAndExpand("bar").toUri();
RequestEntity.get(uri).accept(MediaType.TEXT_PLAIN).build();
String url = "https://www.{host}.com/{path}";
String host = "example";
String path = "foo/bar";
URI expected = new URI("https://www.example.com/foo/bar");
URI expected = URI.create("https://www.example.com/foo/bar");
uri = UriComponentsBuilder.fromUriString(url).buildAndExpand(host, path).toUri();
RequestEntity<?> entity = RequestEntity.get(uri).build();
@@ -107,14 +106,14 @@ class RequestEntityTests {
}
@Test
void headers() throws URISyntaxException {
void headers() {
MediaType accept = MediaType.TEXT_PLAIN;
long ifModifiedSince = 12345L;
String ifNoneMatch = "\"foo\"";
long contentLength = 67890;
MediaType contentType = MediaType.TEXT_PLAIN;
RequestEntity<Void> responseEntity = RequestEntity.post(new URI("https://example.com")).
RequestEntity<Void> responseEntity = RequestEntity.post(URI.create("https://example.com")).
accept(accept).
acceptCharset(StandardCharsets.UTF_8).
ifModifiedSince(ifModifiedSince).
@@ -126,7 +125,7 @@ class RequestEntityTests {
assertThat(responseEntity).isNotNull();
assertThat(responseEntity.getMethod()).isEqualTo(HttpMethod.POST);
assertThat(responseEntity.getUrl()).isEqualTo(new URI("https://example.com"));
assertThat(responseEntity.getUrl()).isEqualTo(URI.create("https://example.com"));
HttpHeaders responseHeaders = responseEntity.getHeaders();
assertThat(responseHeaders.getFirst(HttpHeaders.ACCEPT)).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
@@ -140,8 +139,8 @@ class RequestEntityTests {
}
@Test
void methods() throws URISyntaxException {
URI url = new URI("https://example.com");
void methods() {
URI url = URI.create("https://example.com");
RequestEntity<?> entity = RequestEntity.get(url).build();
assertThat(entity.getMethod()).isEqualTo(HttpMethod.GET);
@@ -167,8 +166,8 @@ class RequestEntityTests {
}
@Test // SPR-13154
void types() throws URISyntaxException {
URI url = new URI("https://example.com");
void types() {
URI url = URI.create("https://example.com");
List<String> body = Arrays.asList("foo", "bar");
ParameterizedTypeReference<?> typeReference = new ParameterizedTypeReference<List<String>>() {};

View File

@@ -17,7 +17,6 @@
package org.springframework.http;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
@@ -92,8 +91,8 @@ class ResponseEntityTests {
}
@Test
void createdLocation() throws URISyntaxException {
URI location = new URI("location");
void createdLocation() {
URI location = URI.create("location");
ResponseEntity<Void> responseEntity = ResponseEntity.created(location).build();
assertThat(responseEntity).isNotNull();
@@ -106,7 +105,7 @@ class ResponseEntityTests {
}
@Test
void acceptedNoBody() throws URISyntaxException {
void acceptedNoBody() {
ResponseEntity<Void> responseEntity = ResponseEntity.accepted().build();
assertThat(responseEntity).isNotNull();
@@ -115,7 +114,7 @@ class ResponseEntityTests {
}
@Test // SPR-14939
void acceptedNoBodyWithAlternativeBodyType() throws URISyntaxException {
void acceptedNoBodyWithAlternativeBodyType() {
ResponseEntity<String> responseEntity = ResponseEntity.accepted().build();
assertThat(responseEntity).isNotNull();
@@ -124,7 +123,7 @@ class ResponseEntityTests {
}
@Test
void noContent() throws URISyntaxException {
void noContent() {
ResponseEntity<Void> responseEntity = ResponseEntity.noContent().build();
assertThat(responseEntity).isNotNull();
@@ -133,7 +132,7 @@ class ResponseEntityTests {
}
@Test
void badRequest() throws URISyntaxException {
void badRequest() {
ResponseEntity<Void> responseEntity = ResponseEntity.badRequest().build();
assertThat(responseEntity).isNotNull();
@@ -142,7 +141,7 @@ class ResponseEntityTests {
}
@Test
void notFound() throws URISyntaxException {
void notFound() {
ResponseEntity<Void> responseEntity = ResponseEntity.notFound().build();
assertThat(responseEntity).isNotNull();
@@ -151,7 +150,7 @@ class ResponseEntityTests {
}
@Test
void unprocessableEntity() throws URISyntaxException {
void unprocessableEntity() {
ResponseEntity<String> responseEntity = ResponseEntity.unprocessableEntity().body("error");
assertThat(responseEntity).isNotNull();
@@ -160,7 +159,7 @@ class ResponseEntityTests {
}
@Test
void internalServerError() throws URISyntaxException {
void internalServerError() {
ResponseEntity<String> responseEntity = ResponseEntity.internalServerError().body("error");
assertThat(responseEntity).isNotNull();
@@ -169,8 +168,8 @@ class ResponseEntityTests {
}
@Test
void headers() throws URISyntaxException {
URI location = new URI("location");
void headers() {
URI location = URI.create("location");
long contentLength = 67890;
MediaType contentType = MediaType.TEXT_PLAIN;
@@ -197,7 +196,7 @@ class ResponseEntityTests {
}
@Test
void Etagheader() throws URISyntaxException {
void Etagheader() {
ResponseEntity<Void> responseEntity = ResponseEntity.ok().eTag("\"foo\"").build();
assertThat(responseEntity.getHeaders().getETag()).isEqualTo("\"foo\"");

View File

@@ -66,7 +66,7 @@ abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebServerTest
@Test
void status() throws Exception {
URI uri = new URI(baseUrl + "/status/notfound");
URI uri = URI.create(baseUrl + "/status/notfound");
ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET);
assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.GET);
assertThat(request.getURI()).as("Invalid HTTP URI").isEqualTo(uri);
@@ -78,7 +78,7 @@ abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebServerTest
@Test
void echo() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT);
ClientHttpRequest request = factory.createRequest(URI.create(baseUrl + "/echo"), HttpMethod.PUT);
assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.PUT);
String headerName = "MyHeader";
@@ -107,7 +107,7 @@ abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebServerTest
@Test
void multipleWrites() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST);
ClientHttpRequest request = factory.createRequest(URI.create(baseUrl + "/echo"), HttpMethod.POST);
final byte[] body = "Hello World".getBytes(StandardCharsets.UTF_8);
if (request instanceof StreamingHttpOutputMessage streamingRequest) {
@@ -128,7 +128,7 @@ abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebServerTest
@Test
void headersAfterExecute() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/status/ok"), HttpMethod.POST);
ClientHttpRequest request = factory.createRequest(URI.create(baseUrl + "/status/ok"), HttpMethod.POST);
request.getHeaders().add("MyHeader", "value");
byte[] body = "Hello World".getBytes(StandardCharsets.UTF_8);
@@ -152,7 +152,7 @@ abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebServerTest
}
protected void assertHttpMethod(String path, HttpMethod method) throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/" + path), method);
ClientHttpRequest request = factory.createRequest(URI.create(baseUrl + "/methods/" + path), method);
if (method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH) {
// requires a body
try {
@@ -171,7 +171,7 @@ abstract class AbstractHttpRequestFactoryTests extends AbstractMockWebServerTest
@Test
void queryParameters() throws Exception {
URI uri = new URI(baseUrl + "/params?param1=value&param2=value1&param2=value2");
URI uri = URI.create(baseUrl + "/params?param1=value&param2=value1&param2=value2");
ClientHttpRequest request = factory.createRequest(uri, HttpMethod.GET);
try (ClientHttpResponse response = request.execute()) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,7 +36,7 @@ class BufferingClientHttpRequestFactoryTests extends AbstractHttpRequestFactoryT
@Test
void repeatableRead() throws Exception {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT);
ClientHttpRequest request = factory.createRequest(URI.create(baseUrl + "/echo"), HttpMethod.PUT);
assertThat(request.getMethod()).as("Invalid HTTP method").isEqualTo(HttpMethod.PUT);
String headerName = "MyHeader";
String headerValue1 = "value1";

View File

@@ -60,7 +60,7 @@ class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpRequestFac
hrf.setConnectTimeout(1234);
hrf.setConnectionRequestTimeout(4321);
URI uri = new URI(baseUrl + "/status/ok");
URI uri = URI.create(baseUrl + "/status/ok");
HttpComponentsClientHttpRequest request = (HttpComponentsClientHttpRequest) hrf.createRequest(uri, HttpMethod.GET);
Object config = request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG);
@@ -146,7 +146,7 @@ class HttpComponentsClientHttpRequestFactoryTests extends AbstractHttpRequestFac
}
private RequestConfig retrieveRequestConfig(HttpComponentsClientHttpRequestFactory factory) throws Exception {
URI uri = new URI(baseUrl + "/status/ok");
URI uri = URI.create(baseUrl + "/status/ok");
HttpComponentsClientHttpRequest request = (HttpComponentsClientHttpRequest)
factory.createRequest(uri, HttpMethod.GET);
return (RequestConfig) request.getHttpContext().getAttribute(HttpClientContext.REQUEST_CONFIG);

View File

@@ -61,7 +61,7 @@ class InterceptingClientHttpRequestFactoryTests {
interceptors.add(new NoOpInterceptor());
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, interceptors);
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
ClientHttpRequest request = requestFactory.createRequest(URI.create("https://example.com"), HttpMethod.GET);
ClientHttpResponse response = request.execute();
assertThat(((NoOpInterceptor) interceptors.get(0)).invoked).isTrue();
@@ -79,7 +79,7 @@ class InterceptingClientHttpRequestFactoryTests {
interceptors.add(new NoOpInterceptor());
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, interceptors);
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
ClientHttpRequest request = requestFactory.createRequest(URI.create("https://example.com"), HttpMethod.GET);
ClientHttpResponse response = request.execute();
assertThat(((NoOpInterceptor) interceptors.get(1)).invoked).isFalse();
@@ -113,13 +113,13 @@ class InterceptingClientHttpRequestFactoryTests {
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
ClientHttpRequest request = requestFactory.createRequest(URI.create("https://example.com"), HttpMethod.GET);
request.execute();
}
@Test
void changeURI() throws Exception {
final URI changedUri = new URI("https://example.com/2");
final URI changedUri = URI.create("https://example.com/2");
ClientHttpRequestInterceptor interceptor = (request, body, execution) -> execution.execute(new HttpRequestWrapper(request) {
@Override
@@ -139,7 +139,7 @@ class InterceptingClientHttpRequestFactoryTests {
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
ClientHttpRequest request = requestFactory.createRequest(URI.create("https://example.com"), HttpMethod.GET);
request.execute();
}
@@ -165,7 +165,7 @@ class InterceptingClientHttpRequestFactoryTests {
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
ClientHttpRequest request = requestFactory.createRequest(URI.create("https://example.com"), HttpMethod.GET);
request.execute();
}
@@ -177,7 +177,7 @@ class InterceptingClientHttpRequestFactoryTests {
requestFactory = new InterceptingClientHttpRequestFactory(requestFactoryMock, Collections.singletonList(interceptor));
ClientHttpRequest request = requestFactory.createRequest(new URI("https://example.com"), HttpMethod.GET);
ClientHttpRequest request = requestFactory.createRequest(URI.create("https://example.com"), HttpMethod.GET);
request.execute();
assertThat(Arrays.equals(changedBody, requestMock.getBodyAsBytes())).isTrue();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,7 +55,7 @@ public class StreamingSimpleClientHttpRequestFactoryTests extends AbstractHttpRe
ClientHttpResponse response = null;
try {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.GET);
ClientHttpRequest request = factory.createRequest(URI.create(baseUrl + "/echo"), HttpMethod.GET);
response = request.execute();
assertThat(response.getStatusCode()).as("Invalid response status").isEqualTo(HttpStatus.OK);
HttpHeaders responseHeaders = response.getHeaders();
@@ -74,7 +74,7 @@ public class StreamingSimpleClientHttpRequestFactoryTests extends AbstractHttpRe
Random rnd = new Random();
ClientHttpResponse response = null;
try {
ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/methods/post"), HttpMethod.POST);
ClientHttpRequest request = factory.createRequest(URI.create(baseUrl + "/methods/post"), HttpMethod.POST);
final int BUF_SIZE = 4096;
final int ITERATIONS = Integer.MAX_VALUE / BUF_SIZE;
// final int contentLength = ITERATIONS * BUF_SIZE;

View File

@@ -59,7 +59,7 @@ public class ServletServerHttpRequestTests {
@Test
void getUriForSimplePath() throws URISyntaxException {
URI uri = new URI("https://example.com/path");
URI uri = URI.create("https://example.com/path");
mockRequest.setScheme(uri.getScheme());
mockRequest.setServerName(uri.getHost());
mockRequest.setServerPort(uri.getPort());
@@ -70,7 +70,7 @@ public class ServletServerHttpRequestTests {
@Test
void getUriWithQueryString() throws URISyntaxException {
URI uri = new URI("https://example.com/path?query");
URI uri = URI.create("https://example.com/path?query");
mockRequest.setScheme(uri.getScheme());
mockRequest.setServerName(uri.getHost());
mockRequest.setServerPort(uri.getPort());
@@ -86,7 +86,7 @@ public class ServletServerHttpRequestTests {
mockRequest.setServerName("example.com");
mockRequest.setRequestURI("/path");
mockRequest.setQueryString("query=foo");
assertThat(request.getURI()).isEqualTo(new URI("https://example.com/path?query=foo"));
assertThat(request.getURI()).isEqualTo(URI.create("https://example.com/path?query=foo"));
}
@Test // SPR-16414
@@ -96,12 +96,12 @@ public class ServletServerHttpRequestTests {
mockRequest.setServerName("example.com");
mockRequest.setRequestURI("/path");
mockRequest.setQueryString("query=foo%%x");
assertThat(request.getURI()).isEqualTo(new URI("https://example.com/path"));
assertThat(request.getURI()).isEqualTo(URI.create("https://example.com/path"));
}
@Test // SPR-13876
void getUriWithEncoding() throws URISyntaxException {
URI uri = new URI("https://example.com/%E4%B8%AD%E6%96%87" +
URI uri = URI.create("https://example.com/%E4%B8%AD%E6%96%87" +
"?redirect=https%3A%2F%2Fgithub.com%2Fspring-projects%2Fspring-framework");
mockRequest.setScheme(uri.getScheme());
mockRequest.setServerName(uri.getHost());

View File

@@ -51,7 +51,7 @@ class AsyncIntegrationTests extends AbstractHttpHandlerIntegrationTests {
void basicTest(HttpServer httpServer) throws Exception {
startServer(httpServer);
URI url = new URI("http://localhost:" + port);
URI url = URI.create("http://localhost:" + port);
@SuppressWarnings("resource")
ResponseEntity<String> response = new RestTemplate().exchange(RequestEntity.get(url).build(), String.class);

View File

@@ -51,7 +51,7 @@ public class CookieIntegrationTests extends AbstractHttpHandlerIntegrationTests
public void basicTest(HttpServer httpServer) throws Exception {
startServer(httpServer);
URI url = new URI("http://localhost:" + port);
URI url = URI.create("http://localhost:" + port);
String header = "SID=31d4d96e407aad42; lang=en-US";
@SuppressWarnings("resource")
ResponseEntity<Void> response = new RestTemplate().exchange(

View File

@@ -53,7 +53,7 @@ public class EchoHandlerIntegrationTests extends AbstractHttpHandlerIntegrationT
RestTemplate restTemplate = new RestTemplate();
byte[] body = randomBytes();
RequestEntity<byte[]> request = RequestEntity.post(new URI("http://localhost:" + port)).body(body);
RequestEntity<byte[]> request = RequestEntity.post(URI.create("http://localhost:" + port)).body(body);
ResponseEntity<byte[]> response = restTemplate.exchange(request, byte[].class);
assertThat(response.getBody()).isEqualTo(body);

View File

@@ -53,7 +53,7 @@ class ErrorHandlerIntegrationTests extends AbstractHttpHandlerIntegrationTests {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(NO_OP_ERROR_HANDLER);
URI url = new URI("http://localhost:" + port + "/response-body-error");
URI url = URI.create("http://localhost:" + port + "/response-body-error");
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@@ -67,7 +67,7 @@ class ErrorHandlerIntegrationTests extends AbstractHttpHandlerIntegrationTests {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(NO_OP_ERROR_HANDLER);
URI url = new URI("http://localhost:" + port + "/handling-error");
URI url = URI.create("http://localhost:" + port + "/handling-error");
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
@@ -81,7 +81,7 @@ class ErrorHandlerIntegrationTests extends AbstractHttpHandlerIntegrationTests {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(NO_OP_ERROR_HANDLER);
URI url = new URI("http://localhost:" + port + "//");
URI url = URI.create("http://localhost:" + port + "//");
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
// Jetty 10+ rejects empty path segments, see https://github.com/eclipse/jetty.project/issues/6302,

View File

@@ -61,7 +61,7 @@ class MultipartHttpHandlerIntegrationTests extends AbstractHttpHandlerIntegratio
@SuppressWarnings("resource")
RestTemplate restTemplate = new RestTemplate();
RequestEntity<MultiValueMap<String, Object>> request = RequestEntity
.post(new URI("http://localhost:" + port + "/form-parts"))
.post(URI.create("http://localhost:" + port + "/form-parts"))
.contentType(MediaType.MULTIPART_FORM_DATA)
.body(generateBody());
ResponseEntity<Void> response = restTemplate.exchange(request, Void.class);

View File

@@ -63,7 +63,7 @@ class RandomHandlerIntegrationTests extends AbstractHttpHandlerIntegrationTests
RestTemplate restTemplate = new RestTemplate();
byte[] body = randomBytes();
RequestEntity<byte[]> request = RequestEntity.post(new URI("http://localhost:" + port)).body(body);
RequestEntity<byte[]> request = RequestEntity.post(URI.create("http://localhost:" + port)).body(body);
ResponseEntity<byte[]> response = restTemplate.exchange(request, byte[].class);
assertThat(response.getBody()).isNotNull();

View File

@@ -44,7 +44,7 @@ class ServerHttpRequestIntegrationTests extends AbstractHttpHandlerIntegrationTe
void checkUri(HttpServer httpServer) throws Exception {
startServer(httpServer);
URI url = new URI("http://localhost:" + port + "/foo?param=bar");
URI url = URI.create("http://localhost:" + port + "/foo?param=bar");
RequestEntity<Void> request = RequestEntity.post(url).build();
@SuppressWarnings("resource")
ResponseEntity<Void> response = new RestTemplate().exchange(request, Void.class);

View File

@@ -86,7 +86,7 @@ class ServerHttpsRequestIntegrationTests {
@Test
void checkUri() throws Exception {
URI url = new URI("https://localhost:" + port + "/foo?param=bar");
URI url = URI.create("https://localhost:" + port + "/foo?param=bar");
RequestEntity<Void> request = RequestEntity.post(url).build();
ResponseEntity<Void> response = this.restTemplate.exchange(request, Void.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);

View File

@@ -58,9 +58,8 @@ class WriteOnlyHandlerIntegrationTests extends AbstractHttpHandlerIntegrationTes
RestTemplate restTemplate = new RestTemplate();
this.body = randomBytes();
RequestEntity<byte[]> request = RequestEntity.post(
new URI("http://localhost:" + port)).body(
"".getBytes(StandardCharsets.UTF_8));
RequestEntity<byte[]> request = RequestEntity.post(URI.create("http://localhost:" + port))
.body("".getBytes(StandardCharsets.UTF_8));
ResponseEntity<byte[]> response = restTemplate.exchange(request, byte[].class);
assertThat(response.getBody()).isEqualTo(body);

View File

@@ -59,7 +59,7 @@ class ZeroCopyIntegrationTests extends AbstractHttpHandlerIntegrationTests {
startServer(httpServer);
URI url = new URI("http://localhost:" + port);
URI url = URI.create("http://localhost:" + port);
RequestEntity<?> request = RequestEntity.get(url).build();
@SuppressWarnings("resource")
ResponseEntity<byte[]> response = new RestTemplate().exchange(request, byte[].class);

View File

@@ -199,7 +199,7 @@ class RestTemplateIntegrationTests extends AbstractMockWebServerTests {
setUpClient(clientHttpRequestFactory);
URI location = template.postForLocation(baseUrl + "/{method}", helloWorld, "post");
assertThat(location).as("Invalid location").isEqualTo(new URI(baseUrl + "/post/1"));
assertThat(location).as("Invalid location").isEqualTo(URI.create(baseUrl + "/post/1"));
}
@ParameterizedRestTemplateTest
@@ -210,7 +210,7 @@ class RestTemplateIntegrationTests extends AbstractMockWebServerTests {
entityHeaders.setContentType(new MediaType("text", "plain", StandardCharsets.ISO_8859_1));
HttpEntity<String> entity = new HttpEntity<>(helloWorld, entityHeaders);
URI location = template.postForLocation(baseUrl + "/{method}", entity, "post");
assertThat(location).as("Invalid location").isEqualTo(new URI(baseUrl + "/post/1"));
assertThat(location).as("Invalid location").isEqualTo(URI.create(baseUrl + "/post/1"));
}
@ParameterizedRestTemplateTest
@@ -274,7 +274,7 @@ class RestTemplateIntegrationTests extends AbstractMockWebServerTests {
void optionsForAllow(ClientHttpRequestFactory clientHttpRequestFactory) throws Exception {
setUpClient(clientHttpRequestFactory);
Set<HttpMethod> allowed = template.optionsForAllow(new URI(baseUrl + "/get"));
Set<HttpMethod> allowed = template.optionsForAllow(URI.create(baseUrl + "/get"));
assertThat(allowed).as("Invalid response").isEqualTo(Set.of(HttpMethod.GET, HttpMethod.OPTIONS, HttpMethod.HEAD, HttpMethod.TRACE));
}
@@ -371,7 +371,7 @@ class RestTemplateIntegrationTests extends AbstractMockWebServerTests {
requestHeaders.setContentType(MediaType.TEXT_PLAIN);
HttpEntity<String> entity = new HttpEntity<>(helloWorld, requestHeaders);
HttpEntity<Void> result = template.exchange(baseUrl + "/{method}", POST, entity, Void.class, "post");
assertThat(result.getHeaders().getLocation()).as("Invalid location").isEqualTo(new URI(baseUrl + "/post/1"));
assertThat(result.getHeaders().getLocation()).as("Invalid location").isEqualTo(URI.create(baseUrl + "/post/1"));
assertThat(result.hasBody()).isFalse();
}
@@ -425,7 +425,7 @@ class RestTemplateIntegrationTests extends AbstractMockWebServerTests {
list.add(new Bar("bar"));
ParameterizedTypeReference<?> typeReference = new ParameterizedTypeReference<List<ParentClass>>() {};
RequestEntity<List<ParentClass>> entity = RequestEntity
.post(new URI(baseUrl + "/jsonpost"))
.post(URI.create(baseUrl + "/jsonpost"))
.contentType(new MediaType("application", "json", StandardCharsets.UTF_8))
.body(list, typeReference.getType());
String content = template.exchange(entity, String.class).getBody();

View File

@@ -122,7 +122,7 @@ class RestTemplateObservationTests {
mockSentRequest(GET, url);
mockResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR);
willThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR))
.given(errorHandler).handleError(new URI(url), GET, response);
.given(errorHandler).handleError(URI.create(url), GET, response);
assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() ->
template.execute(url, GET, null, null));
@@ -164,7 +164,7 @@ class RestTemplateObservationTests {
}
private void mockSentRequest(HttpMethod method, String uri, HttpHeaders requestHeaders) throws Exception {
given(requestFactory.createRequest(new URI(uri), method)).willReturn(request);
given(requestFactory.createRequest(URI.create(uri), method)).willReturn(request);
given(request.getHeaders()).willReturn(requestHeaders);
given(request.getMethod()).willReturn(method);
given(request.getURI()).willReturn(URI.create(uri));

View File

@@ -196,7 +196,7 @@ class RestTemplateTests {
mockSentRequest(GET, url);
mockResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR);
willThrow(new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR))
.given(errorHandler).handleError(new URI(url), GET, response);
.given(errorHandler).handleError(URI.create(url), GET, response);
assertThatExceptionOfType(HttpServerErrorException.class).isThrownBy(() ->
template.execute(url, GET, null, null));
@@ -318,7 +318,7 @@ class RestTemplateTests {
mockResponseStatus(HttpStatus.OK);
String helloWorld = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("https://example.com/hotels");
URI expected = URI.create("https://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
@@ -336,7 +336,7 @@ class RestTemplateTests {
String helloWorld = "Hello World";
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("https://example.com/hotels");
URI expected = URI.create("https://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
@@ -357,7 +357,7 @@ class RestTemplateTests {
mockTextPlainHttpMessageConverter();
mockResponseStatus(HttpStatus.OK);
HttpHeaders responseHeaders = new HttpHeaders();
URI expected = new URI("https://example.com/hotels");
URI expected = URI.create("https://example.com/hotels");
responseHeaders.setLocation(expected);
given(response.getHeaders()).willReturn(responseHeaders);
@@ -762,7 +762,7 @@ class RestTemplateTests {
}
private void mockSentRequest(HttpMethod method, String uri, HttpHeaders requestHeaders) throws Exception {
given(requestFactory.createRequest(new URI(uri), method)).willReturn(request);
given(requestFactory.createRequest(URI.create(uri), method)).willReturn(request);
given(request.getHeaders()).willReturn(requestHeaders);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ public class RequestPartServletServerHttpRequestTests {
this.mockRequest.addFile(new MockMultipartFile("part", "", "application/json", "content".getBytes("UTF-8")));
ServerHttpRequest request = new RequestPartServletServerHttpRequest(this.mockRequest, "part");
URI uri = new URI("https://example.com/path?query");
URI uri = URI.create("https://example.com/path?query");
this.mockRequest.setScheme(uri.getScheme());
this.mockRequest.setServerName(uri.getHost());
this.mockRequest.setServerPort(uri.getPort());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* 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 @@ package org.springframework.web.server.adapter;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import org.junit.jupiter.api.Test;
@@ -31,9 +30,10 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* Unit tests for {@link ForwardedHeaderTransformer}.
*
* @author Rossen Stoyanchev
*/
public class ForwardedHeaderTransformerTests {
class ForwardedHeaderTransformerTests {
private static final String BASE_URL = "https://example.com/path";
@@ -65,7 +65,7 @@ public class ForwardedHeaderTransformerTests {
headers.add("foo", "bar");
ServerHttpRequest request = this.requestMutator.apply(getRequest(headers));
assertThat(request.getURI()).isEqualTo(new URI("https://84.198.58.199/path"));
assertThat(request.getURI()).isEqualTo(URI.create("https://84.198.58.199/path"));
assertForwardedHeadersRemoved(request);
}
@@ -75,7 +75,7 @@ public class ForwardedHeaderTransformerTests {
headers.add("Forwarded", "host=84.198.58.199;proto=https");
ServerHttpRequest request = this.requestMutator.apply(getRequest(headers));
assertThat(request.getURI()).isEqualTo(new URI("https://84.198.58.199/path"));
assertThat(request.getURI()).isEqualTo(URI.create("https://84.198.58.199/path"));
assertForwardedHeadersRemoved(request);
}
@@ -85,7 +85,7 @@ public class ForwardedHeaderTransformerTests {
headers.add("X-Forwarded-Prefix", "/prefix");
ServerHttpRequest request = this.requestMutator.apply(getRequest(headers));
assertThat(request.getURI()).isEqualTo(new URI("https://example.com/prefix/path"));
assertThat(request.getURI()).isEqualTo(URI.create("https://example.com/prefix/path"));
assertThat(request.getPath().value()).isEqualTo("/prefix/path");
assertForwardedHeadersRemoved(request);
}
@@ -95,13 +95,13 @@ public class ForwardedHeaderTransformerTests {
HttpHeaders headers = new HttpHeaders();
headers.add("X-Forwarded-Prefix", "/prefix");
ServerHttpRequest request = MockServerHttpRequest
.method(HttpMethod.GET, new URI("https://example.com/a%20b?q=a%2Bb"))
.method(HttpMethod.GET, URI.create("https://example.com/a%20b?q=a%2Bb"))
.headers(headers)
.build();
request = this.requestMutator.apply(request);
assertThat(request.getURI()).isEqualTo(new URI("https://example.com/prefix/a%20b?q=a%2Bb"));
assertThat(request.getURI()).isEqualTo(URI.create("https://example.com/prefix/a%20b?q=a%2Bb"));
assertThat(request.getPath().value()).isEqualTo("/prefix/a%20b");
assertForwardedHeadersRemoved(request);
}
@@ -112,7 +112,7 @@ public class ForwardedHeaderTransformerTests {
headers.add("X-Forwarded-Prefix", "/prefix////");
ServerHttpRequest request = this.requestMutator.apply(getRequest(headers));
assertThat(request.getURI()).isEqualTo(new URI("https://example.com/prefix/path"));
assertThat(request.getURI()).isEqualTo(URI.create("https://example.com/prefix/path"));
assertThat(request.getPath().value()).isEqualTo("/prefix/path");
assertForwardedHeadersRemoved(request);
}
@@ -123,13 +123,13 @@ public class ForwardedHeaderTransformerTests {
headers.add("Forwarded", "host=84.198.58.199;proto=https");
ServerHttpRequest request = MockServerHttpRequest
.method(HttpMethod.GET, new URI("https://example.com/a%20b?q=a%2Bb"))
.method(HttpMethod.GET, URI.create("https://example.com/a%20b?q=a%2Bb"))
.headers(headers)
.build();
request = this.requestMutator.apply(request);
assertThat(request.getURI()).isEqualTo(new URI("https://84.198.58.199/a%20b?q=a%2Bb"));
assertThat(request.getURI()).isEqualTo(URI.create("https://84.198.58.199/a%20b?q=a%2Bb"));
assertForwardedHeadersRemoved(request);
}
@@ -139,7 +139,7 @@ public class ForwardedHeaderTransformerTests {
headers.add("X-Forwarded-Prefix", "/first,/second");
ServerHttpRequest request = this.requestMutator.apply(getRequest(headers));
assertThat(request.getURI()).isEqualTo(new URI("https://example.com/first/second/path"));
assertThat(request.getURI()).isEqualTo(URI.create("https://example.com/first/second/path"));
assertThat(request.getPath().value()).isEqualTo("/first/second/path");
assertForwardedHeadersRemoved(request);
}
@@ -150,20 +150,20 @@ public class ForwardedHeaderTransformerTests {
headers.add("X-Forwarded-Prefix", "/first/,/second//");
ServerHttpRequest request = this.requestMutator.apply(getRequest(headers));
assertThat(request.getURI()).isEqualTo(new URI("https://example.com/first/second/path"));
assertThat(request.getURI()).isEqualTo(URI.create("https://example.com/first/second/path"));
assertThat(request.getPath().value()).isEqualTo("/first/second/path");
assertForwardedHeadersRemoved(request);
}
@Test
public void forwardedForNotPresent() throws URISyntaxException {
void forwardedForNotPresent() {
HttpHeaders headers = new HttpHeaders();
headers.add("Forwarded", "host=84.198.58.199;proto=https");
InetSocketAddress remoteAddress = new InetSocketAddress("example.client", 47011);
ServerHttpRequest request = MockServerHttpRequest
.method(HttpMethod.GET, new URI("https://example.com/a%20b?q=a%2Bb"))
.method(HttpMethod.GET, URI.create("https://example.com/a%20b?q=a%2Bb"))
.remoteAddress(remoteAddress)
.headers(headers)
.build();
@@ -173,14 +173,14 @@ public class ForwardedHeaderTransformerTests {
}
@Test
public void forwardedFor() throws URISyntaxException {
void forwardedFor() {
HttpHeaders headers = new HttpHeaders();
headers.add("Forwarded", "for=\"203.0.113.195:4711\";host=84.198.58.199;proto=https");
InetSocketAddress remoteAddress = new InetSocketAddress("example.client", 47011);
ServerHttpRequest request = MockServerHttpRequest
.method(HttpMethod.GET, new URI("https://example.com/a%20b?q=a%2Bb"))
.method(HttpMethod.GET, URI.create("https://example.com/a%20b?q=a%2Bb"))
.remoteAddress(remoteAddress)
.headers(headers)
.build();
@@ -192,12 +192,12 @@ public class ForwardedHeaderTransformerTests {
}
@Test
public void xForwardedFor() throws URISyntaxException {
void xForwardedFor() {
HttpHeaders headers = new HttpHeaders();
headers.add("x-forwarded-for", "203.0.113.195, 70.41.3.18, 150.172.238.178");
ServerHttpRequest request = MockServerHttpRequest
.method(HttpMethod.GET, new URI("https://example.com/a%20b?q=a%2Bb"))
.method(HttpMethod.GET, URI.create("https://example.com/a%20b?q=a%2Bb"))
.headers(headers)
.build();

View File

@@ -17,7 +17,6 @@
package org.springframework.web.server.session;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.Clock;
import java.time.Duration;
import java.util.List;
@@ -85,7 +84,6 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe
public void expiredSessionIsRecreated(HttpServer httpServer) throws Exception {
startServer(httpServer);
// First request: no session yet, new session created
RequestEntity<Void> request = RequestEntity.get(createUri()).build();
ResponseEntity<Void> response = this.restTemplate.exchange(request, Void.class);
@@ -123,7 +121,6 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe
public void expiredSessionEnds(HttpServer httpServer) throws Exception {
startServer(httpServer);
// First request: no session yet, new session created
RequestEntity<Void> request = RequestEntity.get(createUri()).build();
ResponseEntity<Void> response = this.restTemplate.exchange(request, Void.class);
@@ -137,7 +134,7 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe
store.setClock(Clock.offset(store.getClock(), Duration.ofMinutes(31)));
// Second request: session expires
URI uri = new URI("http://localhost:" + this.port + "/?expire");
URI uri = URI.create("http://localhost:" + this.port + "/?expire");
request = RequestEntity.get(uri).header("Cookie", "SESSION=" + id).build();
response = this.restTemplate.exchange(request, Void.class);
@@ -151,7 +148,6 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe
public void changeSessionId(HttpServer httpServer) throws Exception {
startServer(httpServer);
// First request: no session yet, new session created
RequestEntity<Void> request = RequestEntity.get(createUri()).build();
ResponseEntity<Void> response = this.restTemplate.exchange(request, Void.class);
@@ -162,7 +158,7 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe
assertThat(this.handler.getSessionRequestCount()).isEqualTo(1);
// Second request: session id changes
URI uri = new URI("http://localhost:" + this.port + "/?changeId");
URI uri = URI.create("http://localhost:" + this.port + "/?changeId");
request = RequestEntity.get(uri).header("Cookie", "SESSION=" + oldId).build();
response = this.restTemplate.exchange(request, Void.class);
@@ -186,7 +182,7 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe
assertThat(id).isNotNull();
// Second request: invalidates session
URI uri = new URI("http://localhost:" + this.port + "/?invalidate");
URI uri = URI.create("http://localhost:" + this.port + "/?invalidate");
request = RequestEntity.get(uri).header("Cookie", "SESSION=" + id).build();
response = this.restTemplate.exchange(request, Void.class);
@@ -209,8 +205,8 @@ public class WebSessionIntegrationTests extends AbstractHttpHandlerIntegrationTe
return null;
}
private URI createUri() throws URISyntaxException {
return new URI("http://localhost:" + this.port + "/");
private URI createUri() {
return URI.create("http://localhost:" + this.port + "/");
}

View File

@@ -17,7 +17,6 @@
package org.springframework.web.util;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@@ -78,7 +77,7 @@ class UriComponentsBuilderTests {
}
@Test
void plain() throws URISyntaxException {
void plain() {
UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
UriComponents result = builder.scheme("https").host("example.com")
.path("foo").queryParam("bar").fragment("baz").build();
@@ -89,12 +88,12 @@ class UriComponentsBuilderTests {
assertThat(result.getQuery()).isEqualTo("bar");
assertThat(result.getFragment()).isEqualTo("baz");
URI expected = new URI("https://example.com/foo?bar#baz");
URI expected = URI.create("https://example.com/foo?bar#baz");
assertThat(result.toUri()).as("Invalid result URI").isEqualTo(expected);
}
@Test
void multipleFromSameBuilder() throws URISyntaxException {
void multipleFromSameBuilder() {
UriComponentsBuilder builder = UriComponentsBuilder.newInstance()
.scheme("https").host("example.com").pathSegment("foo");
UriComponents result1 = builder.build();
@@ -104,7 +103,7 @@ class UriComponentsBuilderTests {
assertThat(result1.getScheme()).isEqualTo("https");
assertThat(result1.getHost()).isEqualTo("example.com");
assertThat(result1.getPath()).isEqualTo("/foo");
URI expected = new URI("https://example.com/foo");
URI expected = URI.create("https://example.com/foo");
assertThat(result1.toUri()).as("Invalid result URI").isEqualTo(expected);
assertThat(result2.getScheme()).isEqualTo("https");
@@ -112,12 +111,12 @@ class UriComponentsBuilderTests {
assertThat(result2.getPath()).isEqualTo("/foo/foo2");
assertThat(result2.getQuery()).isEqualTo("bar");
assertThat(result2.getFragment()).isEqualTo("baz");
expected = new URI("https://example.com/foo/foo2?bar#baz");
expected = URI.create("https://example.com/foo/foo2?bar#baz");
assertThat(result2.toUri()).as("Invalid result URI").isEqualTo(expected);
}
@Test
void fromPath() throws URISyntaxException {
void fromPath() {
UriComponents result = UriComponentsBuilder.fromPath("foo").queryParam("bar").fragment("baz").build();
assertThat(result.getPath()).isEqualTo("foo");
@@ -125,19 +124,19 @@ class UriComponentsBuilderTests {
assertThat(result.getFragment()).isEqualTo("baz");
assertThat(result.toUriString()).as("Invalid result URI String").isEqualTo("foo?bar#baz");
URI expected = new URI("foo?bar#baz");
URI expected = URI.create("foo?bar#baz");
assertThat(result.toUri()).as("Invalid result URI").isEqualTo(expected);
result = UriComponentsBuilder.fromPath("/foo").build();
assertThat(result.getPath()).isEqualTo("/foo");
expected = new URI("/foo");
expected = URI.create("/foo");
assertThat(result.toUri()).as("Invalid result URI").isEqualTo(expected);
}
@Test
void fromHierarchicalUri() throws URISyntaxException {
URI uri = new URI("https://example.com/foo?bar#baz");
void fromHierarchicalUri() {
URI uri = URI.create("https://example.com/foo?bar#baz");
UriComponents result = UriComponentsBuilder.fromUri(uri).build();
assertThat(result.getScheme()).isEqualTo("https");
@@ -149,8 +148,8 @@ class UriComponentsBuilderTests {
}
@Test
void fromOpaqueUri() throws URISyntaxException {
URI uri = new URI("mailto:foo@bar.com#baz");
void fromOpaqueUri() {
URI uri = URI.create("mailto:foo@bar.com#baz");
UriComponents result = UriComponentsBuilder.fromUri(uri).build();
assertThat(result.getScheme()).isEqualTo("mailto");
@@ -160,8 +159,8 @@ class UriComponentsBuilderTests {
}
@Test // SPR-9317
void fromUriEncodedQuery() throws URISyntaxException {
URI uri = new URI("https://www.example.org/?param=aGVsbG9Xb3JsZA%3D%3D");
void fromUriEncodedQuery() {
URI uri = URI.create("https://www.example.org/?param=aGVsbG9Xb3JsZA%3D%3D");
String fromUri = UriComponentsBuilder.fromUri(uri).build().getQueryParams().get("param").get(0);
String fromUriString = UriComponentsBuilder.fromUriString(uri.toString())
.build().getQueryParams().get("param").get(0);
@@ -967,8 +966,8 @@ class UriComponentsBuilderTests {
}
@Test // gh-24444
void opaqueUriDoesNotResetOnNullInput() throws URISyntaxException {
URI uri = new URI("urn:ietf:wg:oauth:2.0:oob");
void opaqueUriDoesNotResetOnNullInput() {
URI uri = URI.create("urn:ietf:wg:oauth:2.0:oob");
UriComponents result = UriComponentsBuilder.fromUri(uri)
.host(null)
.port(-1)

View File

@@ -21,7 +21,6 @@ import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Collections;
@@ -76,30 +75,30 @@ class UriComponentsTests {
}
@Test
void toUriEncoded() throws URISyntaxException {
void toUriEncoded() {
UriComponents uri = UriComponentsBuilder.fromUriString("https://example.com/hotel list/Z\u00fcrich").build();
assertThat(uri.encode().toUri()).isEqualTo(new URI("https://example.com/hotel%20list/Z%C3%BCrich"));
assertThat(uri.encode().toUri()).isEqualTo(URI.create("https://example.com/hotel%20list/Z%C3%BCrich"));
}
@Test
void toUriNotEncoded() throws URISyntaxException {
void toUriNotEncoded() {
UriComponents uri = UriComponentsBuilder.fromUriString("https://example.com/hotel list/Z\u00fcrich").build();
assertThat(uri.toUri()).isEqualTo(new URI("https://example.com/hotel%20list/Z\u00fcrich"));
assertThat(uri.toUri()).isEqualTo(URI.create("https://example.com/hotel%20list/Z\u00fcrich"));
}
@Test
void toUriAlreadyEncoded() throws URISyntaxException {
void toUriAlreadyEncoded() {
UriComponents uri = UriComponentsBuilder.fromUriString("https://example.com/hotel%20list/Z%C3%BCrich").build(true);
assertThat(uri.encode().toUri()).isEqualTo(new URI("https://example.com/hotel%20list/Z%C3%BCrich"));
assertThat(uri.encode().toUri()).isEqualTo(URI.create("https://example.com/hotel%20list/Z%C3%BCrich"));
}
@Test
void toUriWithIpv6HostAlreadyEncoded() throws URISyntaxException {
void toUriWithIpv6HostAlreadyEncoded() {
UriComponents uri = UriComponentsBuilder.fromUriString(
"http://[1abc:2abc:3abc::5ABC:6abc]:8080/hotel%20list/Z%C3%BCrich").build(true);
assertThat(uri.encode().toUri()).isEqualTo(
new URI("http://[1abc:2abc:3abc::5ABC:6abc]:8080/hotel%20list/Z%C3%BCrich"));
URI.create("http://[1abc:2abc:3abc::5ABC:6abc]:8080/hotel%20list/Z%C3%BCrich"));
}
@Test

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2020 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,73 +33,73 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* @author Juergen Hoeller
* @author Rossen Stoyanchev
*/
public class UriTemplateTests {
class UriTemplateTests {
@Test
public void getVariableNames() throws Exception {
void getVariableNames() {
UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}");
List<String> variableNames = template.getVariableNames();
assertThat(variableNames).as("Invalid variable names").isEqualTo(Arrays.asList("hotel", "booking"));
}
@Test
public void expandVarArgs() throws Exception {
void expandVarArgs() {
UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}");
URI result = template.expand("1", "42");
assertThat(result).as("Invalid expanded template").isEqualTo(new URI("/hotels/1/bookings/42"));
assertThat(result).as("Invalid expanded template").isEqualTo(URI.create("/hotels/1/bookings/42"));
}
@Test // SPR-9712
public void expandVarArgsWithArrayValue() throws Exception {
void expandVarArgsWithArrayValue() {
UriTemplate template = new UriTemplate("/sum?numbers={numbers}");
URI result = template.expand(new int[] {1, 2, 3});
assertThat(result).isEqualTo(new URI("/sum?numbers=1,2,3"));
assertThat(result).isEqualTo(URI.create("/sum?numbers=1,2,3"));
}
@Test
public void expandVarArgsNotEnoughVariables() throws Exception {
void expandVarArgsNotEnoughVariables() {
UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}");
assertThatIllegalArgumentException().isThrownBy(() -> template.expand("1"));
}
@Test
public void expandMap() throws Exception {
void expandMap() {
Map<String, String> uriVariables = new HashMap<>(2);
uriVariables.put("booking", "42");
uriVariables.put("hotel", "1");
UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}");
URI result = template.expand(uriVariables);
assertThat(result).as("Invalid expanded template").isEqualTo(new URI("/hotels/1/bookings/42"));
assertThat(result).as("Invalid expanded template").isEqualTo(URI.create("/hotels/1/bookings/42"));
}
@Test
public void expandMapDuplicateVariables() throws Exception {
void expandMapDuplicateVariables() {
UriTemplate template = new UriTemplate("/order/{c}/{c}/{c}");
assertThat(template.getVariableNames()).isEqualTo(Arrays.asList("c", "c", "c"));
URI result = template.expand(Collections.singletonMap("c", "cheeseburger"));
assertThat(result).isEqualTo(new URI("/order/cheeseburger/cheeseburger/cheeseburger"));
assertThat(result).isEqualTo(URI.create("/order/cheeseburger/cheeseburger/cheeseburger"));
}
@Test
public void expandMapNonString() throws Exception {
void expandMapNonString() {
Map<String, Integer> uriVariables = new HashMap<>(2);
uriVariables.put("booking", 42);
uriVariables.put("hotel", 1);
UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}");
URI result = template.expand(uriVariables);
assertThat(result).as("Invalid expanded template").isEqualTo(new URI("/hotels/1/bookings/42"));
assertThat(result).as("Invalid expanded template").isEqualTo(URI.create("/hotels/1/bookings/42"));
}
@Test
public void expandMapEncoded() throws Exception {
void expandMapEncoded() {
Map<String, String> uriVariables = Collections.singletonMap("hotel", "Z\u00fcrich");
UriTemplate template = new UriTemplate("/hotel list/{hotel}");
URI result = template.expand(uriVariables);
assertThat(result).as("Invalid expanded template").isEqualTo(new URI("/hotel%20list/Z%C3%BCrich"));
assertThat(result).as("Invalid expanded template").isEqualTo(URI.create("/hotel%20list/Z%C3%BCrich"));
}
@Test
public void expandMapUnboundVariables() throws Exception {
void expandMapUnboundVariables() {
Map<String, String> uriVariables = new HashMap<>(2);
uriVariables.put("booking", "42");
uriVariables.put("bar", "1");
@@ -109,14 +109,14 @@ public class UriTemplateTests {
}
@Test
public void expandEncoded() throws Exception {
void expandEncoded() {
UriTemplate template = new UriTemplate("/hotel list/{hotel}");
URI result = template.expand("Z\u00fcrich");
assertThat(result).as("Invalid expanded template").isEqualTo(new URI("/hotel%20list/Z%C3%BCrich"));
assertThat(result).as("Invalid expanded template").isEqualTo(URI.create("/hotel%20list/Z%C3%BCrich"));
}
@Test
public void matches() throws Exception {
void matches() {
UriTemplate template = new UriTemplate("/hotels/{hotel}/bookings/{booking}");
assertThat(template.matches("/hotels/1/bookings/42")).as("UriTemplate does not match").isTrue();
assertThat(template.matches("/hotels/bookings")).as("UriTemplate matches").isFalse();
@@ -125,14 +125,14 @@ public class UriTemplateTests {
}
@Test
public void matchesCustomRegex() throws Exception {
void matchesCustomRegex() {
UriTemplate template = new UriTemplate("/hotels/{hotel:\\d+}");
assertThat(template.matches("/hotels/42")).as("UriTemplate does not match").isTrue();
assertThat(template.matches("/hotels/foo")).as("UriTemplate matches").isFalse();
}
@Test
public void match() throws Exception {
void match() {
Map<String, String> expected = new HashMap<>(2);
expected.put("booking", "42");
expected.put("hotel", "1");
@@ -143,7 +143,7 @@ public class UriTemplateTests {
}
@Test
public void matchCustomRegex() throws Exception {
void matchCustomRegex() {
Map<String, String> expected = new HashMap<>(2);
expected.put("booking", "42");
expected.put("hotel", "1");
@@ -154,14 +154,14 @@ public class UriTemplateTests {
}
@Test // SPR-13627
public void matchCustomRegexWithNestedCurlyBraces() throws Exception {
void matchCustomRegexWithNestedCurlyBraces() {
UriTemplate template = new UriTemplate("/site.{domain:co.[a-z]{2}}");
Map<String, String> result = template.match("/site.co.eu");
assertThat(result).as("Invalid match").isEqualTo(Collections.singletonMap("domain", "co.eu"));
}
@Test
public void matchDuplicate() throws Exception {
void matchDuplicate() {
UriTemplate template = new UriTemplate("/order/{c}/{c}/{c}");
Map<String, String> result = template.match("/order/cheeseburger/cheeseburger/cheeseburger");
Map<String, String> expected = Collections.singletonMap("c", "cheeseburger");
@@ -169,7 +169,7 @@ public class UriTemplateTests {
}
@Test
public void matchMultipleInOneSegment() throws Exception {
void matchMultipleInOneSegment() {
UriTemplate template = new UriTemplate("/{foo}-{bar}");
Map<String, String> result = template.match("/12-34");
Map<String, String> expected = new HashMap<>(2);
@@ -179,19 +179,19 @@ public class UriTemplateTests {
}
@Test // SPR-16169
public void matchWithMultipleSegmentsAtTheEnd() throws Exception {
void matchWithMultipleSegmentsAtTheEnd() {
UriTemplate template = new UriTemplate("/account/{accountId}");
assertThat(template.matches("/account/15/alias/5")).isFalse();
}
@Test
public void queryVariables() throws Exception {
void queryVariables() {
UriTemplate template = new UriTemplate("/search?q={query}");
assertThat(template.matches("/search?q=foo")).isTrue();
}
@Test
public void fragments() throws Exception {
void fragments() {
UriTemplate template = new UriTemplate("/search#{fragment}");
assertThat(template.matches("/search#foo")).isTrue();
@@ -200,19 +200,19 @@ public class UriTemplateTests {
}
@Test // SPR-13705
public void matchesWithSlashAtTheEnd() throws Exception {
void matchesWithSlashAtTheEnd() {
assertThat(new UriTemplate("/test/").matches("/test/")).isTrue();
}
@Test
public void expandWithDollar() throws Exception {
void expandWithDollar() {
UriTemplate template = new UriTemplate("/{a}");
URI uri = template.expand("$replacement");
assertThat(uri.toString()).isEqualTo("/$replacement");
}
@Test
public void expandWithAtSign() throws Exception {
void expandWithAtSign() {
UriTemplate template = new UriTemplate("http://localhost/query={query}");
URI uri = template.expand("foo@bar");
assertThat(uri.toString()).isEqualTo("http://localhost/query=foo@bar");