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
21
22 public class OlePatronXMLSchemaValidator {
23
24 private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePatronXMLSchemaValidator.class);
25 private static final String PATRON_SCHEMA_FILE = "olePatronRecord.xsd";
26
27
28
29
30
31
32
33
34
35
36 public boolean validateContentsAgainstSchema(InputStream inputStream)
37 throws ParseException, IOException, SAXException {
38 try {
39 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
40 Source schemaSource = null;
41 schemaSource = new StreamSource(getFileContents());
42 Schema schema = null;
43 schema = factory.newSchema(schemaSource);
44 Validator validator = schema.newValidator();
45 validator.setErrorHandler(new XmlErrorHandler());
46 validator.validate(new StreamSource(inputStream));
47 return true;
48 }
49 catch(Exception ex){
50 LOG.error(ex.getMessage());
51 }
52 return false;
53 }
54
55
56
57
58
59
60 private InputStream getFileContents(){
61 byte[] patronByteArray;
62 ByteArrayInputStream patronXmlFile=null;
63 try{
64 patronByteArray = IOUtils.toByteArray(getClass().getResourceAsStream(PATRON_SCHEMA_FILE));
65 patronXmlFile = new ByteArrayInputStream(patronByteArray);
66 }
67 catch(Exception e){
68 LOG.error(e.getMessage());
69 }
70 return patronXmlFile;
71 }
72
73 }