From 119dd04ae53433f186bb73a2ed347961dc7b2650 Mon Sep 17 00:00:00 2001 From: Juergen Hoeller Date: Mon, 9 Dec 2019 13:28:39 +0100 Subject: [PATCH] Avoid ByteArrayOutputStream for source values without the need to be encoded Closes gh-24152 --- .../web/util/HierarchicalUriComponents.java | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java index a78bc26f7c3f..1aaa56f5a12d 100644 --- a/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java +++ b/spring-web/src/main/java/org/springframework/web/util/HierarchicalUriComponents.java @@ -335,8 +335,21 @@ static String encodeUriComponent(String source, Charset charset, Type type) { Assert.notNull(type, "Type must not be null"); byte[] bytes = source.getBytes(charset); + boolean original = true; + for (byte b : bytes) { + if (b < 0) { + b += 256; + } + if (!type.isAllowed(b)) { + original = false; + break; + } + } + if (original) { + return source; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length); - boolean changed = false; for (byte b : bytes) { if (b < 0) { b += 256; @@ -350,10 +363,9 @@ static String encodeUriComponent(String source, Charset charset, Type type) { char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16)); bos.write(hex1); bos.write(hex2); - changed = true; } } - return (changed ? new String(bos.toByteArray(), charset) : source); + return new String(bos.toByteArray(), charset); } private Type getHostType() { @@ -416,12 +428,10 @@ else if (!type.isAllowed(ch)) { @Override protected HierarchicalUriComponents expandInternal(UriTemplateVariables uriVariables) { - Assert.state(!this.encodeState.equals(EncodeState.FULLY_ENCODED), "URI components already encoded, and could not possibly contain '{' or '}'."); - // Array-based vars rely on the below order.. - + // Array-based vars rely on the order below... String schemeTo = expandUriComponent(getScheme(), uriVariables, this.variableEncoder); String userInfoTo = expandUriComponent(this.userInfo, uriVariables, this.variableEncoder); String hostTo = expandUriComponent(this.host, uriVariables, this.variableEncoder);