001    package org.kuali.ole.ingest;
002    
003    import org.apache.commons.io.IOUtils;
004    import org.kuali.ole.exception.ParseException;
005    import org.kuali.ole.exception.XmlErrorHandler;
006    import org.xml.sax.SAXException;
007    
008    import javax.xml.XMLConstants;
009    import javax.xml.transform.Source;
010    import javax.xml.transform.stream.StreamSource;
011    import javax.xml.validation.Schema;
012    import javax.xml.validation.SchemaFactory;
013    import javax.xml.validation.Validator;
014    import java.io.ByteArrayInputStream;
015    import java.io.IOException;
016    import java.io.InputStream;
017    
018    /**
019     * ProfileXMLSchemaValidator is for validating ProfileAttributeSchema against W3C Xml Schema standards
020     */
021    public class ProfileXMLSchemaValidator {
022    
023        private static final String PROFILE_SCHEMA_FILE = "profileBuilder.xsd";
024    
025        /**
026         * This method returns True/False
027         * This method check the ProfileAttributeSchema against W3C Xml Schema,If it matches it return True else return False.
028         * @param inputStream
029         * @return  boolean
030         * @throws ParseException
031         * @throws IOException
032         * @throws 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 Profile schema file.
056         * @return  profileXmlFile
057         */
058        private InputStream getFileContents(){
059            byte[] profileByteArray;
060            ByteArrayInputStream profileXmlFile=null;
061            try{
062                    profileByteArray = IOUtils.toByteArray(getClass().getResourceAsStream(PROFILE_SCHEMA_FILE));
063                    profileXmlFile = new ByteArrayInputStream(profileByteArray);
064            }
065            catch(Exception e){
066              //TODO: logging required
067            }
068            return profileXmlFile;
069        }
070    }