Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Retry HTTP call on connection failure in sendHTTPReponse()
.
..
...
public JSONObject sendHTTPCall(String urlString, String requestType, AbstractBuild build, BuildListener listener)
throws IOException {
return sendHTTPCall( urlString, requestType, build, listener, 1 );
}
public JSONObject sendHTTPCall(String urlString, String requestType, AbstractBuild build, BuildListener listener, int NumberOfAttempts)
throws IOException {
RemoteJenkinsServer remoteServer = this.findRemoteHost(this.getRemoteJenkinsName());
if (remoteServer == null) {
this.failBuild(new Exception("No remote host is defined for this job."), listener);
return null;
}
HttpURLConnection connection = null;
JSONObject responseObject = null;
try {
URL buildUrl = new URL(urlString);
connection = (HttpURLConnection) buildUrl.openConnection();
// if there is a username + apiToken defined for this remote host, then use it
String usernameTokenConcat;
if (this.getOverrideAuth()) {
usernameTokenConcat = this.getAuth()[0].getUsername() + ":" + this.getAuth()[0].getPassword();
} else {
usernameTokenConcat = remoteServer.getAuth()[0].getUsername() + ":"
+ remoteServer.getAuth()[0].getPassword();
}
if (!usernameTokenConcat.equals(":")) {
// token-macro replacment
usernameTokenConcat = TokenMacro.expandAll(build, listener, usernameTokenConcat);
byte[] encodedAuthKey = Base64.encodeBase64(usernameTokenConcat.getBytes());
connection.setRequestProperty("Authorization", "Basic " + new String(encodedAuthKey));
}
connection.setDoInput(true);
connection.setRequestProperty("Accept", "application/json");
connection.setRequestMethod(requestType);
// wait up to 5 seconds for the connection to be open
connection.setConnectTimeout(5000);
connection.connect();
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
// String response = "";
StringBuilder response = new StringBuilder();
while ((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
// JSONSerializer serializer = new JSONSerializer();
// need to parse the data we get back into struct
//listener.getLogger().println("Called URL: '" + urlString + "', got response: '" + response.toString() + "'");
if ( response.toString().isEmpty() ) {
listener.getLogger().println("Remote Jenkins server returned empty response to trigger.");
return null;
} else {
responseObject = (JSONObject) JSONSerializer.toJSON(response.toString());
}
} catch (IOException e) {
//If we have ConnectionRetryLimit set to > 0 then retry that many times.
if ( NumberOfAttempts <= this.getConnectionRetryLimit() ) {
listener.getLogger().println("Connection to remote server failed, waiting for to retry - " + this.pollInterval + " seconds until next attempt.");
// Sleep for 'pollInterval' seconds.
// Sleep takes miliseconds so need to convert this.pollInterval to milisecopnds (x 1000)
try {
// Could do with a better way of sleeping...
Thread.sleep(this.pollInterval * 1000);
} catch (InterruptedException ex) {
this.failBuild(ex, listener);
}
String strNumberOfRetries = Integer.toString(NumberOfAttempts);
String strConnectionRetryLimit = Integer.toString(this.getConnectionRetryLimit() );
listener.getLogger().println("Retrying (attempt " + strNumberOfRetries + " out of " + strConnectionRetryLimit );
responseObject = sendHTTPCall(urlString, requestType, build, listener, NumberOfAttempts+1);
}
// something failed with the connection, so throw an exception to mark the build as failed.
else {
this.failBuild(e, listener);
}
} catch (MacroEvaluationException e) {
this.failBuild(e, listener);
} catch (InterruptedException e) {
this.failBuild(e, listener);
} finally {
// always make sure we close the connection
if (connection != null) {
connection.disconnect();
}
// and always clear the query string and remove some "global" values
this.clearQueryString();
// this.build = null;
// this.listener = null;
}
return responseObject;
}
...
..
.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.