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 org.apache.commons.lang3.StringUtils;
11
import org.apache.commons.logging.Log;
12
import org.apache.commons.logging.LogFactory;
13
import org.dom4j.Document;
14
import org.dom4j.DocumentException;
15
import org.dom4j.Node;
16
import org.dom4j.io.SAXReader;
17

    
18
import eu.dnetlib.data.collector.plugins.HttpConnector;
19
import eu.dnetlib.data.collector.rmi.CollectorServiceException;
20

    
21
import eu.dnetlib.data.collector.plugins.oai.engine.XmlCleaner;
22

    
23
public class OaiIterator implements Iterator<String> {
24

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

    
27
	private Queue<String> queue = new PriorityBlockingQueue<String>();
28
	private SAXReader reader = new SAXReader();
29

    
30
	private String baseUrl;
31
	private String set;
32
	private String mdFormat;
33
	private String fromDate;
34
	private String untilDate;
35
	private String token;
36
	private boolean started;
37
	private HttpConnector httpConnector;
38
	private String prev_token = null;
39

    
40
	public OaiIterator(final String baseUrl, final String mdFormat, final String set, final String fromDate, final String untilDate, final HttpConnector httpConnector) {
41
		this.baseUrl = baseUrl;
42
		this.mdFormat = mdFormat;
43
		this.set = set;
44
		this.fromDate = fromDate;
45
		this.untilDate = untilDate;
46
		this.started = false;
47
		this.httpConnector = httpConnector;
48
	}
49
	
50
	private void verifyStarted() {
51
		if (!this.started) {
52
			this.started = true;
53
			try {
54
				this.token = firstPage();
55
				prev_token = token;
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
					if(prev_token.equals(token)){
79
						throw new RuntimeException("OAI Iterator Exception: got the same resumption token twice");
80
					}
81
					prev_token = token;
82
				} catch (CollectorServiceException e) {
83
					throw new RuntimeException(e);
84
				}
85
			}
86
			return res;
87
		}
88
	}
89

    
90
	@Override
91
	public void remove() {}
92

    
93
	private String firstPage() throws CollectorServiceException {
94
		try {
95
			String url = baseUrl + "?verb=ListRecords&metadataPrefix=" + URLEncoder.encode(mdFormat,"UTF-8");
96
			if ((set != null) && !set.isEmpty()) {
97
				url += "&set=" + URLEncoder.encode(set,"UTF-8");
98
			}
99
			if ((fromDate != null) && fromDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
100
				url += "&from=" + URLEncoder.encode(fromDate,"UTF-8");
101
			}
102
			if ((untilDate != null) && untilDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
103
				url += "&until=" + URLEncoder.encode(untilDate,"UTF-8");
104
			}
105
			log.info("Start harvesting using url: " + url);
106
	
107
			return downloadPage(url);
108
		} catch(UnsupportedEncodingException e) {
109
			throw new CollectorServiceException(e);
110
		}
111
	}
112

    
113
	private String extractResumptionToken(final String xml) {
114

    
115
		final String s = StringUtils.substringAfter(xml, "<resumptionToken");
116
		if (s == null){
117
			return null;
118
		}
119

    
120
		final String result = StringUtils.substringBetween(s, ">", "</");
121
		if (result == null)
122
			return null;
123
		return  result.trim();
124

    
125

    
126
	}
127

    
128
	private String otherPages(final String resumptionToken) throws CollectorServiceException {
129
		try {
130
			return downloadPage(baseUrl + "?verb=ListRecords&resumptionToken=" + URLEncoder.encode(resumptionToken,"UTF-8"));
131
		} catch (UnsupportedEncodingException e) {
132
			throw new CollectorServiceException(e);
133
		}
134
	}
135

    
136
    private String downloadPage(final String url) throws CollectorServiceException {
137

    
138
        final String xml = httpConnector.getInputSource(url);
139
        Document doc;
140
        try {
141
            doc = reader.read(new StringReader(xml));
142
        } catch (DocumentException e) {
143
            log.warn("Error parsing xml, I try to clean it", e);
144
            final String cleaned = XmlCleaner.cleanAllEntities(xml);
145
            try {
146
                doc = reader.read(new StringReader(cleaned));
147
            } catch (DocumentException e1) {
148
                final String resumptionToken = extractResumptionToken(xml);
149
                if (resumptionToken == null)
150
                    throw new CollectorServiceException("Error parsing cleaned document", e1);
151
                return resumptionToken;
152
            }
153
        }
154

    
155
        final Node errorNode = doc.selectSingleNode("/*[local-name()='OAI-PMH']/*[local-name()='error']");
156
        if (errorNode != null) {
157
            final String code = errorNode.valueOf("@code");
158
            if ("noRecordsMatch".equalsIgnoreCase(code.trim())) {
159
                log.warn("noRecordsMatch for oai call: " + url);
160
                return null;
161
            } else {
162
                throw new CollectorServiceException(code + " - " + errorNode.getText());
163
            }
164
        }
165
		int added_records = 0;
166
        for (Object o : doc.selectNodes("//*[local-name()='ListRecords']/*[local-name()='record']")) {
167
            queue.add(((Node) o).asXML());
168
            added_records++;
169
        }
170
        if(added_records == 0){
171
        	throw new RuntimeException("OAI Iterator Exception: Empty records list for " + url);
172
		}
173

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

    
176
    }
177

    
178
}
(2-2/3)