001package org.kuali.ole.ingest;
002
003import org.apache.commons.io.IOUtils;
004import org.kuali.ole.exception.ParseException;
005import org.kuali.ole.exception.XmlErrorHandler;
006import org.xml.sax.SAXException;
007
008import javax.xml.XMLConstants;
009import javax.xml.transform.Source;
010import javax.xml.transform.stream.StreamSource;
011import javax.xml.validation.Schema;
012import javax.xml.validation.SchemaFactory;
013import javax.xml.validation.Validator;
014import java.io.ByteArrayInputStream;
015import java.io.IOException;
016import java.io.InputStream;
017
018/**
019 * This class provides schema validation for uploaded location xml
020 */
021public class OleLocationXMLSchemaValidator {
022    //TODO: refactor the validateContentsAgainstSchema method to take only 1 parameter which is the file content.
023    private static final String LOCATION_SCHEMA_FILE = "locations.xsd";
024
025    /**
026     *  This method returns True/False.
027     *  This method  validate the inputStream content with W3C Xml Schema standard,if it matches it return True else return False.
028     * @param inputStream
029     * @return   boolean
030     * @throws org.kuali.ole.exception.ParseException
031     * @throws java.io.IOException
032     * @throws org.xml.sax.SAXException
033     */
034    public boolean validateContentsAgainstSchema(InputStream inputStream)
035            throws ParseException, IOException, SAXException {
036        try {
037            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
038            Source schemaSource = null;
039            schemaSource = new StreamSource(getFileContents());
040            Schema schema = null;
041            schema = factory.newSchema(schemaSource);
042            Validator validator = schema.newValidator();
043            validator.setErrorHandler(new XmlErrorHandler());
044            validator.validate(new StreamSource(inputStream));
045            return true;
046        }
047        catch(Exception ex){
048            //TODO: logging required
049        }
050        return false;
051    }
052
053    /**
054     *  This method returns fileContent as InputStream.
055     *  This method get the fileContent based on Location file schema.
056     * @return locationXmlFile.
057     */
058    private InputStream getFileContents(){
059        byte[] locationByteArray;
060        ByteArrayInputStream locationXmlFile=null;
061        try{
062            locationByteArray = IOUtils.toByteArray(getClass().getResourceAsStream(LOCATION_SCHEMA_FILE));
063            locationXmlFile = new ByteArrayInputStream(locationByteArray);
064        }
065        catch(Exception e){
066            //TODO: logging required
067        }
068        return locationXmlFile;
069    }
070
071}