public FakeHttpServletRequest sign(String consumerKey, String consumerSecret, String requestor,
String token, String tokenSecret, OAuthParamLocation paramLocationEnum,
BodySigning bodySigning)
throws Exception {
FakeHttpServletRequest request = new FakeHttpServletRequest(url);
List<OAuth.Parameter> oauthParams = Lists.newArrayList();
UriBuilder target = new UriBuilder(Uri.parse(url));
String query = target.getQuery();
target.setQuery(null);
oauthParams.addAll(OAuth.decodeForm(query));
if (body != null) {
if (OAuth.isFormEncoded(contentType)) {
oauthParams.addAll(OAuth.decodeForm(body));
} else if (bodySigning == BodySigning.LEGACY) {
oauthParams.add(new OAuth.Parameter(body, ""));
} else if (bodySigning == BodySigning.HASH) {
oauthParams.add(
new OAuth.Parameter(OAuthConstants.OAUTH_BODY_HASH,
new String(Base64.encodeBase64(DigestUtils.sha(body.getBytes())), "UTF-8")));
}
}
oauthParams.add(new OAuth.Parameter(OAuth.OAUTH_CONSUMER_KEY, consumerKey));
oauthParams.add(new OAuth.Parameter("xoauth_requestor_id", requestor));
OAuthConsumer consumer = new OAuthConsumer(null,consumerKey,consumerSecret, null);
OAuthAccessor accessor = new OAuthAccessor(consumer);
if (!Strings.isNullOrEmpty(token)) {
accessor.accessToken = token;
accessor.tokenSecret = tokenSecret;
}
OAuthMessage message = accessor.newRequestMessage(method, target.toString(), oauthParams);
List<Map.Entry<String, String>> entryList = selectOAuthParams(message);
switch (paramLocationEnum) {
case AUTH_HEADER:
request.setHeader("Authorization", getAuthorizationHeader(entryList));
break;
case POST_BODY:
if (!OAuth.isFormEncoded(contentType)) {
throw new RuntimeException(
"OAuth param location can only be post_body if post body is of " +
"type x-www-form-urlencoded");
}
// All message params should be added if oauth params are added to body
for (Map.Entry<String, String> param : message.getParameters()) {
request.setParameter(param.getKey(), true, param.getValue());
}
String oauthData = OAuth.formEncode(message.getParameters());
request.setPostData(CharsetUtil.getUtf8Bytes(oauthData));
break;
case URI_QUERY:
request.setQueryString(Uri.parse(OAuth.addParameters(url, entryList)).getQuery());
break;
}
if (body != null && paramLocationEnum != OAuthParamLocation.POST_BODY) {
request.setContentType(contentType);
request.setPostData(body, "UTF-8");
if (contentType.contains(OAuth.FORM_ENCODED)) {
List<OAuth.Parameter> bodyParams = OAuth.decodeForm(body);
for (OAuth.Parameter bodyParam : bodyParams) {
request.setParameter(bodyParam.getKey(), bodyParam.getValue());
}
}
}
request.setMethod(method);
return request;
}