ClientResponse cr = handle(ClientRequest.create().build(requestTokenUri, HttpMethod.POST));
// requestToken request failed
if (cr.getStatus() >= 400) {
return cr;
}
Form response = cr.getEntity(Form.class);
String token = response.getFirst(OAuthParameters.TOKEN);
parameters.token(token);
secrets.tokenSecret(response.getFirst(OAuthParameters.TOKEN_SECRET));
state = State.REQUEST_TOKEN;
parameters.verifier(handler.authorize(getAuthorizationUri()));
return handle(request);
} finally {
if (state == State.UNMANAGED) {
parameters.token(null);
secrets.tokenSecret(null);
}
if (state != State.REQUEST_TOKEN) {
state = State.MANAGED;
}
}
}
break;
case REQUEST_TOKEN:
if (parameters.getVerifier() == null) {
throw new UnauthorizedRequestException(parameters, getAuthorizationUri());
}
state = State.UNMANAGED;
try {
ClientResponse cr = handle(ClientRequest.create().build(accessTokenUri, HttpMethod.POST));
// accessToken request failed
if (cr.getStatus() >= 400) {
return cr;
}
Form response = cr.getEntity(Form.class);
String token = response.getFirst(OAuthParameters.TOKEN);
String secret = response.getFirst(OAuthParameters.TOKEN_SECRET);
if (token == null) {
throw new UnauthorizedRequestException(parameters, null);
}
parameters.token(token);
secrets.tokenSecret(secret);
handler.authorized(parameters.getToken(), secrets.getTokenSecret());
state = State.MANAGED;
} finally {
parameters.remove(OAuthParameters.VERIFIER);
if (state == State.UNMANAGED) {
parameters.token(null);
secrets.tokenSecret(null);
state = State.MANAGED;
}
}
}
final OAuthParameters p = (OAuthParameters)parameters.clone(); // make modifications to clone
if (p.getTimestamp() == null) {
p.setTimestamp();
}
if (p.getNonce() == null) {
p.setNonce();
}
try {
OAuthSignature.sign(new RequestWrapper(request, providers), p, secrets);
}
catch (OAuthSignatureException se) {
throw new ClientHandlerException(se);
}
}
// next filter in chain
ClientResponse response;
UniformInterfaceException uie = null;
try {
response = getNext().handle(request);
} catch (UniformInterfaceException e) {
response = e.getResponse();
uie = e;
}
if (state == State.MANAGED && response.getClientResponseStatus() == ClientResponse.Status.UNAUTHORIZED) {
request.getHeaders().remove("Authorization");
parameters.token(null);
secrets.tokenSecret(null);
uie = null;
return handle(request);