Project

General

Profile

1
package eu.dnetlib.data.mdstore.utils;
2

    
3
import java.io.ByteArrayInputStream;
4
import java.util.Date;
5
import java.util.Stack;
6
import java.util.function.Function;
7
import javax.xml.stream.XMLInputFactory;
8
import javax.xml.stream.XMLStreamConstants;
9
import javax.xml.stream.XMLStreamException;
10
import javax.xml.stream.XMLStreamReader;
11

    
12
import eu.dnetlib.data.mdstore.model.MDStoreRecord;
13
import org.apache.commons.lang3.StringUtils;
14

    
15
/**
16
 * Created by claudio on 20/03/2017.
17
 */
18
public class RecordParser implements Function<String, MDStoreRecord> {
19

    
20
	public static final String OBJ_IDENTIFIER = "objIdentifier";
21
	public static final String IDENTIFIER = "identifier";
22

    
23
	private Long timestamp;
24

    
25
	private XMLInputFactory factory;
26

    
27
	public RecordParser() {
28
		factory = XMLInputFactory.newInstance();
29
		timestamp = null;
30
	}
31

    
32
	public RecordParser(final long timestamp) {
33
		factory = XMLInputFactory.newInstance();
34
		this.timestamp = timestamp;
35
	}
36

    
37
	@Override
38
	public MDStoreRecord apply(final String s) {
39
		try {
40
			final XMLStreamReader parser = factory.createXMLStreamReader(new ByteArrayInputStream(s.getBytes()));
41
			final Stack<String> elementStack = new Stack<>();
42
			elementStack.push("/");
43

    
44
			final MDStoreRecord res = MDStoreRecord.create()
45
					.setBody(s)
46
					.setTimestamp(timestamp != null ? timestamp : new Date().getTime());
47

    
48
			//System.out.println(res.getTimestamp());
49

    
50
			while (parser.hasNext()) {
51
				int event = parser.next();
52

    
53
				if (event == XMLStreamConstants.END_ELEMENT) {
54
					elementStack.pop();
55
				} else if (event == XMLStreamConstants.START_ELEMENT) {
56
					final String localName = parser.getLocalName();
57
					elementStack.push(localName);
58

    
59
					if (OBJ_IDENTIFIER.equals(localName)) {
60
						parser.next();
61
						res.setId(parser.getText().trim());
62

    
63
					} else if (IDENTIFIER.equals(localName)) {
64
						if (StringUtils.isBlank(res.getOriginalId())) {
65
							parser.next();
66
							res.setOriginalId(parser.getText().trim());
67
						}
68
					}
69
					if (StringUtils.isNotBlank(res.getId()) && StringUtils.isNotBlank(res.getOriginalId())) {
70
						return res;
71
					}
72
				}
73
			}
74
			return res;
75
		} catch (XMLStreamException e) {
76
			throw new IllegalStateException(e);
77
		}
78
	}
79
}
(5-5/5)