001package com.plivo.api.xml;
002
003import com.plivo.api.exceptions.PlivoXmlException;
004import com.sun.xml.internal.bind.marshaller.CharacterEscapeHandler;
005import com.sun.xml.internal.bind.marshaller.DataWriter;
006
007import java.io.IOException;
008import java.io.PrintWriter;
009import java.io.StringWriter;
010import java.io.Writer;
011import javax.xml.bind.JAXBContext;
012import javax.xml.bind.JAXBException;
013import javax.xml.bind.Marshaller;
014import javax.xml.bind.annotation.XmlTransient;
015
016@XmlTransient
017public class PlivoXml {
018
019        public String toXmlString() throws PlivoXmlException {
020                return toXmlString(false);
021        }
022
023        public String toXmlString(boolean debug) throws PlivoXmlException {
024
025                try {
026                        JAXBContext jaxbContext = JAXBContext.newInstance(getClass());
027                        StringWriter stringWriter = new StringWriter();
028                        Marshaller marshaller = jaxbContext.createMarshaller();
029                        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
030                        if (debug) {
031                                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
032                        }
033
034                        // Set UTF-8 Encoding
035                        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
036
037                        // The below code will take care of avoiding the conversion of < to &lt; and > to &gt; etc
038                        PrintWriter printWriter = new PrintWriter(stringWriter);
039                        DataWriter dataWriter = new DataWriter(printWriter, "UTF-8", new JaxbCharacterEscapeHandler());
040
041                        // Perform Marshalling operation
042                        marshaller.marshal(this, dataWriter);
043
044                        return stringWriter.toString();
045                } catch (JAXBException e) {
046                        e.printStackTrace();
047                        throw new PlivoXmlException(e.getMessage());
048                }
049        }
050}