Skip to content

Commit

Permalink
Support JAXBElement in Jaxb2XmlEncoder
Browse files Browse the repository at this point in the history
This commit introduces support for JAXBElements in the Jaxb2XmlEncoder.

Closes gh-30552
  • Loading branch information
poutsma committed Jun 8, 2023
1 parent 2f78b42 commit d7970e4
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -21,6 +21,7 @@
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;
Expand Down Expand Up @@ -121,7 +122,7 @@ public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory,
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;
Expand All @@ -140,6 +141,15 @@ public DataBuffer encodeValue(Object value, DataBufferFactory bufferFactory,
}
}

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());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
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;
Expand Down Expand Up @@ -76,6 +79,18 @@ public void encode() {
.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);
Expand Down

0 comments on commit d7970e4

Please sign in to comment.