Example usage for com.squareup.okhttp Request urlString

List of usage examples for com.squareup.okhttp Request urlString

Introduction

In this page you can find the example usage for com.squareup.okhttp Request urlString.

Prototype

public String urlString() 

Source Link

Usage

From source file:com.magnet.max.android.rest.qos.internal.CachedRequest.java

License:Apache License

public CachedRequest(Request request) {
    url = request.urlString();
    method = request.method();// w  w w  .  j av a2s  .c  om

    parseHeaders(request.headers());

    if (null != request.body()) {
        try {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            body = CacheUtils.copyBody(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.magnet.max.android.rest.qos.internal.CacheManager.java

License:Apache License

public Response getCachedResponse(Request request, CacheOptions options) {
    String requestHash = CacheUtils.getRequestHash(request);

    ResponseCacheEntity operation = findLatestCache(requestHash, request, options);
    if (null != operation && null != operation.response) {
        long currentTimestamp = System.currentTimeMillis();
        if (operation.getExpiredAt() >= currentTimestamp) {
            Log.d(TAG, "Cache hited and not expired for request " + request.urlString() + " with CallOptions "
                    + options);//from w  ww  . j  a v  a 2 s  .c o m
            return operation.response.toResponse(request);
        } else if (options.isAlwaysUseCacheIfOffline()) {
            boolean isOffline = ConnectivityManager.getInstance()
                    .getConnectivityStatus() == ConnectivityManager.TYPE_NOT_CONNECTED;
            Log.d(TAG, "Cache hited, expired but isAlwaysUseCacheIfOffline (offline = " + isOffline
                    + ") for request " + request.urlString() + " with CallOptions " + options);
            if (isOffline) {
                return operation.response.toResponse(request);
            }
        } else {
            Log.d(TAG, "Cache hited but expired for request " + request.urlString() + " with CallOptions "
                    + options);
        }
    }

    return null;
}

From source file:com.magnet.max.android.rest.qos.internal.CacheManager.java

License:Apache License

public Response cacheResponse(Request request, Response response, CacheOptions options) {
    String requestHash = CacheUtils.getRequestHash(request);
    ResponseCacheEntity operation = findLatestCache(requestHash, request, options);
    long currentTimestamp = System.currentTimeMillis();
    if (null == operation) {
        operation = new ResponseCacheEntity();
        operation.createdAt = currentTimestamp;
        operation.url = request.urlString();
        operation.httpMethod = request.method();
        operation.requestHash = requestHash;
        operation.response = new CachedResponse(response);
        operation.responseCode = response.code();
        operation.isOfflineCache = options.isAlwaysUseCacheIfOffline();

        Log.d(TAG, "Adding cache for request " + request);
    } else {//from www  .  j  a v  a 2 s.c om
        //Update body
        operation.response = new CachedResponse(response);
        Log.d(TAG, "Updating cache for request " + request);
    }
    operation.updatedAt = currentTimestamp;
    long newExpiredTime = 0;
    if (options.getMaxCacheAge() > 0) {
        newExpiredTime = currentTimestamp + options.getMaxCacheAge() * 1000;
    }
    if (null == operation.getExpiredAt() || newExpiredTime > operation.getExpiredAt()) {
        operation.expiredAt = newExpiredTime;
    }
    operation.save();

    if (null != response.body()) {
        return response.newBuilder()
                .body(ResponseBody.create(response.body().contentType(), operation.response.body)).build();
    } else {
        return response;
    }
}

From source file:com.magnet.max.android.rest.qos.internal.CacheUtils.java

License:Apache License

public static String getRequestHash(Request request) {
    StringBuilder sb = new StringBuilder();
    //Method and URL
    sb.append(request.method()).append(request.urlString());
    //Headers//w w w  .  j a  v  a  2s  . c  o  m
    if (null != request.headers()) {

    }
    //Body
    //Don't include body when it's multipart
    if (toHashBody(request)) {
        try {
            Buffer buffer = new Buffer();
            Request copy = request.newBuilder().build();
            copy.body().writeTo(buffer);
            sb.append(buffer.readUtf8());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return Util.md5Hex(sb.toString());
}

From source file:com.magnet.max.android.rest.qos.internal.ReliableManager.java

License:Apache License

public void saveRequest(Request request, ReliableCallOptions options, String reason) {
    String requestHash = CacheUtils.getRequestHash(request);
    ReliableRequestEntity operation = null; //findRequest(requestHash, request, options);
    long currentTimestamp = System.currentTimeMillis();
    if (null == operation) {
        operation = new ReliableRequestEntity();
        operation.createdAt = currentTimestamp;
        operation.url = request.urlString();
        operation.httpMethod = request.method();
        operation.requestHash = requestHash;
        operation.request = new CachedRequest(request);
        operation.options = options;//from www  . ja  v  a2  s.c  om
        operation.wifiPreq = hasPrerequisite(options.getConditions(), WifiCondition.class);

        Log.d(TAG, "Saving reliable request " + request);
    } else {
        //Update body
        Log.d(TAG, "Updating reliable request " + request);
        operation.retries = operation.retries + 1;
    }
    operation.updatedAt = currentTimestamp;
    long newExpiredTime = currentTimestamp + options.getExpiresIn() * 1000;
    if (null == operation.getExpiredAt() || newExpiredTime > operation.getExpiredAt()) {
        operation.expiredAt = newExpiredTime;
    }
    if (StringUtil.isNotEmpty(reason)) {
        operation.lastFailureReason = reason;
    }
    operation.lastFailureTime = currentTimestamp;
    operation.save();
}

From source file:com.magnet.max.android.rest.RequestInterceptor.java

License:Apache License

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Log.i(TAG, "---------Intercepting url : " + request.method() + " " + request.urlString());

    CallOptions options = requestManager.popRequestOptions(request);
    boolean isCacheEnabled = null != options && null != options.getCacheOptions();
    if (isCacheEnabled) {
        if (options.getCacheOptions().isAlwaysUseCacheIfOffline() && ConnectivityManager.getInstance()
                .getConnectivityStatus() == ConnectivityManager.TYPE_NOT_CONNECTED) {
            Response cachedResponse = cacheManager.getCachedResponse(request, options.getCacheOptions());
            if (null != cachedResponse) {
                Log.d(TAG, "-------return from cache when isAlwaysUseCacheIfOffline==true and offline");
                return cachedResponse;
            } else {
                throw new IOException("It's offline and no cached response found");
            }/*from   w  w w  .  j  a va 2s  .  c  o m*/
        } else if (options.getCacheOptions().getMaxCacheAge() > 0) { // Return from cache if it's not expired
            Response cachedResponse = cacheManager.getCachedResponse(request, options.getCacheOptions());
            if (null != cachedResponse) {
                Log.d(TAG, "-------return from cache when maxCacheAge = "
                        + options.getCacheOptions().getMaxCacheAge());
                return cachedResponse;
            }
        }
    }

    //Add auth token for network call
    String token = null;
    if ((authTokenProvider.isAuthEnabled() && authTokenProvider.isAuthRequired(request))
            && (null != authTokenProvider.getAppToken() || null != authTokenProvider.getUserToken())) {
        String existingToken = request.header(AuthUtil.AUTHORIZATION_HEADER);
        if (null != existingToken && existingToken.startsWith("Basic")) {
            // Already has Basic Auth header, don't overwrite
        } else {
            token = getToken();
        }
    }

    boolean useMock = false;
    if (null != options) {
        if (isCacheEnabled) {
            useMock = options.getCacheOptions().useMock();
        } else if (null != options.getReliableCallOptions()) {
            useMock = options.getReliableCallOptions().useMock();
        }
    }

    Response response = null;
    long startTime = System.currentTimeMillis();
    try {
        // Modify request
        if (null != token || useMock) {
            Request.Builder newRequestBuilder = chain.request().newBuilder();

            if (null != token) {
                newRequestBuilder.header(AuthUtil.AUTHORIZATION_HEADER, AuthUtil.generateOAuthToken(token));
            }

            if (useMock) {
                newRequestBuilder.url(request.urlString().replace(RestConstants.REST_BASE_PATH,
                        RestConstants.REST_MOCK_BASE_PATH));
            }

            response = chain.proceed(newRequestBuilder.build());
        } else {
            response = chain.proceed(request);
        }

        if (null != options && options.isReliable()) { // Reliable call
            requestManager.removeReliableRequest(request);
        }
    } catch (IOException e) {
        //if(null != options && options.isReliable()) { // Reliable call
        //  requestManager.saveReliableRequest(request, null, null, options.getReliableCallOptions(), e.getMessage());
        //  //TODO :
        //  return null;  // Swallow exception
        //} else {
        //  throw e;
        //}
        Log.e(TAG, "error when getting response", e);
        throw e;
    }

    Log.d(TAG,
            "---------Response for url : " + request.method() + " " + request.urlString() + " : code = "
                    + response.code() + ", message = " + response.message() + " in "
                    + (System.currentTimeMillis() - startTime) + " ms");

    //Save/Update response in cache
    if (response.isSuccessful() && isCacheEnabled && (options.getCacheOptions().getMaxCacheAge() > 0
            || options.getCacheOptions().isAlwaysUseCacheIfOffline())) {
        return cacheManager.cacheResponse(request, response, options.getCacheOptions());
    }

    return response;
}

From source file:com.microsoft.rest.credentials.ApplicationTokenCredentialsInterceptor.java

License:Open Source License

private String acquireAccessToken(Request request) throws IOException {
    String authorityUrl = credentials.getEnvironment().getAuthenticationEndpoint() + credentials.getDomain();
    AuthenticationContext context = new AuthenticationContext(authorityUrl,
            credentials.getEnvironment().isValidateAuthority(), Executors.newSingleThreadExecutor());
    AuthenticationResult result;/*  w  ww. j ava 2s .c  om*/
    try {
        result = context.acquireToken(credentials.getEnvironment().getTokenAudience(),
                new ClientCredential(credentials.getClientId(), credentials.getSecret()), null).get();
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    }
    if (result != null && result.getAccessToken() != null) {
        return result.getAccessToken();
    } else {
        throw new IOException("Failed to acquire access token for request url " + request.urlString());
    }
}

From source file:com.microsoft.rest.credentials.UserTokenCredentialsInterceptor.java

License:Open Source License

private String acquireAccessToken(Request request) throws IOException {
    String authorityUrl = credentials.getEnvironment().getAuthenticationEndpoint() + credentials.getDomain();
    AuthenticationContext context = new AuthenticationContext(authorityUrl,
            credentials.getEnvironment().isValidateAuthority(), Executors.newSingleThreadExecutor());
    AuthenticationResult result;//  ww  w .  j  ava 2  s . c om
    try {
        result = context.acquireToken(credentials.getEnvironment().getTokenAudience(),
                credentials.getClientId(), credentials.getUsername(), credentials.getPassword(), null).get();
    } catch (Exception e) {
        throw new IOException(e.getMessage(), e);
    }
    if (result != null && result.getAccessToken() != null) {
        return result.getAccessToken();
    } else {
        throw new IOException("Failed to acquire access token for request url " + request.urlString());
    }
}

From source file:com.navercorp.pinpoint.plugin.okhttp.interceptor.HttpEngineSendRequestMethodInterceptor.java

License:Apache License

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args);
    }//from w  ww.j ava 2  s.  c o m

    final Trace trace = traceContext.currentTraceObject();
    if (trace == null) {
        return;
    }

    if (!validate(target)) {
        return;
    }

    try {
        SpanEventRecorder recorder = trace.currentSpanEventRecorder();
        recorder.recordApi(methodDescriptor);
        recorder.recordException(throwable);
        // typeCheck validate();
        Request request = ((UserRequestGetter) target)._$PINPOINT$_getUserRequest();
        if (request != null) {
            try {
                recorder.recordAttribute(AnnotationKey.HTTP_URL,
                        InterceptorUtils.getHttpUrl(request.urlString(), param));
                final String endpoint = getDestinationId(request.url());
                recorder.recordDestinationId(endpoint);
            } catch (Exception ignored) {
                logger.warn("Failed to invoke of request.url(). {}", ignored.getMessage());
            }
            recordRequest(trace, request, throwable);
        }

        // clear attachment.
        InterceptorScopeInvocation invocation = interceptorScope.getCurrentInvocation();
        if (invocation != null && invocation.getAttachment() != null) {
            invocation.removeAttachment();
        }
    } finally {
        trace.traceBlockEnd();
    }
}

From source file:com.navercorp.pinpoint.plugin.okhttp.v2.interceptor.HttpEngineSendRequestMethodInterceptor.java

License:Apache License

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args);
    }//  ww  w  .  j av  a  2s. co  m

    final Trace trace = traceContext.currentTraceObject();
    if (trace == null) {
        return;
    }

    if (!validate(target)) {
        return;
    }

    try {
        final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
        recorder.recordApi(methodDescriptor);
        recorder.recordException(throwable);

        // clear attachment.
        final InterceptorScopeInvocation invocation = interceptorScope.getCurrentInvocation();
        final Object attachment = getAttachment(invocation);
        if (attachment != null) {
            invocation.removeAttachment();
        }

        // typeCheck validate();
        final Request request = ((UserRequestGetter) target)._$PINPOINT$_getUserRequest();
        if (request != null) {
            try {
                recorder.recordAttribute(AnnotationKey.HTTP_URL,
                        InterceptorUtils.getHttpUrl(request.urlString(), param));
                final String endpoint = getDestinationId(request.url());
                recorder.recordDestinationId(endpoint);
            } catch (Exception ignored) {
                logger.warn("Failed to invoke of request.url(). {}", ignored.getMessage());
            }
            recordRequest(trace, request, throwable);
        }

    } finally {
        trace.traceBlockEnd();
    }
}