home / blog

Marshalling JAXB entities into SOAP wrappers

SOAP envelopes can be added to existing org.w3c.dom.Document or JAXB instances easily.

Farm farm = new Farm();
farm.getHorse().add(new Horse());
farm.getHorse().get(0).setName("glue factory");

Example: using standard API

Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Marshaller marshaller = JAXBContext.newInstance(Farm.class).createMarshaller();
marshaller.marshal(farm, document);

SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

String output = new String(outputStream.toByteArray());

Anti-example seen in the wild: manual concatenation/formatting

String soapEnvelope =
        "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "<soapenv:Header /><soapenv:Body>%s</soapenv:Body></soapenv:Envelope>";

Marshaller marshaller = JAXBContext.newInstance(Farm.class).createMarshaller();
marshaller.setProperty("jaxb.fragment", Boolean.TRUE); // required to stop <?xml ... being added ?>

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
marshaller.marshal(farm, outputStream);
String payload = new String(outputStream.toByteArray());

String output = String.format(soapEnvelope, payload);

Note, the namespace prefix, which the standard libraries which defaults to SOAP-ENV can be changed, but it’s hard work.

soapMessage.getSOAPPart().getEnvelope().addNamespaceDeclaration("soap", "http://www.w3.org/2001/12/soap-envelope");
This entry was posted in geek and tagged , . Bookmark the permalink.

One Response to Marshalling JAXB entities into SOAP wrappers

  1. André says:

    Information on how to do “manual” SOAP and JAXB conversions is so hard to find, thank you so much for working it out so clearly, you saved my day. :)

Leave a Reply

Your email address will not be published.

three − 3 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>