Example usage for com.squareup.okhttp HttpUrl querySize

List of usage examples for com.squareup.okhttp HttpUrl querySize

Introduction

In this page you can find the example usage for com.squareup.okhttp HttpUrl querySize.

Prototype

public int querySize() 

Source Link

Usage

From source file:com.mamaspapas.api.helper.Oauth1SigningInterceptor.java

License:Apache License

public Request signRequest(Request request) throws IOException {
    byte[] nonce = new byte[32];
    random.nextBytes(nonce);//  w w w  .  j  a  v a 2  s .c  om
    String oauthNonce = ByteString.of(nonce).base64().replaceAll("\\W", "");
    String oauthTimestamp = String.valueOf(clock.millis());

    String consumerKeyValue = ESCAPER.escape(consumerKey);
    String accessTokenValue = ESCAPER.escape(accessToken);

    SortedMap<String, String> parameters = new TreeMap<>();
    parameters.put(OAUTH_CONSUMER_KEY, consumerKeyValue);
    parameters.put(OAUTH_ACCESS_TOKEN, accessTokenValue);
    parameters.put(OAUTH_NONCE, oauthNonce);
    parameters.put(OAUTH_TIMESTAMP, oauthTimestamp);
    parameters.put(OAUTH_SIGNATURE_METHOD, OAUTH_SIGNATURE_METHOD_VALUE);
    parameters.put(OAUTH_VERSION, OAUTH_VERSION_VALUE);

    HttpUrl url = request.httpUrl();
    for (int i = 0; i < url.querySize(); i++) {
        parameters.put(ESCAPER.escape(url.queryParameterName(i)), ESCAPER.escape(url.queryParameterValue(i)));
    }

    //        RequestBody requestBody = request.body();
    //        Buffer body = new Buffer();
    //        requestBody.writeTo(body);

    //        while (!body.exhausted()) {
    //            long keyEnd = body.indexOf((byte) '=');
    //            if (keyEnd == -1) throw new IllegalStateException("Key with no value: " + body.readUtf8());
    //            String key = body.readUtf8(keyEnd);
    //            body.skip(1); // Equals.
    //
    //            long valueEnd = body.indexOf((byte) '&');
    //            String value = valueEnd == -1 ? body.readUtf8() : body.readUtf8(valueEnd);
    //            if (valueEnd != -1) body.skip(1); // Ampersand.
    //
    //            parameters.put(key, value);
    //        }

    Buffer base = new Buffer();
    String method = request.method();
    base.writeUtf8(method);
    base.writeByte('&');
    base.writeUtf8(ESCAPER.escape(request.httpUrl().newBuilder().query(null).build().toString()));
    base.writeByte('&');

    boolean first = true;
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        if (!first)
            base.writeUtf8(ESCAPER.escape("&"));
        first = false;
        base.writeUtf8(ESCAPER.escape(entry.getKey()));
        base.writeUtf8(ESCAPER.escape("="));
        base.writeUtf8(ESCAPER.escape(entry.getValue()));
    }

    String signingKey = ESCAPER.escape(consumerSecret) + "&" + ESCAPER.escape(accessSecret);

    SecretKeySpec keySpec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(keySpec);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new IllegalStateException(e);
    }
    byte[] result = mac.doFinal(base.readByteArray());
    String signature = ByteString.of(result).base64();

    String authorization = "OAuth " + OAUTH_CONSUMER_KEY + "=\"" + consumerKeyValue + "\", " + OAUTH_NONCE
            + "=\"" + oauthNonce + "\", " + OAUTH_SIGNATURE + "=\"" + ESCAPER.escape(signature) + "\", "
            + OAUTH_SIGNATURE_METHOD + "=\"" + OAUTH_SIGNATURE_METHOD_VALUE + "\", " + OAUTH_TIMESTAMP + "=\""
            + oauthTimestamp + "\", " + OAUTH_ACCESS_TOKEN + "=\"" + accessTokenValue + "\", " + OAUTH_VERSION
            + "=\"" + OAUTH_VERSION_VALUE + "\"";

    return request.newBuilder().addHeader("Authorization", authorization).build();
}

From source file:com.xing.api.Oauth1SigningInterceptor.java

License:Apache License

public Request signRequest(Request request) throws IOException {
    byte[] nonce = new byte[NUANCE_BYTES];
    random.nextBytes(nonce);//from  w w w . j a v  a2  s .com
    String oauthNonce = CHARACTER_PATTERN.matcher(ByteString.of(nonce).base64()).replaceAll("");
    String oauthTimestamp = clock.millis();

    String consumerKeyValue = UrlEscapeUtils.escape(consumerKey);
    String accessTokenValue = UrlEscapeUtils.escape(accessToken);

    SortedMap<String, String> parameters = new TreeMap<>();
    parameters.put(OAUTH_CONSUMER_KEY, consumerKeyValue);
    parameters.put(OAUTH_ACCESS_TOKEN, accessTokenValue);
    parameters.put(OAUTH_NONCE, oauthNonce);
    parameters.put(OAUTH_TIMESTAMP, oauthTimestamp);
    parameters.put(OAUTH_SIGNATURE_METHOD, OAUTH_SIGNATURE_METHOD_VALUE);
    parameters.put(OAUTH_VERSION, OAUTH_VERSION_VALUE);

    HttpUrl url = request.httpUrl();
    for (int i = 0; i < url.querySize(); i++) {
        parameters.put(UrlEscapeUtils.escape(url.queryParameterName(i)),
                UrlEscapeUtils.escape(url.queryParameterValue(i)));
    }

    Buffer body = new Buffer();
    RequestBody requestBody = request.body();
    if (requestBody != null) {
        requestBody.writeTo(body);
    }

    while (!body.exhausted()) {
        long keyEnd = body.indexOf((byte) '=');
        if (keyEnd == -1) {
            throw new IllegalStateException("Key with no value: " + body.readUtf8());
        }
        String key = body.readUtf8(keyEnd);
        body.skip(1); // Equals.

        long valueEnd = body.indexOf((byte) '&');
        String value = valueEnd == -1 ? body.readUtf8() : body.readUtf8(valueEnd);
        if (valueEnd != -1) {
            body.skip(1); // Ampersand.
        }

        parameters.put(key, value);
    }

    Buffer base = new Buffer();
    String method = request.method();
    base.writeUtf8(method);
    base.writeByte('&');
    base.writeUtf8(UrlEscapeUtils.escape(request.httpUrl().newBuilder().query(null).build().toString()));
    base.writeByte('&');

    boolean first = true;
    for (Entry<String, String> entry : parameters.entrySet()) {
        if (!first) {
            base.writeUtf8(UrlEscapeUtils.escape("&"));
        }
        first = false;
        base.writeUtf8(UrlEscapeUtils.escape(entry.getKey()));
        base.writeUtf8(UrlEscapeUtils.escape("="));
        base.writeUtf8(UrlEscapeUtils.escape(entry.getValue()));
    }

    String signingKey = UrlEscapeUtils.escape(consumerSecret) + '&' + UrlEscapeUtils.escape(accessSecret);
    SecretKeySpec keySpec = new SecretKeySpec(signingKey.getBytes(), "HmacSHA1");
    Mac mac;
    try {
        mac = Mac.getInstance("HmacSHA1");
        mac.init(keySpec);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new IllegalStateException(e);
    }
    byte[] result = mac.doFinal(base.readByteArray());
    String signature = ByteString.of(result).base64();

    String authorization = "OAuth " //
            + OAUTH_CONSUMER_KEY + "=\"" + consumerKeyValue + "\", " //
            + OAUTH_NONCE + "=\"" + oauthNonce + "\", " //
            + OAUTH_SIGNATURE + "=\"" + UrlEscapeUtils.escape(signature) + "\", " //
            + OAUTH_SIGNATURE_METHOD + "=\"" + OAUTH_SIGNATURE_METHOD_VALUE + "\", " //
            + OAUTH_TIMESTAMP + "=\"" + oauthTimestamp + "\", " //
            + OAUTH_ACCESS_TOKEN + "=\"" + accessTokenValue + "\", " //
            + OAUTH_VERSION + "=\"" + OAUTH_VERSION_VALUE + '"';

    return request.newBuilder().addHeader("Authorization", authorization).build();
}

From source file:org.mariotaku.twidere.util.OAuthPasswordAuthenticator.java

License:Open Source License

public OAuthPasswordAuthenticator(final TwitterOAuth oauth,
        final LoginVerificationCallback loginVerificationCallback, final String userAgent) {
    final RestClient restClient = RestAPIFactory.getRestClient(oauth);
    this.oauth = oauth;
    this.client = (OkHttpRestClient) restClient.getRestClient();
    final OkHttpClient okhttp = client.getClient();
    okhttp.setCookieHandler(new CookieManager());
    okhttp.networkInterceptors().add(new Interceptor() {
        @Override// w ww.  ja v a 2  s .  c  o  m
        public Response intercept(Chain chain) throws IOException {
            final Response response = chain.proceed(chain.request());
            if (!response.isRedirect()) {
                return response;
            }
            final String location = response.header("Location");
            final Response.Builder builder = response.newBuilder();
            if (!TextUtils.isEmpty(location) && !endpoint.checkEndpoint(location)) {
                final HttpUrl originalLocation = HttpUrl
                        .get(URI.create("https://api.twitter.com/").resolve(location));
                final HttpUrl.Builder locationBuilder = HttpUrl.parse(endpoint.getUrl()).newBuilder();
                for (String pathSegments : originalLocation.pathSegments()) {
                    locationBuilder.addPathSegment(pathSegments);
                }
                for (int i = 0, j = originalLocation.querySize(); i < j; i++) {
                    final String name = originalLocation.queryParameterName(i);
                    final String value = originalLocation.queryParameterValue(i);
                    locationBuilder.addQueryParameter(name, value);
                }
                final String encodedFragment = originalLocation.encodedFragment();
                if (encodedFragment != null) {
                    locationBuilder.encodedFragment(encodedFragment);
                }
                final HttpUrl newLocation = locationBuilder.build();
                builder.header("Location", newLocation.toString());
            }
            return builder.build();
        }
    });
    this.endpoint = restClient.getEndpoint();
    this.loginVerificationCallback = loginVerificationCallback;
    this.userAgent = userAgent;
}