/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.datasource.reader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.xml.sax.SAXException;

/**
 * Class that does validation on a datasource.
 * @author Tarik Ihadjadene
 */
public class DatasourceValidator {

    /**
     * Private no-args constructor.
     */
    @SuppressWarnings("unused")
    private DatasourceValidator() {
    }

    /**
     * XML Schema for DataSources.
     */
    private static final String DATASOURCE_XSD = "/org/ow2/jonas/datasource/binding/schema/jonas-datasources-1.0.xsd";

    /**
     * Gets the XML file and tries to validate it.
     * @param xmlFile the file to validate.
     * @throws SAXException if a SAX exception is triggered.
     * @throws ParserConfigurationException if the parser couldn't be
     *         configured.
     * @throws IOException if the file couldn't be read.
     */
    public DatasourceValidator(final File xmlFile) throws SAXException, ParserConfigurationException, IOException {

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        InputStream is = getClass().getResourceAsStream(DATASOURCE_XSD);
        if (is == null) {
            System.out.println("is == null");
        }
        Source source = new StreamSource(is);
        if (source == null) {
            System.out.println("source == null");
        }
        Schema schema = schemaFactory.newSchema(source);
        Validator validator = schema.newValidator();

        Source xmlSource = new StreamSource(xmlFile);

        validator.validate(xmlSource);
    }
}
