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  import java.net.MalformedURLException;
18  
19  /**
20   * OlePatronXMLSchemaValidator is for schema validation against W3C Xml Schema standards
21   */
22  public class OlePatronXMLSchemaValidator {
23      //TODO: refactor the validateContentsAgainstSchema method to take only 1 parameter which is the file content.
24      private static final String PATRON_SCHEMA_FILE = "olePatronRecord.xsd";
25  
26      /**
27       *   This method returns True/False.
28       *   This method validate the patron xml schema against W3C Xml Schema standards,If it matches it return True else return False.
29       * @param inputStream
30       * @return  boolean
31       * @throws ParseException
32       * @throws IOException
33       * @throws SAXException
34       */
35      public boolean validateContentsAgainstSchema(InputStream inputStream)
36              throws ParseException, IOException, SAXException {
37          try {
38              SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
39              Source schemaSource = null;
40              schemaSource = new StreamSource(getFileContents());
41              Schema schema = null;
42              schema = factory.newSchema(schemaSource);
43              Validator validator = schema.newValidator();
44              validator.setErrorHandler(new XmlErrorHandler());
45              validator.validate(new StreamSource(inputStream));
46              return true;
47          }
48          catch(Exception ex){
49              //TODO: logging required
50          }
51          return false;
52      }
53  
54      /**
55       *  This method returns fileContent as InputStream.
56       *  This method get the fileContent based on Patron schema file.
57       * @return  patronXmlFile
58       */
59      private InputStream getFileContents(){
60          byte[] patronByteArray;
61          ByteArrayInputStream patronXmlFile=null;
62          try{
63              patronByteArray = IOUtils.toByteArray(getClass().getResourceAsStream(PATRON_SCHEMA_FILE));
64              patronXmlFile = new ByteArrayInputStream(patronByteArray);
65          }
66          catch(Exception e){
67              //TODO: logging required
68          }
69          return patronXmlFile;
70      }
71  
72  }