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 import javax.xml.parsers.SAXParser;
31
32 import org.owasp.dependencycheck.utils.FileUtils;
33 import org.owasp.dependencycheck.utils.XmlUtils;
34
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.xml.sax.InputSource;
38 import org.xml.sax.SAXException;
39 import org.xml.sax.XMLReader;
40
41
42
43
44
45
46 @ThreadSafe
47 public class GrokParser {
48
49
50
51
52 private static final Logger LOGGER = LoggerFactory.getLogger(GrokParser.class);
53
54
55
56 public static final String GROK_SCHEMA = "schema/grok-assembly.1.0.xsd";
57
58
59
60
61
62
63
64
65 @SuppressFBWarnings(justification = "try with resources will clean up the input stream", value = {"OBL_UNSATISFIED_OBLIGATION"})
66 public AssemblyData parse(File file) throws GrokParseException {
67 try (FileInputStream fis = new FileInputStream(file)) {
68 return parse(fis);
69 } catch (IOException ex) {
70 LOGGER.debug("", ex);
71 throw new GrokParseException(ex);
72 }
73 }
74
75
76
77
78
79
80
81
82 public AssemblyData parse(InputStream inputStream) throws GrokParseException {
83 try (InputStream schema = FileUtils.getResourceAsStream(GROK_SCHEMA)) {
84 final GrokHandler handler = new GrokHandler();
85 final SAXParser saxParser = XmlUtils.buildSecureSaxParser(schema);
86 final XMLReader xmlReader = saxParser.getXMLReader();
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 }