com.google.api.client.http.GenericUrl

Here are the examples of the java api class com.google.api.client.http.GenericUrl taken from open source projects.

1. UserAuthorizer#getAuthorizationUrl()

View license
/**
   * Return an URL that performs the authorization consent prompt web UI.
   *
   * @param userId Application's identifier for the end user.
   * @param state State that is passed on to the OAuth2 callback URI after the consent.
   * @param baseUri The URI to resolve the OAuth2 callback URI relative to.
   * @return The URL that can be navigated or redirected to.
   */
public URL getAuthorizationUrl(String userId, String state, URI baseUri) {
    URI resolvedCallbackUri = getCallbackUri(baseUri);
    String scopesString = Joiner.on(' ').join(scopes);
    GenericUrl url = new GenericUrl(userAuthUri);
    url.put("response_type", "code");
    url.put("client_id", clientId.getClientId());
    url.put("redirect_uri", resolvedCallbackUri);
    url.put("scope", scopesString);
    if (state != null) {
        url.put("state", state);
    }
    url.put("access_type", "offline");
    url.put("approval_prompt", "force");
    if (userId != null) {
        url.put("login_hint", userId);
    }
    url.put("include_granted_scopes", true);
    return url.toURL();
}

2. UploadIdResponseInterceptorTest#buildHttpResponse()

View license
/**
   * Builds a HttpResponse with the given string response.
   *
   * @param header header value to provide or null if none.
   * @param uploadId upload id to provide in the url upload id param or null if none.
   * @param uploadType upload type to provide in url upload type param or null if none.
   * @return HttpResponse with the given parameters
   * @throws IOException
   */
private HttpResponse buildHttpResponse(String header, String uploadId, String uploadType) throws IOException {
    MockHttpTransport.Builder builder = new MockHttpTransport.Builder();
    MockLowLevelHttpResponse resp = new MockLowLevelHttpResponse();
    builder.setLowLevelHttpResponse(resp);
    resp.setStatusCode(200);
    GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
    if (header != null) {
        resp.addHeader("X-GUploader-UploadID", header);
    }
    if (uploadId != null) {
        url.put("upload_id", uploadId);
    }
    if (uploadType != null) {
        url.put("uploadType", uploadType);
    }
    return builder.build().createRequestFactory().buildGetRequest(url).execute();
}

3. UploadIdResponseInterceptorTest#buildHttpResponse()

View license
/**
   * Builds a HttpResponse with the given string response.
   *
   * @param header header value to provide or null if none.
   * @param uploadId upload id to provide in the url upload id param or null if none.
   * @param uploadType upload type to provide in url upload type param or null if none.
   * @return HttpResponse with the given parameters
   * @throws IOException
   */
private HttpResponse buildHttpResponse(String header, String uploadId, String uploadType) throws IOException {
    MockHttpTransport.Builder builder = new MockHttpTransport.Builder();
    MockLowLevelHttpResponse resp = new MockLowLevelHttpResponse();
    builder.setLowLevelHttpResponse(resp);
    resp.setStatusCode(200);
    GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
    if (header != null) {
        resp.addHeader("X-GUploader-UploadID", header);
    }
    if (uploadId != null) {
        url.put("upload_id", uploadId);
    }
    if (uploadType != null) {
        url.put("uploadType", uploadType);
    }
    return builder.build().createRequestFactory().buildGetRequest(url).execute();
}

4. UploadIdResponseInterceptor#interceptResponse()

View license
@Override
public void interceptResponse(HttpResponse response) throws IOException {
    if (!LOG.isDebugEnabled()) {
        return;
    }
    String uploadId = response.getHeaders().getFirstHeaderStringValue(UPLOAD_HEADER);
    if (uploadId == null) {
        return;
    }
    GenericUrl url = response.getRequest().getUrl();
    // The check for upload type makes sure this is an upload and not a read.
    if (url.get(UPLOAD_ID_PARAM) == null && url.get(UPLOAD_TYPE_PARAM) != null) {
        LOG.debug("Upload ID for url {} on worker {} is {}", url, System.getProperty("worker_id"), uploadId);
    }
}

5. LocalDevelopmentDatastore#stopDatastoreInternal()

View license
void stopDatastoreInternal() throws LocalDevelopmentDatastoreException {
    // No need to kill the process we started, this function will take care of it.
    HttpRequestFactory client = remoteRpc.getHttpRequestFactory();
    Map<String, String> params = new HashMap<String, String>();
    UrlEncodedContent content = new UrlEncodedContent(params);
    GenericUrl url = new GenericUrl(host + "/_ah/admin/quit");
    try {
        HttpResponse httpResponse = client.buildPostRequest(url, content).execute();
        if (!httpResponse.isSuccessStatusCode()) {
            throw new LocalDevelopmentDatastoreException("Request to shutdown local datastore returned http error code " + httpResponse.getStatusCode());
        }
    } catch (IOException e) {
        throw new LocalDevelopmentDatastoreException("Exception trying to stop the dev datastore", e);
    }
}

6. UploadIdResponseInterceptor#interceptResponse()

View license
@Override
public void interceptResponse(HttpResponse response) throws IOException {
    if (!LOG.isDebugEnabled()) {
        return;
    }
    String uploadId = response.getHeaders().getFirstHeaderStringValue(UPLOAD_HEADER);
    if (uploadId == null) {
        return;
    }
    GenericUrl url = response.getRequest().getUrl();
    // The check for upload type makes sure this is an upload and not a read.
    if (url.get(UPLOAD_ID_PARAM) == null && url.get(UPLOAD_TYPE_PARAM) != null) {
        LOG.debug("Upload ID for url {} on worker {} is {}", url, System.getProperty("worker_id"), uploadId);
    }
}

7. OAuthParameters#computeSignature()

View license
/**
   * Computes a new signature based on the fields and the given request method and URL, setting the
   * values of the {@link #signature} and {@link #signatureMethod} fields.
   *
   * @throws GeneralSecurityException general security exception
   */
public void computeSignature(String requestMethod, GenericUrl requestUrl) throws GeneralSecurityException {
    OAuthSigner signer = this.signer;
    String signatureMethod = this.signatureMethod = signer.getSignatureMethod();
    // oauth_* parameters (except oauth_signature)
    TreeMap<String, String> parameters = new TreeMap<String, String>();
    putParameterIfValueNotNull(parameters, "oauth_callback", callback);
    putParameterIfValueNotNull(parameters, "oauth_consumer_key", consumerKey);
    putParameterIfValueNotNull(parameters, "oauth_nonce", nonce);
    putParameterIfValueNotNull(parameters, "oauth_signature_method", signatureMethod);
    putParameterIfValueNotNull(parameters, "oauth_timestamp", timestamp);
    putParameterIfValueNotNull(parameters, "oauth_token", token);
    putParameterIfValueNotNull(parameters, "oauth_verifier", verifier);
    putParameterIfValueNotNull(parameters, "oauth_version", version);
    // parse request URL for query parameters
    for (Map.Entry<String, Object> fieldEntry : requestUrl.entrySet()) {
        Object value = fieldEntry.getValue();
        if (value != null) {
            String name = fieldEntry.getKey();
            if (value instanceof Collection<?>) {
                for (Object repeatedValue : (Collection<?>) value) {
                    putParameter(parameters, name, repeatedValue);
                }
            } else {
                putParameter(parameters, name, value);
            }
        }
    }
    // normalize parameters
    StringBuilder parametersBuf = new StringBuilder();
    boolean first = true;
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        if (first) {
            first = false;
        } else {
            parametersBuf.append('&');
        }
        parametersBuf.append(entry.getKey());
        String value = entry.getValue();
        if (value != null) {
            parametersBuf.append('=').append(value);
        }
    }
    String normalizedParameters = parametersBuf.toString();
    // normalize URL, removing any query parameters and possibly port
    GenericUrl normalized = new GenericUrl();
    String scheme = requestUrl.getScheme();
    normalized.setScheme(scheme);
    normalized.setHost(requestUrl.getHost());
    normalized.setPathParts(requestUrl.getPathParts());
    int port = requestUrl.getPort();
    if ("http".equals(scheme) && port == 80 || "https".equals(scheme) && port == 443) {
        port = -1;
    }
    normalized.setPort(port);
    String normalizedPath = normalized.build();
    // signature base string
    StringBuilder buf = new StringBuilder();
    buf.append(escape(requestMethod)).append('&');
    buf.append(escape(normalizedPath)).append('&');
    buf.append(escape(normalizedParameters));
    String signatureBaseString = buf.toString();
    signature = signer.computeSignature(signatureBaseString);
}

8. MethodOverrideTest#testInterceptMaxLength()

View license
public void testInterceptMaxLength() throws IOException {
    HttpTransport transport = new MockHttpTransport();
    GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
    url.set("a", "foo");
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    new MethodOverride().intercept(request);
    assertEquals(HttpMethods.GET, request.getRequestMethod());
    assertNull(request.getHeaders().get(MethodOverride.HEADER));
    assertNull(request.getContent());
    char[] arr = new char[MethodOverride.MAX_URL_LENGTH];
    Arrays.fill(arr, 'x');
    url.set("a", new String(arr));
    request.setUrl(url);
    new MethodOverride().intercept(request);
    assertEquals(HttpMethods.POST, request.getRequestMethod());
    assertEquals(HttpMethods.GET, request.getHeaders().get(MethodOverride.HEADER));
    assertEquals(HttpTesting.SIMPLE_GENERIC_URL, request.getUrl());
    char[] arr2 = new char[arr.length + 2];
    Arrays.fill(arr2, 'x');
    arr2[0] = 'a';
    arr2[1] = '=';
    UrlEncodedContent content = (UrlEncodedContent) request.getContent();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    content.writeTo(out);
    assertEquals(new String(arr2), out.toString());
}

9. UserAuthorizer#revokeAuthorization()

View license
/**
   * Revokes the authorization for tokens stored for the user.
   * @param userId Application's identifier for the end user.
   * @throws IOException An error calling the revoke API or deleting the state.
   */
public void revokeAuthorization(String userId) throws IOException {
    Preconditions.checkNotNull(userId);
    if (tokenStore == null) {
        throw new IllegalStateException("Method cannot be called if token store is not specified.");
    }
    String tokenData = tokenStore.load(userId);
    if (tokenData == null) {
        return;
    }
    IOException deleteTokenException = null;
    try {
        // Delete the stored version first. If token reversion fails it is less harmful to have an
        // non revoked token to hold on to a potentially revoked token.
        tokenStore.delete(userId);
    } catch (IOException e) {
        deleteTokenException = e;
    }
    GenericJson tokenJson = OAuth2Utils.parseJson(tokenData);
    String accessTokenValue = OAuth2Utils.validateOptionalString(tokenJson, "access_token", TOKEN_STORE_ERROR);
    String refreshToken = OAuth2Utils.validateOptionalString(tokenJson, "refresh_token", TOKEN_STORE_ERROR);
    // If both tokens are present, either can be used
    String revokeToken = (refreshToken != null) ? refreshToken : accessTokenValue;
    GenericUrl revokeUrl = new GenericUrl(OAuth2Utils.TOKEN_REVOKE_URI);
    revokeUrl.put("token", revokeToken);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest tokenRequest = requestFactory.buildGetRequest(revokeUrl);
    tokenRequest.execute();
    if (deleteTokenException != null) {
        throw deleteTokenException;
    }
}

10. ClientLogin#authenticate()

View license
/**
   * Authenticates based on the provided field values.
   *
   * @throws ClientLoginResponseException if the authentication response has an error code, such as
   *         for a CAPTCHA challenge.
   */
public Response authenticate() throws IOException {
    GenericUrl url = serverUrl.clone();
    url.appendRawPath("/accounts/ClientLogin");
    HttpRequest request = transport.createRequestFactory().buildPostRequest(url, new UrlEncodedContent(this));
    request.setParser(AuthKeyValueParser.INSTANCE);
    request.setContentLoggingLimit(0);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    // check for an HTTP success response (2xx)
    if (response.isSuccessStatusCode()) {
        return response.parseAs(Response.class);
    }
    HttpResponseException.Builder builder = new HttpResponseException.Builder(response.getStatusCode(), response.getStatusMessage(), response.getHeaders());
    // On error, throw a ClientLoginResponseException with the parsed error details
    ErrorInfo details = response.parseAs(ErrorInfo.class);
    String detailString = details.toString();
    StringBuilder message = HttpResponseException.computeMessageBuffer(response);
    if (!Strings.isNullOrEmpty(detailString)) {
        message.append(StringUtils.LINE_SEPARATOR).append(detailString);
        builder.setContent(detailString);
    }
    builder.setMessage(message.toString());
    throw new ClientLoginResponseException(builder, details);
}

11. UploadIdResponseInterceptorTest#testResponseLogs()

View license
/**
   * Check that a response logs with the correct log.
   */
@Test
public void testResponseLogs() throws IOException {
    new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse("abc", null, "type"));
    GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
    url.put("uploadType", "type");
    String worker = System.getProperty("worker_id");
    expectedLogs.verifyDebug("Upload ID for url " + url + " on worker " + worker + " is abc");
}

12. UploadIdResponseInterceptorTest#testResponseLogs()

View license
/**
   * Check that a response logs with the correct log.
   */
@Test
public void testResponseLogs() throws IOException {
    new UploadIdResponseInterceptor().interceptResponse(buildHttpResponse("abc", null, "type"));
    GenericUrl url = new GenericUrl(HttpTesting.SIMPLE_URL);
    url.put("uploadType", "type");
    String worker = System.getProperty("worker_id");
    expectedLogs.verifyDebug("Upload ID for url " + url + " on worker " + worker + " is abc");
}

13. ComputeCredential#executeRefreshToken()

View license
@Override
protected TokenResponse executeRefreshToken() throws IOException {
    GenericUrl tokenUrl = new GenericUrl(getTokenServerEncodedUrl());
    HttpRequest request = getTransport().createRequestFactory().buildGetRequest(tokenUrl);
    request.setParser(new JsonObjectParser(getJsonFactory()));
    request.getHeaders().set("Metadata-Flavor", "Google");
    return request.execute().parseAs(TokenResponse.class);
}

14. MediaHttpUploader#resumableUpload()

View license
/**
   * Uploads the media in a resumable manner.
   *
   * @param initiationRequestUrl The request URL where the initiation request will be sent
   * @return HTTP response
   */
private HttpResponse resumableUpload(GenericUrl initiationRequestUrl) throws IOException {
    // Make initial request to get the unique upload URL.
    HttpResponse initialResponse = executeUploadInitiation(initiationRequestUrl);
    if (!initialResponse.isSuccessStatusCode()) {
        // If the initiation request is not successful return it immediately.
        return initialResponse;
    }
    GenericUrl uploadUrl;
    try {
        uploadUrl = new GenericUrl(initialResponse.getHeaders().getLocation());
    } finally {
        initialResponse.disconnect();
    }
    // Convert media content into a byte stream to upload in chunks.
    contentInputStream = mediaContent.getInputStream();
    if (!contentInputStream.markSupported() && isMediaLengthKnown()) {
        // If we know the media content length then wrap the stream into a Buffered input stream to
        // support the {@link InputStream#mark} and {@link InputStream#reset} methods required for
        // handling server errors.
        contentInputStream = new BufferedInputStream(contentInputStream);
    }
    HttpResponse response;
    // Upload the media content in chunks.
    while (true) {
        currentRequest = requestFactory.buildPutRequest(uploadUrl, null);
        setContentAndHeadersOnCurrentRequest();
        // set mediaErrorHandler as I/O exception handler and as unsuccessful response handler for
        // calling to serverErrorCallback on an I/O exception or an abnormal HTTP response
        new MediaUploadErrorHandler(this, currentRequest);
        if (isMediaLengthKnown()) {
            // TODO(rmistry): Support gzipping content for the case where media content length is
            // known (https://code.google.com/p/google-api-java-client/issues/detail?id=691).
            response = executeCurrentRequestWithoutGZip(currentRequest);
        } else {
            response = executeCurrentRequest(currentRequest);
        }
        boolean returningResponse = false;
        try {
            if (response.isSuccessStatusCode()) {
                totalBytesServerReceived = getMediaContentLength();
                if (mediaContent.getCloseInputStream()) {
                    contentInputStream.close();
                }
                updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE);
                returningResponse = true;
                return response;
            }
            if (response.getStatusCode() != 308) {
                returningResponse = true;
                return response;
            }
            // Check to see if the upload URL has changed on the server.
            String updatedUploadUrl = response.getHeaders().getLocation();
            if (updatedUploadUrl != null) {
                uploadUrl = new GenericUrl(updatedUploadUrl);
            }
            // we check the amount of bytes the server received so far, because the server may process
            // fewer bytes than the amount of bytes the client had sent
            long newBytesServerReceived = getNextByteIndex(response.getHeaders().getRange());
            // the server can receive any amount of bytes from 0 to current chunk length
            long currentBytesServerReceived = newBytesServerReceived - totalBytesServerReceived;
            Preconditions.checkState(currentBytesServerReceived >= 0 && currentBytesServerReceived <= currentChunkLength);
            long copyBytes = currentChunkLength - currentBytesServerReceived;
            if (isMediaLengthKnown()) {
                if (copyBytes > 0) {
                    // If the server didn't receive all the bytes the client sent the current position of
                    // the input stream is incorrect. So we should reset the stream and skip those bytes
                    // that the server had already received.
                    // Otherwise (the server got all bytes the client sent), the stream is in its right
                    // position, and we can continue from there
                    contentInputStream.reset();
                    long actualSkipValue = contentInputStream.skip(currentBytesServerReceived);
                    Preconditions.checkState(currentBytesServerReceived == actualSkipValue);
                }
            } else if (copyBytes == 0) {
                // server got all the bytes, so we don't need to use this buffer. Otherwise, we have to
                // keep the buffer and copy part (or all) of its bytes to the stream we are sending to the
                // server
                currentRequestContentBuffer = null;
            }
            totalBytesServerReceived = newBytesServerReceived;
            updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS);
        } finally {
            if (!returningResponse) {
                response.disconnect();
            }
        }
    }
}

15. ComputeEngineCredentials#refreshAccessToken()

View license
/**
   * Refresh the access token by getting it from the GCE metadata server
   */
@Override
public AccessToken refreshAccessToken() throws IOException {
    GenericUrl tokenUrl = new GenericUrl(TOKEN_SERVER_ENCODED_URL);
    HttpRequest request = transport.createRequestFactory().buildGetRequest(tokenUrl);
    JsonObjectParser parser = new JsonObjectParser(OAuth2Utils.JSON_FACTORY);
    request.setParser(parser);
    request.getHeaders().set("Metadata-Flavor", "Google");
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = null;
    try {
        response = request.execute();
    } catch (UnknownHostException exception) {
        throw OAuth2Utils.exceptionWithCause(new IOException("ComputeEngineCredentials cannot find" + " the metadata server. This is likely because code is not running on Google Compute" + " Engine."), exception);
    }
    int statusCode = response.getStatusCode();
    if (statusCode == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
        throw new IOException(String.format("Error code %s trying to get security access token from" + " Compute Engine metadata for the default service account. This may be because" + " the virtual machine instance does not have permission scopes specified.", statusCode));
    }
    if (statusCode != HttpStatusCodes.STATUS_CODE_OK) {
        throw new IOException(String.format("Unexpected Error code %s trying to get security access" + " token from Compute Engine metadata for the default service account: %s", statusCode, response.parseAsString()));
    }
    InputStream content = response.getContent();
    if (content == null) {
        // Mock transports will have success code with empty content by default.
        throw new IOException("Empty content from metadata token server request.");
    }
    GenericData responseData = response.parseAs(GenericData.class);
    String accessToken = OAuth2Utils.validateString(responseData, "access_token", PARSE_ERROR_PREFIX);
    int expiresInSeconds = OAuth2Utils.validateInt32(responseData, "expires_in", PARSE_ERROR_PREFIX);
    long expiresAtMilliseconds = clock.currentTimeMillis() + expiresInSeconds * 1000;
    AccessToken access = new AccessToken(accessToken, new Date(expiresAtMilliseconds));
    return access;
}

16. OAuth2Utils#runningOnComputeEngine()

View license
static boolean runningOnComputeEngine(HttpTransport transport, SystemEnvironmentProvider environment) {
    // If the environment has requested that we do no GCE checks, return immediately.
    if (Boolean.parseBoolean(environment.getEnv("NO_GCE_CHECK"))) {
        return false;
    }
    GenericUrl tokenUrl = new GenericUrl(getMetadataServerUrl(environment));
    for (int i = 1; i <= MAX_COMPUTE_PING_TRIES; ++i) {
        try {
            HttpRequest request = transport.createRequestFactory().buildGetRequest(tokenUrl);
            request.setConnectTimeout(COMPUTE_PING_CONNECTION_TIMEOUT_MS);
            HttpResponse response = request.execute();
            try {
                HttpHeaders headers = response.getHeaders();
                return headersContainValue(headers, "Metadata-Flavor", "Google");
            } finally {
                response.disconnect();
            }
        } catch (SocketTimeoutException expected) {
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Failed to detect whether we are running on Google Compute Engine.", e);
        }
    }
    return false;
}

17. HttpRequestIT#execute()

Project: pinpoint
Source File: HttpRequestIT.java
View license
@Test
public void execute() throws Exception {
    HttpTransport NET_HTTP_TRANSPORT = new NetHttpTransport();
    HttpRequestFactory requestFactory = NET_HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
        }
    });
    GenericUrl url = new GenericUrl("http://google.com");
    HttpRequest request = null;
    HttpResponse response = null;
    try {
        request = requestFactory.buildGetRequest(url);
        response = request.execute();
        response.disconnect();
    } catch (IOException ignored) {
    } finally {
        if (response != null) {
            response.disconnect();
        }
    }
    Method executeMethod = HttpRequest.class.getDeclaredMethod("execute");
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    verifier.verifyTrace(Expectations.event("GOOGLE_HTTP_CLIENT_INTERNAL", executeMethod));
}

18. HttpRequestIT#executeAsync()

Project: pinpoint
Source File: HttpRequestIT.java
View license
@Test
public void executeAsync() throws Exception {
    HttpTransport NET_HTTP_TRANSPORT = new NetHttpTransport();
    HttpRequestFactory requestFactory = NET_HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
        }
    });
    GenericUrl url = new GenericUrl("http://google.com");
    HttpRequest request = null;
    HttpResponse response = null;
    try {
        request = requestFactory.buildGetRequest(url);
        response = request.executeAsync().get();
        response.disconnect();
    } catch (IOException ignored) {
    } finally {
        if (response != null) {
            response.disconnect();
        }
    }
    Method executeAsyncMethod = HttpRequest.class.getDeclaredMethod("executeAsync", Executor.class);
    Method callMethod = Callable.class.getDeclaredMethod("call");
    Method executeMethod = HttpRequest.class.getDeclaredMethod("execute");
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    // async
    verifier.verifyTrace(Expectations.async(Expectations.event("GOOGLE_HTTP_CLIENT_INTERNAL", executeAsyncMethod), Expectations.event("ASYNC", "Asynchronous Invocation")));
}