Project

General

Profile

1
package eu.dnetlib.data.collector.plugins.oai;
2

    
3
import java.io.StringReader;
4
import java.io.UnsupportedEncodingException;
5
import java.net.URLEncoder;
6
import java.util.Iterator;
7
import java.util.Queue;
8
import java.util.concurrent.PriorityBlockingQueue;
9

    
10
import eu.dnetlib.data.collector.plugins.oai.engine.HttpConnector;
11
import eu.dnetlib.data.collector.plugins.oai.engine.XmlCleaner;
12
import eu.dnetlib.rmi.data.CollectorServiceException;
13
import org.apache.commons.logging.Log;
14
import org.apache.commons.logging.LogFactory;
15
import org.dom4j.Document;
16
import org.dom4j.DocumentException;
17
import org.dom4j.Node;
18
import org.dom4j.io.SAXReader;
19

    
20
public class OaiIterator implements Iterator<String> {
21

    
22
	private static final Log log = LogFactory.getLog(OaiIterator.class); // NOPMD by marko on 11/24/08 5:02 PM
23

    
24
	private Queue<String> queue = new PriorityBlockingQueue<String>();
25
	private SAXReader reader = new SAXReader();
26

    
27
	private String baseUrl;
28
	private String set;
29
	private String mdFormat;
30
	private String fromDate;
31
	private String untilDate;
32
	private String token;
33
	private boolean started;
34
	private HttpConnector httpConnector;
35

    
36
	public OaiIterator(final String baseUrl,
37
			final String mdFormat,
38
			final String set,
39
			final String fromDate,
40
			final String untilDate,
41
			final HttpConnector httpConnector) {
42
		this.baseUrl = baseUrl;
43
		this.mdFormat = mdFormat;
44
		this.set = set;
45
		this.fromDate = fromDate;
46
		this.untilDate = untilDate;
47
		this.started = false;
48
		this.httpConnector = httpConnector;
49
	}
50

    
51
	private void verifyStarted() {
52
		if (!this.started) {
53
			this.started = true;
54
			try {
55
				this.token = firstPage();
56
			} catch (CollectorServiceException e) {
57
				throw new RuntimeException(e);
58
			}
59
		}
60
	}
61

    
62
	@Override
63
	public boolean hasNext() {
64
		synchronized (queue) {
65
			verifyStarted();
66
			return !queue.isEmpty();
67
		}
68
	}
69

    
70
	@Override
71
	public String next() {
72
		synchronized (queue) {
73
			verifyStarted();
74
			final String res = queue.poll();
75
			while (queue.isEmpty() && (token != null) && !token.isEmpty()) {
76
				try {
77
					token = otherPages(token);
78
				} catch (CollectorServiceException e) {
79
					throw new RuntimeException(e);
80
				}
81
			}
82
			return res;
83
		}
84
	}
85

    
86
	@Override
87
	public void remove() {
88
	}
89

    
90
	private String firstPage() throws CollectorServiceException {
91
		try {
92
			String url = baseUrl + "?verb=ListRecords&metadataPrefix=" + URLEncoder.encode(mdFormat, "UTF-8");
93
			if ((set != null) && !set.isEmpty()) {
94
				url += "&set=" + URLEncoder.encode(set, "UTF-8");
95
			}
96
            if ((fromDate != null) && fromDate.matches("\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}Z)?+")) {
97
                url += "&from=" + URLEncoder.encode(fromDate, "UTF-8");
98
			}
99
            if ((untilDate != null) && untilDate.matches("\\d{4}-\\d{2}-\\d{2}(T\\d{2}:\\d{2}:\\d{2}Z)?+")) {
100
                url += "&until=" + URLEncoder.encode(untilDate, "UTF-8");
101
			}
102
			log.info("Start harvesting using url: " + url);
103

    
104
			return downloadPage(url);
105
		} catch (UnsupportedEncodingException e) {
106
			throw new CollectorServiceException(e);
107
		}
108
	}
109

    
110
	private String otherPages(final String resumptionToken) throws CollectorServiceException {
111
		try {
112
			return downloadPage(baseUrl + "?verb=ListRecords&resumptionToken=" + URLEncoder.encode(resumptionToken, "UTF-8"));
113
		} catch (UnsupportedEncodingException e) {
114
			throw new CollectorServiceException(e);
115
		}
116
	}
117

    
118
	private String downloadPage(final String url) throws CollectorServiceException {
119

    
120
		final String xml = httpConnector.getInputSource(url);
121

    
122
		Document doc;
123
		try {
124
			doc = reader.read(new StringReader(xml));
125
		} catch (DocumentException e) {
126
			log.warn("Error parsing xml, I try to clean it: " + xml, e);
127
			final String cleaned = XmlCleaner.cleanAllEntities(xml);
128
			try {
129
				doc = reader.read(new StringReader(cleaned));
130
			} catch (DocumentException e1) {
131
				throw new CollectorServiceException("Error parsing cleaned document:" + cleaned, e1);
132
			}
133
		}
134

    
135
		final Node errorNode = doc.selectSingleNode("/*[local-name()='OAI-PMH']/*[local-name()='error']");
136
		if (errorNode != null) {
137
			final String code = errorNode.valueOf("@code");
138
			if ("noRecordsMatch".equalsIgnoreCase(code.trim())) {
139
				log.warn("noRecordsMatch for oai call: " + url);
140
				return null;
141
			} else {
142
				throw new CollectorServiceException(code + " - " + errorNode.getText());
143
			}
144
		}
145

    
146
		for (Object o : doc.selectNodes("//*[local-name()='ListRecords']/*[local-name()='record']")) {
147
			queue.add(((Node) o).asXML());
148
		}
149

    
150
		return doc.valueOf("//*[local-name()='resumptionToken']");
151

    
152
	}
153

    
154
}
(2-2/3)