How do we pass media type info in lagom rest call in the service call?
i have a rest call which takes xml as request, but then it throws a deserialization exception.
use this restCall(Method.POST, “/api”, this::func)
.withRequestSerializer(new XMLSerializer())
`public class XMLSerializer implements StrictMessageSerializer {
private Unmarshaller unmarshaller;
private final Marshaller marshaller;
public static final Logger LOGGER = LoggerFactory.getLogger(XMLSerializer.class);
public XMLSerializer() {
try {
JAXBContext context = JAXBContext.newInstance(YourRequestDtoClass.class);
this.unmarshaller = context.createUnmarshaller();
this.marshaller = context.createMarshaller();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
private final NegotiatedSerializer<YourRequestDtoClass, ByteString> serializer =
new NegotiatedSerializer<YourRequestDtoClass, ByteString>() {
@Override
public MessageProtocol protocol() {
return new MessageProtocol().withContentType("application/xml");
}
@Override
public ByteString serialize(YourRequestDtoClass order) throws SerializationException {
ByteStringBuilder builder = ByteString.createBuilder();
try {
marshaller.marshal(order, builder.asOutputStream());
return builder.result();
} catch (JAXBException e) {
throw new SerializationException(e);
}
}
};
private final NegotiatedDeserializer<YourRequestDtoClass, ByteString> deserializer =
bytes -> {
try {
LOGGER.info("bytes in unmarshaller: "+ bytes.iterator().asInputStream());
return unmarshaller
.unmarshal(new StreamSource(bytes.iterator().asInputStream()), YourRequestDtoClass.class)
.getValue();
} catch (JAXBException e) {
throw new DeserializationException(e);
}
};
@Override
public NegotiatedSerializer<YourRequestDtoClass, ByteString> serializerForRequest() {
return serializer;
}
@Override
public NegotiatedDeserializer<YourRequestDtoClass, ByteString> deserializer(MessageProtocol protocol)
throws UnsupportedMediaType {
return deserializer;
}
@Override
public NegotiatedSerializer<YourRequestDtoClass, ByteString> serializerForResponse(
List<MessageProtocol> acceptedMessageProtocols) throws NotAcceptable {
return serializer;
}
}
`