1   package org.kuali.ole.ingest;
2   
3   import org.apache.commons.io.IOUtils;
4   import org.kuali.ole.exception.ParseException;
5   import org.kuali.ole.exception.XmlErrorHandler;
6   import org.xml.sax.SAXException;
7   
8   import javax.xml.XMLConstants;
9   import javax.xml.transform.Source;
10  import javax.xml.transform.stream.StreamSource;
11  import javax.xml.validation.Schema;
12  import javax.xml.validation.SchemaFactory;
13  import javax.xml.validation.Validator;
14  import java.io.ByteArrayInputStream;
15  import java.io.IOException;
16  import java.io.InputStream;
17  
18  
19  
20  
21  public class ProfileXMLSchemaValidator {
22  
23      private static final String PROFILE_SCHEMA_FILE = "profileBuilder.xsd";
24  
25      
26  
27  
28  
29  
30  
31  
32  
33  
34      public boolean validateContentsAgainstSchema(InputStream inputStream)
35              throws ParseException, IOException, SAXException {
36          try {
37                  SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
38                  Source schemaSource = null;
39                  schemaSource = new StreamSource(getFileContents());
40                  Schema schema = null;
41                  schema = factory.newSchema(schemaSource);
42                  Validator validator = schema.newValidator();
43                  validator.setErrorHandler(new XmlErrorHandler());
44                  validator.validate(new StreamSource(inputStream));
45                  return true;
46          }
47          catch(Exception ex){
48             
49          }
50          return false;
51      }
52  
53      
54  
55  
56  
57  
58      private InputStream getFileContents(){
59          byte[] profileByteArray;
60          ByteArrayInputStream profileXmlFile=null;
61          try{
62                  profileByteArray = IOUtils.toByteArray(getClass().getResourceAsStream(PROFILE_SCHEMA_FILE));
63                  profileXmlFile = new ByteArrayInputStream(profileByteArray);
64          }
65          catch(Exception e){
66            
67          }
68          return profileXmlFile;
69      }
70  }