1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.jboss.as.quickstart.xml;
18
19 import java.io.BufferedReader;
20 import java.io.ByteArrayInputStream;
21 import java.io.CharArrayReader;
22 import java.io.InputStream;
23 import java.io.InputStreamReader;
24 import java.net.URL;
25 import java.util.List;
26
27 import javax.inject.Inject;
28 import javax.xml.transform.Source;
29 import javax.xml.transform.stream.StreamSource;
30 import javax.xml.validation.SchemaFactory;
31 import javax.xml.validation.Validator;
32
33
34
35
36
37
38
39
40 public abstract class XMLParser {
41
42 @Inject
43 private Errors errorHolder;
44
45 public List<Book> parse(InputStream is) throws Exception {
46
47
48
49 StringBuffer xmlFile = new StringBuffer();
50 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
51 String line = null;
52 while ((line = bufferedReader.readLine()) != null) {
53 xmlFile.append(line);
54 }
55 String xml = xmlFile.toString();
56
57 try {
58 URL schema = Resources.getResource("/catalog.xsd");
59 Validator validator = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema").newSchema(schema)
60 .newValidator();
61 Source source = new StreamSource(new CharArrayReader(xml.toCharArray()));
62 validator.validate(source);
63 } catch (Exception e) {
64 this.errorHolder.addErrorMessage("Validation Error", e);
65 return null;
66 }
67
68 ByteArrayInputStream bais = new ByteArrayInputStream(xml.getBytes());
69
70 return parseInternal(bais);
71 }
72
73
74
75
76
77
78
79 protected abstract List<Book> parseInternal(InputStream is) throws Exception;
80
81 }