Project

General

Profile

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

    
3
import org.apache.commons.io.IOUtils;
4
import org.apache.commons.lang3.StringUtils;
5
import org.apache.http.HttpStatus;
6
import org.apache.http.client.methods.CloseableHttpResponse;
7
import org.apache.http.client.methods.HttpGet;
8
import org.apache.http.impl.client.CloseableHttpClient;
9
import org.apache.http.impl.client.HttpClients;
10

    
11
import java.io.BufferedInputStream;
12
import java.io.BufferedReader;
13
import java.io.IOException;
14
import java.io.StringReader;
15
import java.util.Iterator;
16

    
17
public class HttpListIterator implements Iterator<String> {
18

    
19
	final CloseableHttpClient client = HttpClients.createDefault();
20

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

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

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

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

    
57
	private String download(final String url) {
58
		try(CloseableHttpResponse response = client.execute(new HttpGet(url))) {
59

    
60
			final int responseCode = response.getStatusLine().getStatusCode();
61

    
62
			if (responseCode == HttpStatus.SC_OK) {
63
				return IOUtils.toString(new BufferedInputStream(response.getEntity().getContent()));
64
			} else {
65
				throw new RuntimeException("Error " + responseCode + " dowloading url: " + url);
66
			}
67

    
68
		} catch (IOException e) {
69
			throw new RuntimeException("Error dowloading url: " + url, e);
70
		}
71
	}
72

    
73
	@Override
74
	public void remove() {}
75

    
76
}
(2-2/2)