1 package net.sf.layoutParser.util.xml.validation;
2
3 import java.io.IOException;
4
5 import javax.xml.parsers.ParserConfigurationException;
6 import javax.xml.parsers.SAXParser;
7 import javax.xml.parsers.SAXParserFactory;
8
9 import net.sf.layoutParser.build.BuilderException;
10 import net.sf.layoutParser.exception.ExceptionKey;
11
12 import org.xml.sax.SAXException;
13 import org.xml.sax.SAXParseException;
14 import org.xml.sax.helpers.DefaultHandler;
15
16
17
18
19
20
21
22
23 public abstract class XsdChecker {
24
25
26
27 public static final String XMLSCHEMA = "http://www.w3.org/2001/XMLSchema";
28
29
30
31
32 public static final String SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
33
34
35
36
37
38 public static void checkLayout(String fileName, String xsdFileName) throws BuilderException {
39 SAXParser saxParser = null;
40
41 try {
42 SAXParserFactory f = SAXParserFactory.newInstance();
43 f.setNamespaceAware(true);
44 f.setValidating(true);
45
46 saxParser = f.newSAXParser();
47 saxParser.setProperty( SCHEMA_LANGUAGE, XMLSCHEMA);
48 saxParser.setProperty(
49 "http://apache.org/xml/properties/schema/external-schemaLocation",
50 " http://layoutparser.sourceforge.net/ " + Thread.currentThread().getContextClassLoader().getResource(xsdFileName).toExternalForm());
51
52 saxParser.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName), new LayoutErrorHandler());
53 } catch (SAXException e) {
54 throw new BuilderException(ExceptionKey.SCHEMA_CHECK, new Object[]{fileName}, e);
55 } catch (IOException e) {
56 throw new BuilderException(ExceptionKey.FILE_NOT_FOUND, new Object[]{fileName}, e);
57 } catch (ParserConfigurationException e) {
58 throw new BuilderException(e);
59 }
60 }
61
62
63
64
65
66
67
68
69 private static class LayoutErrorHandler extends DefaultHandler {
70 public void warning(SAXParseException e) throws SAXException {
71 System.out.println("Warning: ");
72 printInfo(e);
73 }
74
75 public void error(SAXParseException e) throws SAXException {
76 throw e;
77 }
78
79 public void fatalError(SAXParseException e) throws SAXException {
80 throw e;
81 }
82
83 private void printInfo(SAXParseException e) {
84 System.out.println(" Public ID: " + e.getPublicId());
85 System.out.println(" System ID: " + e.getSystemId());
86 System.out.println(" Line number: " + e.getLineNumber());
87 System.out.println(" Column number: " + e.getColumnNumber());
88 System.out.println(" Message: " + e.getMessage());
89 }
90 }
91 }