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

    
39
	public OaiIterator(final String baseUrl, final String mdFormat, final String set, final String fromDate, final String untilDate, final HttpConnector httpConnector) {
40
		this.baseUrl = baseUrl;
41
		this.mdFormat = mdFormat;
42
		this.set = set;
43
		this.fromDate = fromDate;
44
		this.untilDate = untilDate;
45
		this.started = false;
46
		this.httpConnector = httpConnector;
47
	}
48
	
49
	private void verifyStarted() {
50
		if (!this.started) {
51
			this.started = true;
52
			try {
53
				this.token = firstPage();
54
			} catch (CollectorServiceException e) {
55
				throw new RuntimeException(e);
56
			}
57
		}
58
	}
59

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

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

    
84
	@Override
85
	public void remove() {}
86

    
87
	private String firstPage() throws CollectorServiceException {
88
		try {
89
			String url = baseUrl + "?verb=ListRecords&metadataPrefix=" + URLEncoder.encode(mdFormat,"UTF-8");
90
			if ((set != null) && !set.isEmpty()) {
91
				url += "&set=" + URLEncoder.encode(set,"UTF-8");
92
			} 
93
			// http://www.openarchives.org/OAI/openarchivesprotocol.html#Dates , eg. 1957-03-20T20:30:00Z
94
			if ((fromDate != null) && (fromDate.matches("\\d{4}-\\d{2}-\\d{2}") || fromDate.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z"))  ) {
95
				url += "&from=" + URLEncoder.encode(fromDate,"UTF-8");
96
			}
97
			if ((untilDate != null) && (untilDate.matches("\\d{4}-\\d{2}-\\d{2}") || untilDate.matches("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z")) ) {
98
				url += "&until=" + URLEncoder.encode(untilDate,"UTF-8");
99
			}
100
			log.info("Start harvesting using url: " + url);
101
	
102
			return downloadPage(url);
103
		} catch(UnsupportedEncodingException e) {
104
			throw new CollectorServiceException(e);
105
		}
106
	}
107

    
108
	private String extractResumptionToken(final String xml) {
109

    
110
		final String s = StringUtils.substringAfter(xml, "<resumptionToken");
111
		if (s == null){
112
			return null;
113
		}
114

    
115
		final String result = StringUtils.substringBetween(s, ">", "</");
116
		if (result == null)
117
			return null;
118
		return  result.trim();
119

    
120

    
121
	}
122

    
123
	private String otherPages(final String resumptionToken) throws CollectorServiceException {
124
		try {
125
			return downloadPage(baseUrl + "?verb=ListRecords&resumptionToken=" + URLEncoder.encode(resumptionToken,"UTF-8"));
126
		} catch (UnsupportedEncodingException e) {
127
			throw new CollectorServiceException(e);
128
		}
129
	}
130

    
131
    private String downloadPage(final String url) throws CollectorServiceException {
132

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

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

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

    
171
    }
172

    
173
}
(2-2/3)