1313import java .nio .file .Paths ;
1414import java .nio .file .StandardOpenOption ;
1515import java .util .Optional ;
16+ import java .time .Duration ;
1617import okhttp3 .OkHttpClient ;
1718import okhttp3 .Request ;
1819import okhttp3 .Response ;
@@ -30,6 +31,11 @@ public class LatestAgentSnapshotResolver {
3031 "https://oss.sonatype.org/content/repositories/snapshots/io/opentelemetry/javaagent/opentelemetry-javaagent" ;
3132 static final String LATEST_SNAPSHOT_META = BASE_URL + "/maven-metadata.xml" ;
3233
34+ private static final OkHttpClient client = new OkHttpClient .Builder ()
35+ .connectTimeout (Duration .ofMinutes (1 ))
36+ .readTimeout (Duration .ofMinutes (1 ))
37+ .build ();
38+
3339 Optional <Path > resolve () throws IOException {
3440 String version = fetchLatestSnapshotVersion ();
3541 logger .info ("Latest snapshot version is {}" , version );
@@ -81,11 +87,33 @@ private byte[] fetchBodyBytesFrom(String url) throws IOException {
8187 return fetchBodyFrom (url ).bytes ();
8288 }
8389
90+ // The sonatype repository can be very unreliable, so we retry a few times
8491 private ResponseBody fetchBodyFrom (String url ) throws IOException {
8592 Request request = new Request .Builder ().url (url ).build ();
86- OkHttpClient client = new OkHttpClient ();
87- Response response = client .newCall (request ).execute ();
88- ResponseBody body = response .body ();
89- return body ;
93+ IOException lastException = null ;
94+
95+ for (int attempt = 0 ; attempt < 3 ; attempt ++) {
96+ try {
97+ try (Response response = client .newCall (request ).execute ()) {
98+ if (!response .isSuccessful ()) {
99+ throw new IOException ("Unexpected HTTP code " + response .code () + " for " + url );
100+ }
101+ ResponseBody body = response .body ();
102+ if (body != null ) {
103+ byte [] data = body .bytes ();
104+ return ResponseBody .create (data , body .contentType ());
105+ } else {
106+ throw new IOException ("Response body is null" );
107+ }
108+ }
109+ } catch (IOException e ) {
110+ lastException = e ;
111+ if (attempt < 2 ) {
112+ logger .warn ("Attempt {} to fetch {} failed: {}. Retrying..." , attempt + 1 , url , e .getMessage ());
113+ }
114+ }
115+ }
116+ throw lastException ;
90117 }
91118}
119+
0 commit comments