1
|
package eu.dnetlib.data.utils;
|
2
|
|
3
|
import java.net.URI;
|
4
|
import java.net.URISyntaxException;
|
5
|
import java.security.KeyManagementException;
|
6
|
import java.security.KeyStoreException;
|
7
|
import java.security.NoSuchAlgorithmException;
|
8
|
import java.util.concurrent.TimeUnit;
|
9
|
|
10
|
import org.apache.commons.logging.Log;
|
11
|
import org.apache.commons.logging.LogFactory;
|
12
|
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
13
|
import org.apache.http.impl.client.HttpClientBuilder;
|
14
|
import org.apache.http.ssl.SSLContextBuilder;
|
15
|
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
16
|
import org.springframework.web.client.RestTemplate;
|
17
|
|
18
|
import eu.dnetlib.data.mdstore.plugins.GenericDoiMdstorePlugin;
|
19
|
|
20
|
public class HttpFetcher {
|
21
|
|
22
|
private static final Log log = LogFactory.getLog(GenericDoiMdstorePlugin.class);
|
23
|
public static final int MAX_NUMBER_OF_ATTEMPTS = 10;
|
24
|
private static final int INTERVAL_MILLIS = 20000;
|
25
|
|
26
|
private static final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
|
27
|
private static SSLConnectionSocketFactory sslSocketFactory;
|
28
|
static {
|
29
|
try {
|
30
|
sslContextBuilder.loadTrustMaterial(null, (chain, authType) -> true);
|
31
|
sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build());
|
32
|
} catch (final NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
|
33
|
log.error(e);;
|
34
|
}
|
35
|
}
|
36
|
private static final HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory(HttpClientBuilder
|
37
|
.create()
|
38
|
.setConnectionTimeToLive(0, TimeUnit.MILLISECONDS)
|
39
|
.setMaxConnPerRoute(1)
|
40
|
.setMaxConnTotal(1)
|
41
|
.disableAutomaticRetries()
|
42
|
.disableConnectionState()
|
43
|
.setSSLSocketFactory(sslSocketFactory)
|
44
|
.build());
|
45
|
|
46
|
public static String fetch(final String url) throws URISyntaxException {
|
47
|
return fetch(new URI(url), 1);
|
48
|
}
|
49
|
|
50
|
public static String fetch(final URI url) {
|
51
|
return fetch(url, 1);
|
52
|
}
|
53
|
|
54
|
public static String fetch(final URI url, final int attempts) {
|
55
|
if (attempts > MAX_NUMBER_OF_ATTEMPTS) {
|
56
|
log.error("Max number of attempts reached, downloading url: " + url);
|
57
|
return "";
|
58
|
}
|
59
|
|
60
|
try {
|
61
|
log.debug("Downloading URL: " + url + " - try: " + attempts);
|
62
|
return (new RestTemplate(httpRequestFactory)).getForObject(url, String.class);
|
63
|
} catch (final Throwable e) {
|
64
|
try {
|
65
|
log.error("Error downloading url: " + url + " - try: " + attempts + " - " + e.getMessage());
|
66
|
Thread.sleep(INTERVAL_MILLIS);
|
67
|
return fetch(url, attempts + 1);
|
68
|
} catch (final InterruptedException e1) {
|
69
|
log.error(e);
|
70
|
return "";
|
71
|
}
|
72
|
}
|
73
|
}
|
74
|
}
|