Java源码示例:oauth.signpost.exception.OAuthException
示例1
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
String dataXml = "";
if (resultData != null) {
String format = isUrl ? resultDataUrl : resultDataText;
dataXml = String.format(format, StringEscapeUtils.escapeXml(resultData));
}
//*LAMS* the following line was added by LAMS and also messageIdentifier was added to the line after it
String messageIdentifier = UUID.randomUUID().toString();
String xml = String.format(replaceResultMessage, messageIdentifier, StringEscapeUtils.escapeXml(sourcedid),
StringEscapeUtils.escapeXml(score), dataXml);
HttpParameters parameters = new HttpParameters();
String hash = getBodyHash(xml);
parameters.put("oauth_body_hash", URLEncoder.encode(hash, "UTF-8"));
CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/xml");
request.setEntity(new StringEntity(xml, "UTF-8"));
signer.setAdditionalParameters(parameters);
signer.sign(request);
return request;
}
示例2
@Override
public void processHttpMessage(int toolFlag, boolean messageIsRequest, IHttpRequestResponse messageInfo)
{
if (messageIsRequest && shouldSign(messageInfo))
{
HttpRequest req = new BurpHttpRequestWrapper(messageInfo);
OAuthConsumer consumer = new DefaultOAuthConsumer(
OAuthConfig.getConsumerKey(),
OAuthConfig.getConsumerSecret());
consumer.setTokenWithSecret(OAuthConfig.getToken(),
OAuthConfig.getTokenSecret());
try {
consumer.sign(req);
} catch (OAuthException oae) {
oae.printStackTrace();
}
}
}
示例3
/**
* Starts the OAuth authentication flow.
*/
public synchronized void startAuthentication(String accountId) {
WithingsAccount withingsAccount = getAccount(accountId);
if (withingsAccount == null) {
logger.warn("Couldn't find Credentials of Account '{}'. Please check openhab.cfg or withings.cfg.",
accountId);
return;
}
OAuthConsumer consumer = withingsAccount.createConsumer();
provider = new DefaultOAuthProvider(OAUTH_REQUEST_TOKEN_ENDPOINT, OAUTH_ACCESS_TOKEN_ENDPOINT_URL,
OAUTH_AUTHORIZE_ENDPOINT_URL);
try {
String url = provider.retrieveRequestToken(consumer, this.redirectUrl);
printSetupInstructions(url);
} catch (OAuthException ex) {
logger.error(ex.getMessage(), ex);
printAuthenticationFailed(ex);
}
}
示例4
/**
* Returns a list of all measures in form {@link MeasureGroup} objects since
* the given start time.
*
* @param startTime
* time after which measures are returned
* @return list of all measures
* @throws OAuthException
* if an error occurs while signing the request
* @throws WithingsConnectionException
* if a connection, server or authorization error occurs
* @see http://www.withings.com/de/api#bodymetrics
*/
public List<MeasureGroup> getMeasures(int startTime) throws OAuthException, WithingsConnectionException {
String url = getServiceUrl(API_ENDPOINT_MEASURE, API_METHOD_GET_MEASURES);
if (startTime > 0) {
url = url + "&startdate=" + startTime;
}
try {
JsonObject jsonObject = call(consumer.sign(url));
int status = jsonObject.get("status").getAsInt();
if (status == 0) {
JsonElement body = jsonObject.get("body");
return gson.fromJson(body.getAsJsonObject(), MeasureResult.class).measureGroups;
} else {
throw new WithingsConnectionException("Withings API call failed: " + status);
}
} catch (Exception ex) {
throw new WithingsConnectionException("Could not connect to URL: " + ex.getMessage(), ex);
}
}
示例5
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
HttpPost request = buildReplaceResult(url, key, secret, sourcedid, score, resultData, isUrl);
//*LAMS* replaced DefaultHttpClient with HttpClient
HttpClient client = HttpClients.custom()
.setDefaultRequestConfig(RequestConfig.custom()
.setCookieSpec(CookieSpecs.STANDARD).build())
.build(); // DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() >= 400) {
throw new HttpResponseException(response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase());
}
}
示例6
@Override
protected List<String> doInBackground() throws OAuthException {
provider.retrieveAccessToken(consumer, verificationCode);
// must use an own connection here and not the normal singleton because since the
// authorization process is not finished, the new authorized consumer is not applied yet
OsmConnection osm = new OsmConnection(OSM_API_URL, ApplicationConstants.USER_AGENT, consumer);
return new PermissionsDao(osm).get();
}
示例7
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
if (original.header(ApiConstants.OAUTH_ENABLE_HEADER) != null) {
try {
original = (Request) consumer.sign(original).unwrap();
} catch (OAuthException e) {
throw new IOException("Could not sign request", e);
}
}
return chain.proceed(original);
}
示例8
private HttpURLConnection sendRequest(
String call, String method, boolean authenticate, ApiRequestWriter writer)
throws IOException, OAuthException
{
HttpURLConnection connection = openConnection(call);
if(method != null)
{
connection.setRequestMethod(method);
}
if(writer != null && writer.getContentType() != null)
{
connection.setRequestProperty("Content-Type", writer.getContentType());
connection.setRequestProperty("charset", CHARSET.toLowerCase(Locale.UK));
}
if(authenticate)
{
createOAuthConsumer().sign(connection);
}
if(writer != null)
{
sendRequestPayload(connection, writer);
}
return connection;
}
示例9
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
try {
HttpRequest httpRequest = consumer.sign(request);
Request authenticateRequest = (Request) httpRequest.unwrap();
return chain.proceed(authenticateRequest);
} catch (OAuthException e) {
Log.e(LOG_TAG, "Error " + e.getMessage());
throw new IOException("Could not sign request", e);
}
}
示例10
/**
* Get access token-secret pair
*
* @param verifier OAuth verifier, which was got after authorization
* @return Access token-secret pair
* */
public HashMap<String, String> getAccessTokenSet(String verifier) {
try {
mOAuthProvider.retrieveAccessToken(mOAuthConsumer, verifier);
}
catch (OAuthException e) {
e.printStackTrace();
}
return setTokenWithSecret(mOAuthConsumer.getToken(), mOAuthConsumer.getTokenSecret());
}
示例11
/**
* Get authorization URL, use provided callback URL
*
* @param oauthCallback URL, i.e. oauth_callback
* @return URL for authorizing application
* */
private String _getAuthorizationUrl(String oauthCallback) {
String url = null;
try {
url = mOAuthProvider.retrieveRequestToken(mOAuthConsumer, oauthCallback);
}
catch (OAuthException e) {
e.printStackTrace();
}
return url;
}
示例12
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
try {
HttpRequest httpRequest = consumer.sign(request);
Request authenticateRequest = (Request) httpRequest.unwrap();
return chain.proceed(authenticateRequest);
} catch (OAuthException e) {
Log.e(LOG_TAG, "Error " + e.getMessage());
throw new IOException("Could not sign request", e);
}
}
示例13
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
HttpPost request = buildReplaceResult(url, key, secret, sourcedid, score, resultData, isUrl);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() >= 400) {
throw new HttpResponseException(response.getStatusLine().getStatusCode(),
response.getStatusLine().getReasonPhrase());
}
}
示例14
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid,
String score, String resultData, Boolean isUrl, String messageId) throws IOException, OAuthException, GeneralSecurityException
{
String dataXml = "";
if (resultData != null) {
String format = isUrl ? resultDataUrl : resultDataText;
dataXml = String.format(format, StringEscapeUtils.escapeXml(resultData));
}
String messageIdentifier = StringUtils.isBlank(messageId) ? String.valueOf(new Date().getTime()) : messageId;
String xml = String.format(ReplaceResultMessageTemplate,
StringEscapeUtils.escapeXml(messageIdentifier),
StringEscapeUtils.escapeXml(sourcedid),
StringEscapeUtils.escapeXml(score),
dataXml);
HttpParameters parameters = new HttpParameters();
String hash = getBodyHash(xml);
parameters.put("oauth_body_hash", URLEncoder.encode(hash, "UTF-8"));
CommonsHttpOAuthConsumer signer = new CommonsHttpOAuthConsumer(key, secret);
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/xml");
request.setEntity(new StringEntity(xml, "UTF-8"));
signer.setAdditionalParameters(parameters);
signer.sign(request);
return request;
}
示例15
/**
* Request the request token and secret.
* @param callbackURL the URL where the provider should redirect to
* @return a Response object holding either the result in case of a success or the error
*/
public Response retrieveRequestToken(String callbackURL) {
OAuthConsumer consumer = new DefaultOAuthConsumer(info.consumerKey, info.consumerSecret);
try {
provider.retrieveRequestToken(consumer, callbackURL);
} catch (OAuthException e) {
return Response.error(new Error(e));
}
return Response.success(consumer.getToken(), consumer.getTokenSecret());
}
示例16
/**
* Exchange a request token for an access token.
* @param token the token obtained from a previous call
* @param secret your application secret
* @return a Response object holding either the result in case of a success or the error
*/
public Response retrieveAccessToken(String token, String secret) {
OAuthConsumer consumer = new DefaultOAuthConsumer(info.consumerKey, info.consumerSecret);
consumer.setTokenWithSecret(token, secret);
String verifier = Params.current().get("oauth_verifier");
try {
provider.retrieveAccessToken(consumer, verifier);
} catch (OAuthException e) {
return Response.error(new Error(e));
}
return Response.success(consumer.getToken(), consumer.getTokenSecret());
}
示例17
private Error(OAuthException exception) {
this.exception = exception;
if (this.exception instanceof OAuthMessageSignerException) {
this.type = Type.MESSAGE_SIGNER;
} else if (this.exception instanceof OAuthNotAuthorizedException) {
this.type = Type.NOT_AUTHORIZED;
} else if (this.exception instanceof OAuthExpectationFailedException) {
this.type = Type.EXPECTATION_FAILED;
} else if (this.exception instanceof OAuthCommunicationException) {
this.type = Type.COMMUNICATION;
} else {
this.type = Type.OTHER;
}
this.details = exception.getMessage();
}
示例18
/**
* Finishes the OAuth authentication flow.
*
* @param verificationCode
* OAuth verification code
* @param userId
* user id
*/
public synchronized void finishAuthentication(String accountId, String verificationCode, String userId) {
WithingsAccount withingsAccount = getAccount(accountId);
if (withingsAccount == null) {
logger.warn("Couldn't find Credentials of Account '{}'. Please check openhab.cfg or withings.cfg.",
accountId);
return;
}
OAuthConsumer consumer = withingsAccount.consumer;
if (provider == null || consumer == null) {
logger.warn("Could not finish authentication. Please execute 'startAuthentication' first.");
return;
}
try {
provider.retrieveAccessToken(consumer, verificationCode);
} catch (OAuthException ex) {
logger.error(ex.getMessage(), ex);
printAuthenticationFailed(ex);
return;
}
withingsAccount.userId = userId;
withingsAccount.setOuathToken(consumer.getToken(), consumer.getTokenSecret());
withingsAccount.registerAccount(componentContext.getBundleContext());
withingsAccount.persist();
printAuthenticationSuccessful();
}
示例19
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
try {
return chain.proceed((Request) consumer.sign(request).unwrap());
} catch (OAuthException e) {
throw new IOException("Could not sign request", e);
}
}
示例20
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score) throws IOException, OAuthException, GeneralSecurityException {
sendReplaceResult(url, key, secret, sourcedid, score, null);
}
示例21
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData) throws IOException, OAuthException, GeneralSecurityException {
sendReplaceResult(url, key, secret, sourcedid, score, resultData, false);
}
示例22
@Override
protected String doInBackground() throws OAuthException {
return provider.retrieveRequestToken(consumer, CALLBACK_URL);
}
示例23
/**
* Send signed POST OAuth request
*
* @param url Relative URL
* @param type Type of HTTP request (HTTP method)
* @param params Hash of parameters
* @throws JSONException If JSON object is invalid or request was abnormal
* @return {@link JSONObject} JSON Object that contains data from response
* */
private JSONObject sendPostRequest(String url, Integer type, HashMap<String, String> params) throws JSONException {
String fullUrl = getFullUrl(url);
HttpPost request = new HttpPost(fullUrl);
switch(type) {
case METHOD_PUT:
case METHOD_DELETE:
// assign overload value
String oValue;
if (type == METHOD_PUT) {
oValue = "put";
} else {
oValue = "delete";
}
params.put(OVERLOAD_PARAM, oValue);
case METHOD_POST:
break;
default:
throw new RuntimeException("Wrong http method requested");
}
// doing post request using json to avoid issue with urlencoded symbols
JSONObject json = new JSONObject();
for (Map.Entry<String, String> entry : params.entrySet()) {
json.put(entry.getKey(), entry.getValue());
}
request.setHeader("Content-Type", "application/json");
try {
request.setEntity(new StringEntity(json.toString()));
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// sign request
try {
mOAuthConsumer.sign(request);
}
catch (OAuthException e) {
e.printStackTrace();
}
return UpworkRestClient.getJSONObject(request, type, params);
}
示例24
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score) throws IOException, OAuthException, GeneralSecurityException {
sendReplaceResult(url, key, secret, sourcedid, score, null);
}
示例25
public static void sendReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData) throws IOException, OAuthException, GeneralSecurityException {
sendReplaceResult(url, key, secret, sourcedid, score, resultData, false);
}
示例26
public static HttpPost buildReplaceResult(String url, String key, String secret, String sourcedid, String score, String resultData, Boolean isUrl) throws IOException, OAuthException, GeneralSecurityException {
return buildReplaceResult(url, key, secret, sourcedid, score, resultData, isUrl, null);
}
示例27
private void printAuthenticationFailed(OAuthException ex) {
logger.info(LINE);
logger.info("# Withings authentication FAILED: " + ex.getMessage());
logger.info("# Try to restart authentication by executing 'withings:startAuthentication'");
logger.info(LINE);
}
示例28
/**
* Returns a list of all measures in form {@link MeasureGroup} objects.
*
* @return list of all measures
* @throws OAuthException
* if an error occurs while signing the request
* @throws WithingsConnectionException
* if a connection, server or authorization error occurs
* @see http://www.withings.com/de/api#bodymetrics
*/
public List<MeasureGroup> getMeasures() throws OAuthException, WithingsConnectionException {
return getMeasures(0);
}