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
			if ((fromDate != null) && fromDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
94
				url += "&from=" + URLEncoder.encode(fromDate,"UTF-8");
95
			}
96
			if ((untilDate != null) && untilDate.matches("\\d{4}-\\d{2}-\\d{2}")) {
97
				url += "&until=" + URLEncoder.encode(untilDate,"UTF-8");
98
			}
99
			log.info("Start harvesting using url: " + url);
100
	
101
			return downloadPage(url);
102
		} catch(UnsupportedEncodingException e) {
103
			throw new CollectorServiceException(e);
104
		}
105
	}
106

    
107
	private String extractResumptionToken(final String xml) {
108

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

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

    
119

    
120
	}
121

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

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

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

    
149
        final Node errorNode = doc.selectSingleNode("/*[local-name()='OAI-PMH']/*[local-name()='error']");
150
        if (errorNode != null) {
151
            final String code = errorNode.valueOf("@code");
152
            if ("noRecordsMatch".equalsIgnoreCase(code.trim())) {
153
                log.warn("noRecordsMatch for oai call: " + url);
154
                return null;
155
            } else {
156
                throw new CollectorServiceException(code + " - " + errorNode.getText());
157
            }
158
        }
159

    
160
        for (Object o : doc.selectNodes("//*[local-name()='ListRecords']/*[local-name()='record']")) {
161
            queue.add(((Node) o).asXML());
162
        }
163

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

    
166
    }
167

    
168
}
(2-2/3)