Skip to content

Commit d3eb9cf

Browse files
authored
Ensure all brackets are decoded in JSON based Body Templates (OpenFeign#1140)
* Ensure all brackets are decoded in JSON based Body Templates Fixes OpenFeign#1129 When JSON is detected in a Body Template, all start and end tokens that may have been pct-encoded are decoded, ensuring that the expanded result is valid JSON.
1 parent 9e23599 commit d3eb9cf

2 files changed

Lines changed: 35 additions & 8 deletions

File tree

‎core/src/main/java/feign/template/BodyTemplate.java‎

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,14 +50,9 @@ private BodyTemplate(String value, Charset charset) {
5050
public String expand(Map<String, ?> variables) {
5151
String expanded = super.expand(variables);
5252
if (this.json) {
53-
/* decode only the first and last character */
54-
StringBuilder sb = new StringBuilder();
55-
sb.append(JSON_TOKEN_START);
56-
sb.append(expanded,
57-
expanded.indexOf(JSON_TOKEN_START_ENCODED) + JSON_TOKEN_START_ENCODED.length(),
58-
expanded.lastIndexOf(JSON_TOKEN_END_ENCODED));
59-
sb.append(JSON_TOKEN_END);
60-
return sb.toString();
53+
/* restore all start and end tokens */
54+
expanded = expanded.replaceAll(JSON_TOKEN_START_ENCODED, JSON_TOKEN_START);
55+
expanded = expanded.replaceAll(JSON_TOKEN_END_ENCODED, JSON_TOKEN_END);
6156
}
6257
return expanded;
6358
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Copyright 2012-2019 The Feign Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5+
* in compliance with the License. You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software distributed under the License
10+
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11+
* or implied. See the License for the specific language governing permissions and limitations under
12+
* the License.
13+
*/
14+
package feign.template;
15+
16+
import static org.assertj.core.api.Assertions.assertThat;
17+
import java.util.Collections;
18+
import org.junit.Test;
19+
20+
public class BodyTemplateTest {
21+
22+
@Test
23+
public void bodyTemplatesSupportJsonOnlyWhenEncoded() {
24+
String bodyTemplate =
25+
"%7B\"resize\": %7B\"method\": \"fit\",\"width\": {size},\"height\": {size}%7D%7D";
26+
BodyTemplate template = BodyTemplate.create(bodyTemplate);
27+
String expanded = template.expand(Collections.singletonMap("size", "100"));
28+
assertThat(expanded)
29+
.isEqualToIgnoringCase(
30+
"{\"resize\": {\"method\": \"fit\",\"width\": 100,\"height\": 100}}");
31+
}
32+
}

0 commit comments

Comments
 (0)