forked from OpenFeign/feign
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJAXBCodecTest.java
More file actions
454 lines (382 loc) · 14.3 KB
/
Copy pathJAXBCodecTest.java
File metadata and controls
454 lines (382 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/*
* Copyright © 2012 The Feign Authors (feign@commonhaus.dev)
*
* 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 feign.jaxb;
import static feign.Util.UTF_8;
import static feign.assertj.FeignAssertions.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import feign.Request;
import feign.Request.HttpMethod;
import feign.RequestTemplate;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.EncodeException;
import feign.codec.Encoder;
import java.io.StringReader;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Objects;
import javax.xml.XMLConstants;
import javax.xml.bind.MarshalException;
import javax.xml.bind.UnmarshalException;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.junit.jupiter.api.Test;
@SuppressWarnings("deprecation")
class JAXBCodecTest {
@Test
void encodesXml() throws Exception {
MockObject mock = new MockObject();
mock.value = "Test";
RequestTemplate template = new RequestTemplate();
new JAXBEncoder(new JAXBContextFactory.Builder().build())
.encode(mock, MockObject.class, template);
assertThat(template)
.hasBody(
"<?xml version=\"1.0\" encoding=\"UTF-8\""
+ " standalone=\"yes\"?><mockObject><value>Test</value></mockObject>");
}
@Test
void doesntEncodeParameterizedTypes() throws Exception {
class ParameterizedHolder {
Map<String, ?> field;
}
Type parameterized = ParameterizedHolder.class.getDeclaredField("field").getGenericType();
RequestTemplate template = new RequestTemplate();
Throwable exception =
assertThrows(
UnsupportedOperationException.class,
() ->
new JAXBEncoder(new JAXBContextFactory.Builder().build())
.encode(Collections.emptyMap(), parameterized, template));
assertThat(exception.getMessage())
.contains(
"JAXB only supports encoding raw types. Found java.util.Map<java.lang.String, ?>");
}
@Test
void encodesXmlWithCustomJAXBEncoding() throws Exception {
JAXBContextFactory jaxbContextFactory =
new JAXBContextFactory.Builder().withMarshallerJAXBEncoding("UTF-16").build();
Encoder encoder = new JAXBEncoder(jaxbContextFactory);
MockObject mock = new MockObject();
mock.value = "Test";
RequestTemplate template = new RequestTemplate();
encoder.encode(mock, MockObject.class, template);
assertThat(template)
.hasBody(
"""
<?xml version="1.0" encoding="UTF-16" \
standalone="yes"?><mockObject><value>Test</value></mockObject>\
""");
}
@Test
void encodesXmlWithCustomJAXBSchemaLocation() throws Exception {
JAXBContextFactory jaxbContextFactory =
new JAXBContextFactory.Builder()
.withMarshallerSchemaLocation("http://apihost http://apihost/schema.xsd")
.build();
Encoder encoder = new JAXBEncoder(jaxbContextFactory);
MockObject mock = new MockObject();
mock.value = "Test";
RequestTemplate template = new RequestTemplate();
encoder.encode(mock, MockObject.class, template);
assertThat(template)
.hasBody(
"""
<?xml version="1.0" encoding="UTF-8" \
standalone="yes"?><mockObject xsi:schemaLocation="http://apihost \
http://apihost/schema.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\
<value>Test</value></mockObject>\
""");
}
@Test
void encodesXmlWithCustomJAXBNoNamespaceSchemaLocation() throws Exception {
JAXBContextFactory jaxbContextFactory =
new JAXBContextFactory.Builder()
.withMarshallerNoNamespaceSchemaLocation("http://apihost/schema.xsd")
.build();
Encoder encoder = new JAXBEncoder(jaxbContextFactory);
MockObject mock = new MockObject();
mock.value = "Test";
RequestTemplate template = new RequestTemplate();
encoder.encode(mock, MockObject.class, template);
assertThat(template)
.hasBody(
"""
<?xml version="1.0" encoding="UTF-8" \
standalone="yes"?><mockObject xsi:noNamespaceSchemaLocation="http://apihost/schema.xsd" \
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\
<value>Test</value></mockObject>\
""");
}
@Test
void encodesXmlWithCustomJAXBFormattedOutput() {
JAXBContextFactory jaxbContextFactory =
new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build();
Encoder encoder = new JAXBEncoder(jaxbContextFactory);
MockObject mock = new MockObject();
mock.value = "Test";
RequestTemplate template = new RequestTemplate();
encoder.encode(mock, MockObject.class, template);
// RequestTemplate always expects a UNIX style newline.
assertThat(template)
.hasBody(
new StringBuilder()
.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>")
.append("\n")
.append("<mockObject>")
.append("\n")
.append(" <value>Test</value>")
.append("\n")
.append("</mockObject>")
.append("\n")
.toString());
}
@Test
void decodesXml() throws Exception {
MockObject mock = new MockObject();
mock.value = "Test";
String mockXml =
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><mockObject>\
<value>Test</value></mockObject>\
""";
Response response =
Response.builder()
.status(200)
.reason("OK")
.request(
Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
.headers(Collections.emptyMap())
.body(mockXml, UTF_8)
.build();
JAXBDecoder decoder = new JAXBDecoder(new JAXBContextFactory.Builder().build());
assertThat(decoder.decode(response, MockObject.class)).isEqualTo(mock);
}
@Test
void doesntDecodeParameterizedTypes() throws Exception {
class ParameterizedHolder {
Map<String, ?> field;
}
Type parameterized = ParameterizedHolder.class.getDeclaredField("field").getGenericType();
Response response =
Response.builder()
.status(200)
.reason("OK")
.request(
Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
.headers(Collections.<String, Collection<String>>emptyMap())
.body("<foo/>", UTF_8)
.build();
Throwable exception =
assertThrows(
DecodeException.class,
() ->
new JAXBDecoder(new JAXBContextFactory.Builder().build())
.decode(response, parameterized));
assertThat(exception.getMessage())
.contains(
"""
java.util.Map is an interface, and JAXB can't handle interfaces.
this problem is related to the following location:
at java.util.Map\
""");
}
@XmlRootElement
static class Box<T> {
@XmlElement private T t;
public void set(T t) {
this.t = t;
}
}
@Test
void decodeAnnotatedParameterizedTypes() throws Exception {
JAXBContextFactory jaxbContextFactory =
new JAXBContextFactory.Builder().withMarshallerFormattedOutput(true).build();
Encoder encoder = new JAXBEncoder(jaxbContextFactory);
Box<String> boxStr = new Box<>();
boxStr.set("hello");
Box<Box<String>> boxBoxStr = new Box<>();
boxBoxStr.set(boxStr);
RequestTemplate template = new RequestTemplate();
encoder.encode(boxBoxStr, Box.class, template);
Response response =
Response.builder()
.status(200)
.reason("OK")
.request(
Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
.headers(Collections.<String, Collection<String>>emptyMap())
.body(template.body())
.build();
new JAXBDecoder(new JAXBContextFactory.Builder().build()).decode(response, Box.class);
}
/** Enabled via {@link feign.Feign.Builder#dismiss404()} */
@Test
void notFoundDecodesToEmpty() throws Exception {
Response response =
Response.builder()
.status(404)
.reason("NOT FOUND")
.request(
Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
.headers(Collections.<String, Collection<String>>emptyMap())
.build();
assertThat(
(byte[])
new JAXBDecoder(new JAXBContextFactory.Builder().build())
.decode(response, byte[].class))
.isEmpty();
}
@Test
void decodeThrowsExceptionWhenUnmarshallingFailsWithSetSchema() throws Exception {
String mockXml =
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><mockIntObject>\
<value>Test</value></mockIntObject>\
""";
Response response =
Response.builder()
.status(200)
.reason("OK")
.request(
Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
.headers(Collections.emptyMap())
.body(mockXml, UTF_8)
.build();
JAXBContextFactory factory =
new JAXBContextFactory.Builder().withUnmarshallerSchema(getMockIntObjSchema()).build();
DecodeException exception =
assertThrows(
DecodeException.class,
() -> new JAXBDecoder(factory).decode(response, MockIntObject.class));
assertThat(exception)
.hasCauseInstanceOf(UnmarshalException.class)
.hasMessageContaining("'Test' is not a valid value for 'integer'.");
}
@Test
void decodesIgnoringErrorsWithEventHandler() throws Exception {
String mockXml =
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><mockIntObject>\
<value>Test</value></mockIntObject>\
""";
Response response =
Response.builder()
.status(200)
.reason("OK")
.request(
Request.create(HttpMethod.GET, "/api", Collections.emptyMap(), null, Util.UTF_8))
.headers(Collections.emptyMap())
.body(mockXml, UTF_8)
.build();
JAXBContextFactory factory =
new JAXBContextFactory.Builder()
.withUnmarshallerSchema(getMockIntObjSchema())
.withUnmarshallerEventHandler(event -> true)
.build();
assertThat(new JAXBDecoder(factory).decode(response, MockIntObject.class))
.isEqualTo(new MockIntObject());
}
@Test
void encodeThrowsExceptionWhenMarshallingFailsWithSetSchema() throws Exception {
JAXBContextFactory jaxbContextFactory =
new JAXBContextFactory.Builder().withMarshallerSchema(getMockIntObjSchema()).build();
Encoder encoder = new JAXBEncoder(jaxbContextFactory);
RequestTemplate template = new RequestTemplate();
EncodeException exception =
assertThrows(
EncodeException.class,
() -> encoder.encode(new MockIntObject(), MockIntObject.class, template));
assertThat(exception)
.hasCauseInstanceOf(MarshalException.class)
.hasMessageContaining("The content of element 'mockIntObject' is not complete.");
}
@Test
void encodesIgnoringErrorsWithEventHandler() throws Exception {
JAXBContextFactory jaxbContextFactory =
new JAXBContextFactory.Builder()
.withMarshallerSchema(getMockIntObjSchema())
.withMarshallerEventHandler(event -> true)
.build();
Encoder encoder = new JAXBEncoder(jaxbContextFactory);
RequestTemplate template = new RequestTemplate();
encoder.encode(new MockIntObject(), MockIntObject.class, template);
assertThat(template)
.hasBody(
"""
<?xml version="1.0" encoding="UTF-8"\
standalone="yes"?><mockIntObject/>\
""");
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
static class MockIntObject {
@XmlElement(required = true)
private Integer value;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MockIntObject that = (MockIntObject) o;
return Objects.equals(value, that.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
private static Schema getMockIntObjSchema() throws Exception {
String schema =
"""
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">\
<xs:element name="mockIntObject" type="mockIntObject"/><xs:complexType name="mockIntObject">\
<xs:sequence><xs:element name="value" type="xs:int"/></xs:sequence></xs:complexType>\
</xs:schema>\
""";
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
return schemaFactory.newSchema(new StreamSource(new StringReader(schema)));
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
static class MockObject {
@XmlElement private String value;
@Override
public boolean equals(Object obj) {
if (obj instanceof MockObject other) {
return value.equals(other.value);
}
return false;
}
@Override
public int hashCode() {
return value != null ? value.hashCode() : 0;
}
}
}