}
if (!commsTokenAlreadyRenewed) {
session.createCommsTokenAsRequired();
}
HttpPost httpRequest = requestBuilder.build(session);
try {
JsonNode jsonNode = executeRequest(httpRequest);
// Handle fault codes from the API
GroovesharkException exception = mapGroovesharkFaultCodeToException(jsonNode);
if (exception != null) {
if (exception instanceof GroovesharkException.InvalidSessionException) {
// Attempt to renew session and retry
if (sessionAlreadyRenewed) {
throw new GroovesharkException.ServerErrorException(
"Failed with invalid session. Renewed session still invalid.");
} else {
createSession();
sessionAlreadyRenewed = true;
continue;
}
} else if (exception instanceof GroovesharkException.InvalidCommsTokenException) {
// Attempt to renew token and retry
if (commsTokenAlreadyRenewed) {
throw new GroovesharkException.ServerErrorException(
"Failed with invalid comms token. Renewed token also invalid.");
} else {
session.createCommsToken();
commsTokenAlreadyRenewed = true;
continue;
}
} else {
// The exception can't be handled internally
throw exception;
}
}
return jsonNode;
} finally {
// Finished with connection at this point, so make it reuseable
httpRequest.reset();
}
}
}