/*
Copyright 2012-2014 Samuel Gesche

This file is part of the Greek Reuse Toolkit.

The Greek Reuse Toolkit is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

The Greek Reuse Toolkit is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with the Greek Reuse Toolkit.  If not, see <http://www.gnu.org/licenses/>.
*/

package fr.cnrs.liris.drim.grt.proc.parsers;

import fr.cnrs.liris.drim.grt.proc.exceptions.DOMCreationFailureException;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * This class offers methods for parsing an XML file into a hierarchical tree.
 * See org.w3c.dom.Document for further information about the obtained tree.
 *
 * @author Samuel Gesche
 */

public class XMLReader{

  /**
   * Parses the given file into a tree.
   * @param file the XML file to parse.
   * @return a Document describing the XML file.
   * @throws proc.exceptions.DOMCreationFailureException if someting goes wrong.
   */
  public static Document getDOM(File file) throws DOMCreationFailureException{
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setIgnoringComments(true);
    dbf.setCoalescing(false);
    dbf.setIgnoringElementContentWhitespace(true);
    DocumentBuilder db = null;
    try{
      db = dbf.newDocumentBuilder();
    }
    catch (ParserConfigurationException pce){
      throw new DOMCreationFailureException("Echec de configuration du parseur (" +
                                            pce.getMessage() + ")", pce);
    }
    Document result = null;
    try{
      result = db.parse(file);
    }
    catch (SAXException se){
      throw new DOMCreationFailureException("Echec de parsage du texte (" +
                                            se.getMessage() + ")", se);
    }
    catch (IOException ioe){
      throw new DOMCreationFailureException("Echec de parsage du texte (" +
                                            ioe.getMessage() + ")", ioe);
    }
    return result;
  }

}
