1
|
package eu.dnetlib.enabling.resultset.client;
|
2
|
|
3
|
import java.io.InputStream;
|
4
|
import java.util.List;
|
5
|
import java.util.stream.Collectors;
|
6
|
|
7
|
import com.google.gson.Gson;
|
8
|
|
9
|
import eu.dnetlib.enabling.resultset.ResultSetResponse;
|
10
|
import eu.dnetlib.rmi.common.ResultSetException;
|
11
|
import org.apache.commons.io.IOUtils;
|
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.CloseableHttpClient;
|
16
|
import org.apache.http.impl.client.HttpClients;
|
17
|
|
18
|
public class HttpResultSetClientIterator<T> extends AbstractResultSetClientIterator<T> {
|
19
|
|
20
|
private static final int PAGE_SIZE = 20;
|
21
|
|
22
|
private final String id;
|
23
|
private final String baseUrl;
|
24
|
private final Class<T> clazz;
|
25
|
|
26
|
private final CloseableHttpClient client = HttpClients.createDefault();
|
27
|
|
28
|
public HttpResultSetClientIterator(final String id, final String baseUrl, final Class<T> clazz) {
|
29
|
super();
|
30
|
this.id = id;
|
31
|
this.baseUrl = baseUrl;
|
32
|
this.clazz = clazz;
|
33
|
}
|
34
|
|
35
|
@Override
|
36
|
protected List<T> nextPage() throws ResultSetException {
|
37
|
final HttpGet method = new HttpGet(getBaseUrl() + "/" + getId() + "/next/" + PAGE_SIZE);
|
38
|
method.addHeader("Accept", "application/json");
|
39
|
|
40
|
try(CloseableHttpResponse httpResponse = client.execute(method)) {
|
41
|
|
42
|
int statusCode = httpResponse.getStatusLine().getStatusCode();
|
43
|
if (HttpStatus.SC_OK != statusCode) {
|
44
|
throw new ResultSetException("Error " + statusCode + " dowloading url: " + getBaseUrl());
|
45
|
}
|
46
|
|
47
|
try(InputStream responseBody = httpResponse.getEntity().getContent()) {
|
48
|
final String json = IOUtils.toString(responseBody);
|
49
|
final Gson gson = new Gson();
|
50
|
final ResultSetResponse response = gson.fromJson(json, ResultSetResponse.class);
|
51
|
return response.getElements()
|
52
|
.stream()
|
53
|
.map(s -> gson.fromJson(s, getClazz()))
|
54
|
.collect(Collectors.toList());
|
55
|
}
|
56
|
} catch (Throwable e) {
|
57
|
throw new ResultSetException("Error dowloading url: " + getBaseUrl(), e);
|
58
|
}
|
59
|
}
|
60
|
|
61
|
public String getId() {
|
62
|
return this.id;
|
63
|
}
|
64
|
|
65
|
public String getBaseUrl() {
|
66
|
return this.baseUrl;
|
67
|
}
|
68
|
|
69
|
public Class<T> getClazz() {
|
70
|
return this.clazz;
|
71
|
}
|
72
|
|
73
|
}
|