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 * KrmsXMLSchemaValidator is used to validate the xsd schema for KRMS builder.
020 */
021 public class KrmsXMLSchemaValidator {
022
023 private static final String KRMS_SCHEMA_FILE = "license.xsd";
024
025 /**
026 * This method return True/False.
027 * This method checks fileContent schema with W3 Xml schema standards,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 will return fileContents based on KRMS Schema File
055 * @return profileXmlFile.
056 */
057 private InputStream getFileContents(){
058 byte[] profileByteArray;
059 ByteArrayInputStream profileXmlFile=null;
060 try{
061 profileByteArray = IOUtils.toByteArray(getClass().getResourceAsStream(KRMS_SCHEMA_FILE));
062 profileXmlFile = new ByteArrayInputStream(profileByteArray);
063 }
064 catch(Exception e){
065 //TODO: logging required
066 }
067 return profileXmlFile;
068 }
069 }