/*
 *     Copyright (C) 2015 ASIP Santé
 */
package fr.asipsante.mss.connectkit.xml;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * Souche commune de tous les protocoles XML basés sur un parseur DOM.
 * 
 * @author ASIP Santé
 *
 */
public class DOMBasedXmlProtocol {

    /**
     * Transformer un DOM en document text/xml.
     * 
     * @param message
     * @param encoding
     * @return
     * @throws TransformerConfigurationException
     * @throws TransformerFactoryConfigurationError
     * @throws TransformerException
     */
    protected ByteArrayOutputStream toXmlText(Document message, String encoding)
            throws TransformerConfigurationException,
            TransformerFactoryConfigurationError, TransformerException {
        DOMSource messageSource = new DOMSource(message);
        Transformer serializer = TransformerFactory.newInstance()
                .newTransformer();
        serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        serializer.setOutputProperty(OutputKeys.METHOD, "xml");
        serializer.setOutputProperty(OutputKeys.ENCODING, encoding);
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
        ByteArrayOutputStream xmlContentStream = new ByteArrayOutputStream();
        StreamResult result = new StreamResult(xmlContentStream);
        serializer.transform(messageSource, result);
        return xmlContentStream;
    }

    /**
     * Créer un DOM à partir des données brutes d'un message XML.
     * 
     * @param reponseData
     * @return
     * @throws ParserConfigurationException
     * @throws SAXException
     * @throws IOException
     */
    protected Document parseRaw(byte[] reponseData)
            throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory docDuilderFactory = DocumentBuilderFactory
                .newInstance();
        docDuilderFactory.setNamespaceAware(true);
        DocumentBuilder builder = docDuilderFactory.newDocumentBuilder();
        Document message = builder.parse(new InputSource(
                new ByteArrayInputStream(reponseData)));
        return message;
    }

}