1
|
package eu.dnetlib.data.mdstore.modular;
|
2
|
|
3
|
import java.io.ByteArrayInputStream;
|
4
|
import java.util.HashMap;
|
5
|
import java.util.Map;
|
6
|
import java.util.Stack;
|
7
|
|
8
|
import javax.xml.stream.XMLInputFactory;
|
9
|
import javax.xml.stream.XMLStreamConstants;
|
10
|
import javax.xml.stream.XMLStreamException;
|
11
|
import javax.xml.stream.XMLStreamReader;
|
12
|
|
13
|
/**
|
14
|
* This method outperforms SimpleRecordParser by a vast amount, especially since we are just getting stuff in the
|
15
|
* header.
|
16
|
*
|
17
|
* @author marko
|
18
|
*
|
19
|
*/
|
20
|
public class StreamingRecordParser implements RecordParser {
|
21
|
|
22
|
private long ts;
|
23
|
|
24
|
@Override
|
25
|
public Map<String, String> parseRecord(String record) {
|
26
|
|
27
|
try {
|
28
|
XMLInputFactory factory = XMLInputFactory.newInstance();
|
29
|
XMLStreamReader parser = factory.createXMLStreamReader(new ByteArrayInputStream(record.getBytes()));
|
30
|
|
31
|
HashMap<String, String> res = new HashMap<String, String>();
|
32
|
res.put("timestamp", String.valueOf(getTimestamp()));
|
33
|
|
34
|
Stack<String> elementStack = new Stack<String>();
|
35
|
elementStack.push("/");
|
36
|
|
37
|
while (parser.hasNext()) {
|
38
|
int event = parser.next();
|
39
|
|
40
|
if (event == XMLStreamConstants.END_ELEMENT) {
|
41
|
elementStack.pop();
|
42
|
} else if (event == XMLStreamConstants.START_ELEMENT) {
|
43
|
final String localName = parser.getLocalName();
|
44
|
elementStack.push(localName);
|
45
|
|
46
|
if ("objIdentifier".equals(localName)) {
|
47
|
parser.next();
|
48
|
|
49
|
res.put("id", parser.getText().trim());
|
50
|
|
51
|
} else if ("identifier".equals(localName) && "efgEntity".equals(grandParent(elementStack))) {
|
52
|
if (!res.containsKey("originalId")) {
|
53
|
parser.next();
|
54
|
// log.info("ZZZZZZ OK: found identifier at right depth " + elementStack);
|
55
|
res.put("originalId", parser.getText().trim());
|
56
|
}
|
57
|
}
|
58
|
|
59
|
else if ("identifier".equals(localName)) {
|
60
|
|
61
|
// log.info("ZZZZZZ: found identifier not at right depth " + elementStack + " grand parent " + grandParent(elementStack));
|
62
|
}
|
63
|
|
64
|
if (res.containsKey("id") && res.containsKey("originalId"))
|
65
|
return res;
|
66
|
}
|
67
|
}
|
68
|
return res;
|
69
|
} catch (XMLStreamException e) {
|
70
|
throw new IllegalStateException(e);
|
71
|
}
|
72
|
|
73
|
}
|
74
|
|
75
|
private String grandParent(Stack<String> elementStack) {
|
76
|
if (elementStack.size() <= 3)
|
77
|
return "";
|
78
|
return elementStack.get(elementStack.size() - 3);
|
79
|
}
|
80
|
|
81
|
@Override
|
82
|
public void setTimestamp(final long ts) {
|
83
|
this.ts = ts;
|
84
|
}
|
85
|
|
86
|
@Override
|
87
|
public long getTimestamp() {
|
88
|
return ts;
|
89
|
}
|
90
|
|
91
|
}
|