1
|
package eu.dnetlib.msro.workers.aggregation.collect.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 org.apache.commons.io.IOUtils;
|
10
|
import org.apache.commons.lang3.StringUtils;
|
11
|
import org.apache.http.HttpStatus;
|
12
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
13
|
import org.apache.http.client.methods.HttpGet;
|
14
|
import org.apache.http.impl.client.CloseableHttpClient;
|
15
|
import org.apache.http.impl.client.HttpClients;
|
16
|
|
17
|
import eu.dnetlib.msro.exceptions.CollectorServiceRuntimeException;
|
18
|
|
19
|
public class HttpListIterator implements Iterator<String> {
|
20
|
|
21
|
private final CloseableHttpClient client = HttpClients.createDefault();
|
22
|
|
23
|
private String baseUrl;
|
24
|
private String currentLine;
|
25
|
private BufferedReader reader;
|
26
|
|
27
|
public HttpListIterator(final String baseUrl, final String listAddress) {
|
28
|
try {
|
29
|
this.baseUrl = baseUrl;
|
30
|
reader = new BufferedReader(new StringReader(download(listAddress)));
|
31
|
currentLine = reader.readLine();
|
32
|
} catch (final Exception e) {
|
33
|
throw new CollectorServiceRuntimeException("Error creating iterator", e);
|
34
|
}
|
35
|
}
|
36
|
|
37
|
@Override
|
38
|
public synchronized boolean hasNext() {
|
39
|
return StringUtils.isNotBlank(currentLine);
|
40
|
}
|
41
|
|
42
|
@Override
|
43
|
public synchronized String next() {
|
44
|
try {
|
45
|
if (StringUtils.isNotBlank(currentLine)) {
|
46
|
return download(baseUrl + currentLine);
|
47
|
} else {
|
48
|
throw new CollectorServiceRuntimeException("Iterator has reached the end");
|
49
|
}
|
50
|
} finally {
|
51
|
try {
|
52
|
currentLine = reader.readLine();
|
53
|
} catch (final IOException e) {
|
54
|
throw new CollectorServiceRuntimeException("Error obtaining next element " + currentLine, e);
|
55
|
}
|
56
|
}
|
57
|
}
|
58
|
|
59
|
private String download(final String url) {
|
60
|
final HttpGet method = new HttpGet(url);
|
61
|
|
62
|
try (CloseableHttpResponse response = client.execute(method)) {
|
63
|
final int statusCode = response.getStatusLine().getStatusCode();
|
64
|
|
65
|
if (HttpStatus.SC_OK == statusCode) {
|
66
|
return IOUtils.toString(new BufferedInputStream(response.getEntity().getContent()));
|
67
|
} else {
|
68
|
throw new CollectorServiceRuntimeException("Error " + statusCode + " dowloading url: " + url);
|
69
|
}
|
70
|
|
71
|
} catch (final IOException e) {
|
72
|
throw new CollectorServiceRuntimeException("Error downloading url: " + url);
|
73
|
}
|
74
|
}
|
75
|
|
76
|
@Override
|
77
|
public void remove() {
|
78
|
throw new UnsupportedOperationException();
|
79
|
}
|
80
|
|
81
|
}
|