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.rmi.data.CollectorServiceRuntimeException;
10
import org.apache.commons.io.IOUtils;
11
import org.apache.commons.lang3.StringUtils;
12
import org.apache.http.HttpStatus;
13
import org.apache.http.client.methods.CloseableHttpResponse;
14
import org.apache.http.client.methods.HttpGet;
15
import org.apache.http.impl.client.HttpClients;
16
import org.apache.http.impl.client.CloseableHttpClient;
17

    
18
public class HttpListIterator implements Iterator<String> {
19

    
20
	private final CloseableHttpClient client = HttpClients.createDefault();
21

    
22
	private String baseUrl;
23
	private String currentLine;
24
	private BufferedReader reader;
25

    
26
	public HttpListIterator(final String baseUrl, final String listAddress) {
27
		try {
28
			this.baseUrl = baseUrl;
29
			this.reader = new BufferedReader(new StringReader(download(listAddress)));
30
			this.currentLine = reader.readLine();
31
		} catch (Exception e) {
32
			throw new CollectorServiceRuntimeException("Error creating iterator", e);
33
		}
34
	}
35

    
36
	@Override
37
	public synchronized boolean hasNext() {
38
		return StringUtils.isNotBlank(currentLine);
39
	}
40

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

    
58
	private String download(final String url) {
59
		final HttpGet method = new HttpGet(url);
60

    
61
		try(CloseableHttpResponse response = client.execute(method)) {
62
			int statusCode = response.getStatusLine().getStatusCode();
63

    
64
			if (HttpStatus.SC_OK == statusCode) {
65
				return IOUtils.toString(new BufferedInputStream(response.getEntity().getContent()));
66
			} else {
67
				throw new CollectorServiceRuntimeException("Error " + statusCode + " dowloading url: " + url);
68
			}
69

    
70
		} catch (IOException e) {
71
			throw new CollectorServiceRuntimeException("Error downloading url: " + url);
72
		}
73
	}
74

    
75
	@Override
76
	public void remove() {
77
		throw new UnsupportedOperationException();
78
	}
79

    
80
}
(2-2/2)