request.setEventListener(new SalesforceSecurityListener(
httpClient.getDestination(request.getAddress(), isHttps),
request, session, accessToken));
} catch (IOException e) {
// propagate exception
callback.onResponse(null, new SalesforceException(
String.format("Error registering security listener: %s", e.getMessage()),
e));
}
// use HttpEventListener for lifecycle events
request.setEventListener(new HttpEventListenerWrapper(request.getEventListener(), true) {
public String reason;
@Override
public void onConnectionFailed(Throwable ex) {
super.onConnectionFailed(ex);
callback.onResponse(null,
new SalesforceException("Connection error: " + ex.getMessage(), ex));
}
@Override
public void onException(Throwable ex) {
super.onException(ex);
callback.onResponse(null,
new SalesforceException("Unexpected exception: " + ex.getMessage(), ex));
}
@Override
public void onExpire() {
super.onExpire();
callback.onResponse(null,
new SalesforceException("Request expired", null));
}
@Override
public void onResponseComplete() throws IOException {
super.onResponseComplete();
final int responseStatus = request.getResponseStatus();
if (responseStatus < HttpStatus.OK_200 || responseStatus >= HttpStatus.MULTIPLE_CHOICES_300) {
final String msg = String.format("Error {%s:%s} executing {%s:%s}",
responseStatus, reason, request.getMethod(), request.getRequestURI());
final SalesforceException exception = new SalesforceException(msg, responseStatus, createRestException(request));
callback.onResponse(null, exception);
} else {
// TODO not memory efficient for large response messages,
// doesn't seem to be possible in Jetty 7 to directly stream to response parsers
final byte[] bytes = request.getResponseContentBytes();
callback.onResponse(bytes != null ? new ByteArrayInputStream(bytes) : null, null);
}
}
@Override
public void onResponseStatus(Buffer version, int status, Buffer reason) throws IOException {
super.onResponseStatus(version, status, reason);
// remember status reason
this.reason = reason.toString(StringUtil.__ISO_8859_1);
}
});
// execute the request
try {
httpClient.send(request);
} catch (IOException e) {
String msg = "Unexpected Error: " + e.getMessage();
// send error through callback
callback.onResponse(null, new SalesforceException(msg, e));
}
}