1 package org.kuali.ole.ingest;
2
3 import org.apache.commons.io.IOUtils;
4 import org.kuali.ole.OLEConstants;
5 import org.kuali.ole.exception.ParseException;
6 import org.kuali.ole.exception.XmlErrorHandler;
7 import org.xml.sax.SAXException;
8
9 import javax.xml.XMLConstants;
10 import javax.xml.transform.Source;
11 import javax.xml.transform.stream.StreamSource;
12 import javax.xml.validation.Schema;
13 import javax.xml.validation.SchemaFactory;
14 import javax.xml.validation.Validator;
15 import java.io.ByteArrayInputStream;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.net.MalformedURLException;
19 import java.util.HashMap;
20 import java.util.Map;
21
22
23
24
25 public class OlePatronXMLSchemaValidator {
26
27 private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(OlePatronXMLSchemaValidator.class);
28 private static final String PATRON_SCHEMA_FILE = "olePatronRecord.xsd";
29
30
31
32
33
34
35
36
37
38
39 public Map validateContentsAgainstSchema(InputStream inputStream)
40 throws ParseException, IOException, SAXException {
41 Map validateResultMap = new HashMap();
42 try {
43 SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
44 Source schemaSource = null;
45 schemaSource = new StreamSource(getFileContents());
46 Schema schema = null;
47 schema = factory.newSchema(schemaSource);
48 Validator validator = schema.newValidator();
49 validator.setErrorHandler(new XmlErrorHandler());
50 validator.validate(new StreamSource(inputStream));
51 validateResultMap.put(OLEConstants.OlePatron.PATRON_XML_ISVALID, true);
52 validateResultMap.put(OLEConstants.OlePatron.PATRON_POLLERSERVICE_ERROR_MESSAGE,"");
53 return validateResultMap;
54 }
55 catch(Exception ex){
56 validateResultMap.put(OLEConstants.OlePatron.PATRON_XML_ISVALID, false);
57 validateResultMap.put(OLEConstants.OlePatron.PATRON_POLLERSERVICE_ERROR_MESSAGE,ex.getMessage());
58 LOG.error(ex.getMessage());
59 }
60 return validateResultMap;
61 }
62
63
64
65
66
67
68 private InputStream getFileContents(){
69 byte[] patronByteArray;
70 ByteArrayInputStream patronXmlFile=null;
71 try{
72 patronByteArray = IOUtils.toByteArray(getClass().getResourceAsStream(PATRON_SCHEMA_FILE));
73 patronXmlFile = new ByteArrayInputStream(patronByteArray);
74 }
75 catch(Exception e){
76 LOG.error(e.getMessage());
77 }
78 return patronXmlFile;
79 }
80
81 }