Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.ByteArrayOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;

@XmlRootElement
public class Main {

    private JAXBContext jaxbContext;
    private XMLOutputFactory xmlOutputFactory;

    public Main() throws Exception {
        jaxbContext = JAXBContext.newInstance(Main.class);
        xmlOutputFactory = XMLOutputFactory.newFactory();
    }

    public static void main(String[] args) throws Exception {
        System.out.println(new Main().getMessage());
    }

    public final String getMessage() throws Exception {

        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty("jaxb.encoding", "ISO-8859-1");
        jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        XMLStreamWriter xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(baos,
                (String) jaxbMarshaller.getProperty(Marshaller.JAXB_ENCODING));
        xmlStreamWriter.writeStartDocument((String) jaxbMarshaller.getProperty(Marshaller.JAXB_ENCODING), "1.0");
        jaxbMarshaller.marshal(this, xmlStreamWriter);
        xmlStreamWriter.writeEndDocument();
        xmlStreamWriter.close();
        return new String(baos.toByteArray());
    }
}