Project

General

Profile

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

    
3
import java.io.BufferedInputStream;
4
import java.io.BufferedReader;
5
import java.io.IOException;
6
import java.io.StringReader;
7
import java.util.Iterator;
8

    
9
import eu.dnetlib.data.collector.plugins.HttpConnector;
10
import eu.dnetlib.data.collector.rmi.CollectorServiceException;
11
import org.apache.commons.io.IOUtils;
12
import org.apache.commons.lang3.StringUtils;
13

    
14
public class HttpListIterator implements Iterator<String> {
15

    
16
	private HttpConnector httpConnector;
17

    
18
	private String baseUrl;
19
	private String currentLine;
20
	private BufferedReader reader;
21

    
22
	public HttpListIterator(final String baseUrl, final String listAddress, final HttpConnector httpConnector) {
23
		this.httpConnector = httpConnector;
24
		this.baseUrl = baseUrl;
25
		try {
26
			this.reader = new BufferedReader(new StringReader(download(listAddress)));
27
			this.currentLine = reader.readLine();
28
		} catch (Exception e) {
29
			throw new RuntimeException("Error creating iterator", e);
30
		}
31
	}
32

    
33
	@Override
34
	public synchronized boolean hasNext() {
35
		return StringUtils.isNotBlank(currentLine);
36
	}
37

    
38
	@Override
39
	public synchronized String next() {
40
		try {
41
			if (StringUtils.isNotBlank(currentLine)) {
42
				return download(baseUrl + currentLine);
43
			} else {
44
				throw new RuntimeException("Iterator has reached the end");
45
			}
46
		} finally {
47
			try {
48
				this.currentLine = reader.readLine();
49
			} catch (IOException e) {
50
				throw new RuntimeException("Error obtaining next element " + currentLine, e);
51
			}
52
		}
53
	}
54

    
55
	private String download(final String url) {
56
		try {
57
			return IOUtils.toString(new BufferedInputStream(httpConnector.getInputSourceAsStream(url)));
58
		} catch(Exception e) {
59
			throw new RuntimeException(String.format("Error downloading url: %s, error: %s", url, e.getMessage()));
60
		}
61
	}
62

    
63
	@Override
64
	public void remove() {}
65

    
66
	public HttpConnector getHttpConnector() {
67
		return httpConnector;
68
	}
69

    
70
	public void setHttpConnector(final HttpConnector httpConnector) {
71
		this.httpConnector = httpConnector;
72
	}
73
}
(2-2/2)