Support JAXBElement in Jaxb2XmlEncoder

This commit introduces support for JAXBElements in the Jaxb2XmlEncoder.

Closes gh-30552
This commit is contained in:
Arjen Poutsma 2023-06-08 15:29:56 +02:00
parent 2f78b42133
commit d7970e4ab8
2 changed files with 27 additions and 2 deletions

View File

@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2023 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.
@ -21,6 +21,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.function.Function;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.MarshalException;
import jakarta.xml.bind.Marshaller;
@ -121,7 +122,7 @@ public class Jaxb2XmlEncoder extends AbstractSingleValueEncoder<Object> {
DataBuffer buffer = bufferFactory.allocateBuffer(1024);
try {
OutputStream outputStream = buffer.asOutputStream();
Class<?> clazz = ClassUtils.getUserClass(value);
Class<?> clazz = getMarshallerType(value);
Marshaller marshaller = initMarshaller(clazz);
marshaller.marshal(value, outputStream);
release = false;
@ -140,6 +141,15 @@ public class Jaxb2XmlEncoder extends AbstractSingleValueEncoder<Object> {
}
}
private static Class<?> getMarshallerType(Object value) {
if (value instanceof JAXBElement<?> jaxbElement) {
return jaxbElement.getDeclaredType();
}
else {
return ClassUtils.getUserClass(value);
}
}
private Marshaller initMarshaller(Class<?> clazz) throws CodecException, JAXBException {
Marshaller marshaller = this.jaxbContexts.createMarshaller(clazz);
marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());

View File

@ -20,6 +20,9 @@ import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import javax.xml.namespace.QName;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlElements;
import jakarta.xml.bind.annotation.XmlRootElement;
@ -76,6 +79,18 @@ public class Jaxb2XmlEncoderTests extends AbstractEncoderTests<Jaxb2XmlEncoder>
.verifyComplete());
}
@Test
public void encodeJaxbElement() {
Mono<JAXBElement<Pojo>> input = Mono.just(new JAXBElement<>(new QName("baz"), Pojo.class,
new Pojo("foofoo", "barbar")));
testEncode(input, Pojo.class, step -> step
.consumeNextWith(expectXml(
"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>" +
"<baz><bar>barbar</bar><foo>foofoo</foo></baz>"))
.verifyComplete());
}
@Test
public void encodeError() {
Flux<Pojo> input = Flux.error(RuntimeException::new);