View Javadoc
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   * ProfileXMLSchemaValidator is for validating ProfileAttributeSchema against W3C Xml Schema standards
20   */
21  public class ProfileXMLSchemaValidator {
22  
23      private static final String PROFILE_SCHEMA_FILE = "profileBuilder.xsd";
24  
25      /**
26       * This method returns True/False
27       * This method check the ProfileAttributeSchema against W3C Xml Schema,If it matches it return True else return False.
28       * @param inputStream
29       * @return  boolean
30       * @throws org.kuali.ole.exception.ParseException
31       * @throws java.io.IOException
32       * @throws org.xml.sax.SAXException
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             //TODO: logging required
49          }
50          return false;
51      }
52  
53      /**
54       *  This method returns fileContent as InputStream.
55       *  This method get the fileContent based on Profile schema file.
56       * @return  profileXmlFile
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            //TODO: logging required
67          }
68          return profileXmlFile;
69      }
70  }