1
|
package eu.dnetlib.data.utils;
|
2
|
|
3
|
import java.net.URI;
|
4
|
import java.net.URISyntaxException;
|
5
|
|
6
|
import org.apache.commons.lang3.StringUtils;
|
7
|
import org.apache.commons.logging.Log;
|
8
|
import org.apache.commons.logging.LogFactory;
|
9
|
import org.springframework.http.HttpEntity;
|
10
|
import org.springframework.http.HttpHeaders;
|
11
|
import org.springframework.http.HttpMethod;
|
12
|
|
13
|
public class HttpFetcher {
|
14
|
|
15
|
private static final Log log = LogFactory.getLog(HttpFetcher.class);
|
16
|
|
17
|
private static final int INTERVAL_MILLIS = 20000;
|
18
|
|
19
|
public static final int MAX_NUMBER_OF_ATTEMPTS = 10;
|
20
|
|
21
|
public static String fetch(final String url, final String accessToken) throws URISyntaxException {
|
22
|
return fetch(new URI(url), 1, accessToken);
|
23
|
}
|
24
|
|
25
|
public static String fetch(final URI url, final String accessToken) {
|
26
|
return fetch(url, 1, accessToken);
|
27
|
}
|
28
|
|
29
|
public static String fetch(final URI url, final int attempts, final String accessToken) {
|
30
|
if (attempts > MAX_NUMBER_OF_ATTEMPTS) {
|
31
|
log.error("Max number of attempts reached, downloading url: " + url);
|
32
|
return "";
|
33
|
}
|
34
|
|
35
|
try {
|
36
|
log.debug("Downloading URL: " + url + " - try: " + attempts);
|
37
|
|
38
|
final HttpHeaders headers = new HttpHeaders();
|
39
|
if (StringUtils.isNotBlank(accessToken)) {
|
40
|
log.debug("Perform call using access token: " + accessToken);
|
41
|
headers.set("Authorization", "Bearer " + accessToken);
|
42
|
}
|
43
|
|
44
|
return RestTemplateFactory.newInstance()
|
45
|
.exchange(url, HttpMethod.GET, new HttpEntity<>(null, headers), String.class)
|
46
|
.getBody();
|
47
|
} catch (final Throwable e) {
|
48
|
try {
|
49
|
log.error("Error downloading url: " + url + " - try: " + attempts + " - " + e.getMessage());
|
50
|
Thread.sleep(INTERVAL_MILLIS);
|
51
|
return fetch(url, attempts + 1, accessToken);
|
52
|
} catch (final InterruptedException e1) {
|
53
|
log.error(e);
|
54
|
return "";
|
55
|
}
|
56
|
}
|
57
|
}
|
58
|
}
|