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   * This class provides schema validation for uploaded location xml
20   */
21  public class OleLocationXMLSchemaValidator {
22      //TODO: refactor the validateContentsAgainstSchema method to take only 1 parameter which is the file content.
23      private static final String LOCATION_SCHEMA_FILE = "locations.xsd";
24  
25      /**
26       *  This method returns True/False.
27       *  This method  validate the inputStream content with W3C Xml Schema standard,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 Location file schema.
56       * @return locationXmlFile.
57       */
58      private InputStream getFileContents(){
59          byte[] locationByteArray;
60          ByteArrayInputStream locationXmlFile=null;
61          try{
62              locationByteArray = IOUtils.toByteArray(getClass().getResourceAsStream(LOCATION_SCHEMA_FILE));
63              locationXmlFile = new ByteArrayInputStream(locationByteArray);
64          }
65          catch(Exception e){
66              //TODO: logging required
67          }
68          return locationXmlFile;
69      }
70  
71  }