1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.owasp.dependencycheck.data.update.nvd.api;
19
20 import com.fasterxml.jackson.core.JsonParser;
21 import com.fasterxml.jackson.core.JsonToken;
22 import com.fasterxml.jackson.databind.ObjectMapper;
23 import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
24 import io.github.jeremylong.openvulnerability.client.nvd.DefCveItem;
25 import org.apache.commons.io.IOUtils;
26
27 import java.io.IOException;
28 import java.io.InputStream;
29
30 public class CveApiJson20CveItemSource implements CveItemSource<DefCveItem> {
31
32
33
34
35 private final ObjectMapper mapper;
36
37
38
39 private final InputStream inputStream;
40
41
42
43 private final JsonParser jsonParser;
44
45
46
47 private DefCveItem currentItem;
48
49
50
51 private DefCveItem nextItem;
52
53
54
55
56
57
58
59
60 public CveApiJson20CveItemSource(InputStream inputStream) throws IOException {
61 mapper = new ObjectMapper();
62 mapper.registerModule(new JavaTimeModule());
63 this.inputStream = inputStream;
64 jsonParser = mapper.getFactory().createParser(inputStream);
65
66 JsonToken token = null;
67 do {
68 token = jsonParser.nextToken();
69 if (token == JsonToken.FIELD_NAME) {
70 final String fieldName = jsonParser.currentName();
71 if ("vulnerabilities".equals(fieldName) && (jsonParser.nextToken() == JsonToken.START_ARRAY)) {
72 nextItem = readItem(jsonParser);
73 }
74 }
75 } while (token != null && nextItem == null);
76 }
77
78 @Override
79 public void close() throws Exception {
80 IOUtils.closeQuietly(jsonParser, inputStream);
81 }
82
83 @Override
84 public boolean hasNext() {
85 return nextItem != null;
86 }
87
88 @Override
89 public DefCveItem next() throws IOException {
90 currentItem = nextItem;
91 nextItem = readItem(jsonParser);
92 return currentItem;
93 }
94
95 private DefCveItem readItem(JsonParser jsonParser) throws IOException {
96 if (jsonParser.nextToken() == JsonToken.START_OBJECT) {
97 return mapper.readValue(jsonParser, DefCveItem.class);
98 }
99 return null;
100 }
101 }