1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.owasp.dependencycheck.xml.assembly;
19
20 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21 import java.io.File;
22 import java.io.FileInputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.io.InputStreamReader;
26 import java.io.Reader;
27 import java.nio.charset.StandardCharsets;
28 import javax.annotation.concurrent.ThreadSafe;
29 import javax.xml.parsers.ParserConfigurationException;
30
31 import org.owasp.dependencycheck.utils.AutoCloseableInputSource;
32 import org.owasp.dependencycheck.utils.XmlUtils;
33
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.xml.sax.InputSource;
37 import org.xml.sax.SAXException;
38 import org.xml.sax.XMLReader;
39
40 import static org.owasp.dependencycheck.utils.AutoCloseableInputSource.fromResource;
41
42
43
44
45
46
47 @ThreadSafe
48 public class GrokParser {
49
50
51
52
53 private static final Logger LOGGER = LoggerFactory.getLogger(GrokParser.class);
54
55
56
57 public static final String GROK_SCHEMA = "schema/grok-assembly.1.0.xsd";
58
59
60
61
62
63
64
65
66 @SuppressFBWarnings(justification = "try with resources will clean up the input stream", value = {"OBL_UNSATISFIED_OBLIGATION"})
67 public AssemblyData parse(File file) throws GrokParseException {
68 try (FileInputStream fis = new FileInputStream(file)) {
69 return parse(fis);
70 } catch (IOException ex) {
71 LOGGER.debug("", ex);
72 throw new GrokParseException(ex);
73 }
74 }
75
76
77
78
79
80
81
82
83 public AssemblyData parse(InputStream inputStream) throws GrokParseException {
84 try (AutoCloseableInputSource schema = fromResource(GROK_SCHEMA)) {
85 final GrokHandler handler = new GrokHandler();
86 final XMLReader xmlReader = XmlUtils.buildSecureValidatingXmlReader(schema);
87 xmlReader.setErrorHandler(new GrokErrorHandler());
88 xmlReader.setContentHandler(handler);
89 try (Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) {
90 final InputSource in = new InputSource(reader);
91 xmlReader.parse(in);
92 return handler.getAssemblyData();
93 }
94 } catch (ParserConfigurationException | IOException ex) {
95 LOGGER.debug("", ex);
96 throw new GrokParseException(ex);
97 } catch (SAXException ex) {
98 if (ex.getMessage().contains("Cannot find the declaration of element 'assembly'.")) {
99 throw new GrokParseException("Malformed grok xml?", ex);
100 } else {
101 LOGGER.debug("", ex);
102 throw new GrokParseException(ex);
103 }
104 }
105 }
106 }