/*
 * Copyright (c) eHealth
 */
package be.ehealth.businessconnector.chapterIV.service;

import java.io.InputStream;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;

import org.apache.commons.lang.ArrayUtils;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


/**
 * test class for {@link ServiceFactory}
 * 
 * @author EHP
 * 
 */
public class ServiceFactoryTest {

    private static final Logger LOG = LoggerFactory.getLogger(ServiceFactoryTest.class);

    /**
     * Test if all the xsd needed by the ServiceFactory are present on the classpath.
     * 
     * @throws Exception
     */
    @Test
    public void testXSDPresent() throws Exception {
        Source[] sources = new Source[]{};
        for (String xsd : ServiceFactory.CH4_XSD) {
            InputStream in = ServiceFactoryTest.class.getResourceAsStream(xsd);
            Assert.assertNotNull("Could not find file:" + xsd, in);
            Source source = new StreamSource(in);
            sources = (Source[]) ArrayUtils.add(sources, source);
        }
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schemaFactory.setErrorHandler(new MyErrorHandler());
        schemaFactory.newSchema(sources);

    }

    /**
     * Inner ErrorHandler used to validate XSD files Logs every encountered errors
     * 
     * @author EHP
     * 
     */
    class MyErrorHandler implements ErrorHandler {

        @Override
        public void warning(SAXParseException exception) throws SAXException {
            // Bring things to a crashing halt
            LOG.info("**Parsing Warning** " + "Line:    " + exception.getLineNumber() + " URI:     " + exception.getSystemId() + " Message: " + exception.getMessage());
            throw new SAXException("Warning encountered");
        }

        @Override
        public void error(SAXParseException exception) throws SAXException {
            // Bring things to a crashing halt
            LOG.info("**Parsing Error**" + "  Line:    " + exception.getLineNumber() + "  URI:     " + exception.getSystemId() + "  Message: " + exception.getMessage());
            throw new SAXException("Error encountered");
        }

        @Override
        public void fatalError(SAXParseException exception) throws SAXException {
            // Bring things to a crashing halt
            LOG.info("**Parsing Fatal Error**" + "  Line:    " + exception.getLineNumber() + "  URI:     " + exception.getSystemId() + "  Message: " + exception.getMessage());
            throw new SAXException("Fatal Error encountered");
        }
    }
}
