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 org.apache.commons.httpclient.HttpClient;
|
10
|
import org.apache.commons.httpclient.HttpMethod;
|
11
|
import org.apache.commons.httpclient.HttpStatus;
|
12
|
import org.apache.commons.httpclient.methods.GetMethod;
|
13
|
import org.apache.commons.io.IOUtils;
|
14
|
import org.apache.commons.lang3.StringUtils;
|
15
|
|
16
|
public class HttpListIterator implements Iterator<String> {
|
17
|
|
18
|
final HttpClient client = new HttpClient();
|
19
|
|
20
|
private String baseUrl;
|
21
|
private String currentLine;
|
22
|
private BufferedReader reader;
|
23
|
|
24
|
public HttpListIterator(final String baseUrl, final String listAddress) {
|
25
|
try {
|
26
|
this.baseUrl = baseUrl;
|
27
|
this.reader = new BufferedReader(new StringReader(download(listAddress)));
|
28
|
this.currentLine = reader.readLine();
|
29
|
} catch (Exception e) {
|
30
|
throw new RuntimeException("Error creating iterator", e);
|
31
|
}
|
32
|
}
|
33
|
|
34
|
@Override
|
35
|
public synchronized boolean hasNext() {
|
36
|
return StringUtils.isNotBlank(currentLine);
|
37
|
}
|
38
|
|
39
|
@Override
|
40
|
public synchronized String next() {
|
41
|
try {
|
42
|
if (StringUtils.isNotBlank(currentLine)) {
|
43
|
return download(baseUrl + currentLine);
|
44
|
} else {
|
45
|
throw new RuntimeException("Iterator has reached the end");
|
46
|
}
|
47
|
} finally {
|
48
|
try {
|
49
|
this.currentLine = reader.readLine();
|
50
|
} catch (IOException e) {
|
51
|
throw new RuntimeException("Error obtaining next element " + currentLine, e);
|
52
|
}
|
53
|
}
|
54
|
}
|
55
|
|
56
|
private String download(final String url) {
|
57
|
try {
|
58
|
final HttpMethod method = new GetMethod(url);
|
59
|
final int responseCode = client.executeMethod(method);
|
60
|
if (responseCode == HttpStatus.SC_OK) {
|
61
|
return IOUtils.toString(new BufferedInputStream(method.getResponseBodyAsStream()));
|
62
|
} else {
|
63
|
throw new RuntimeException("Error " + responseCode + " dowloading url: " + url);
|
64
|
}
|
65
|
} catch (IOException e) {
|
66
|
throw new RuntimeException("Error dowloading url: " + url);
|
67
|
}
|
68
|
}
|
69
|
|
70
|
@Override
|
71
|
public void remove() {}
|
72
|
|
73
|
}
|