Search in sources :

Example 56 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project copybara by google.

the class GitHubApiTransportImplTest method runTestThrowsHttpResponseException.

private void runTestThrowsHttpResponseException(Callable<?> c) throws Exception {
    HttpResponseException ex = new HttpResponseException.Builder(STATUS_CODE, ERROR_MESSAGE, new HttpHeaders()).build();
    httpTransport = createMockHttpTransport(ex);
    transport = new GitHubApiTransportImpl(repo, httpTransport, "store", new TestingConsole());
    try {
        c.call();
        fail();
    } catch (GitHubApiException e) {
        assertThat(e.getHttpCode()).isEqualTo(STATUS_CODE);
        assertThat(e.getError()).isNull();
    }
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) TestingConsole(com.google.copybara.util.console.testing.TestingConsole) HttpResponseException(com.google.api.client.http.HttpResponseException)

Example 57 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project googleads-java-lib by googleads.

the class MockHttpServerTest method testUrlMismatch_verifyDisabled.

/**
 * Tests behavior when URL validation is disabled.
 */
@Test
public void testUrlMismatch_verifyDisabled() throws IOException {
    MockResponse mockResponse = new MockResponse("test response");
    mockResponse.setValidateUrlMatches(false);
    HttpRequest request = mockHttpServer.getHttpTransport().createRequestFactory().buildGetRequest(new GenericUrl("http://www.example.com/does_not_match_mock_http_server_url"));
    request.setContent(new ByteArrayContent("text", "test content".getBytes(UTF_8)));
    HttpHeaders headers = new HttpHeaders();
    headers.set("one", "1");
    headers.set("two", "2");
    request.setHeaders(headers);
    mockHttpServer.setMockResponse(mockResponse);
    HttpResponse response = request.execute();
    ActualResponse actualResponse = mockHttpServer.getLastResponse();
    assertEquals("Incorrect response code", 200, response.getStatusCode());
    assertEquals("Request header 'one' incorrect", "1", actualResponse.getRequestHeader("one").get(0));
    assertEquals("Request header 'two' incorrect", "2", actualResponse.getRequestHeader("two").get(0));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayContent(com.google.api.client.http.ByteArrayContent) Test(org.junit.Test)

Example 58 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project googleads-java-lib by googleads.

the class BatchJobUploader method uploadIncrementalBatchJobOperations.

/**
 * Incrementally uploads a batch job's operations and returns the response.
 *
 * @param request the request to upload
 * @param isLastRequest if the request is the last request in the sequence of uploads for the job
 * @param batchJobUploadStatus the current upload status of the job
 */
public BatchJobUploadResponse uploadIncrementalBatchJobOperations(final BatchJobMutateRequestInterface request, final boolean isLastRequest, BatchJobUploadStatus batchJobUploadStatus) throws BatchJobException {
    Preconditions.checkNotNull(batchJobUploadStatus, "Null batch job upload status");
    Preconditions.checkNotNull(batchJobUploadStatus.getResumableUploadUri(), "No resumable session URI");
    // This reference is final because it is referenced below within an anonymous class.
    final BatchJobUploadStatus effectiveStatus;
    if (batchJobUploadStatus.getTotalContentLength() == 0) {
        // If this is the first upload, then issue a request to get the resumable session URI from
        // Google Cloud Storage.
        URI uploadUri = initiateResumableUpload(batchJobUploadStatus.getResumableUploadUri());
        effectiveStatus = new BatchJobUploadStatus(0, uploadUri);
    } else {
        effectiveStatus = batchJobUploadStatus;
    }
    // The process below follows the Google Cloud Storage guidelines for resumable
    // uploads of unknown size:
    // https://cloud.google.com/storage/docs/concepts-techniques#unknownresumables
    ByteArrayContent content = request.createBatchJobUploadBodyProvider().getHttpContent(request, effectiveStatus.getTotalContentLength() == 0, isLastRequest);
    try {
        content = postProcessContent(content, effectiveStatus.getTotalContentLength() == 0L, isLastRequest);
    } catch (IOException e) {
        throw new BatchJobException("Failed to post-process the request content", e);
    }
    String requestXml = null;
    Throwable exception = null;
    BatchJobUploadResponse batchJobUploadResponse = null;
    final long contentLength = content.getLength();
    try {
        HttpRequestFactory requestFactory = httpTransport.createRequestFactory(req -> {
            HttpHeaders headers = createHttpHeaders();
            headers.setContentLength(contentLength);
            headers.setContentRange(constructContentRangeHeaderValue(contentLength, isLastRequest, effectiveStatus));
            req.setHeaders(headers);
            req.setLoggingEnabled(true);
        });
        // Incremental uploads require a PUT request.
        HttpRequest httpRequest = requestFactory.buildPutRequest(new GenericUrl(effectiveStatus.getResumableUploadUri()), content);
        requestXml = Streams.readAll(content.getInputStream(), UTF_8);
        content.getInputStream().reset();
        HttpResponse response = httpRequest.execute();
        batchJobUploadResponse = new BatchJobUploadResponse(response, effectiveStatus.getTotalContentLength() + httpRequest.getContent().getLength(), effectiveStatus.getResumableUploadUri());
        return batchJobUploadResponse;
    } catch (HttpResponseException e) {
        if (e.getStatusCode() == 308) {
            // 308 indicates that the upload succeeded.
            batchJobUploadResponse = new BatchJobUploadResponse(new ByteArrayInputStream(new byte[0]), e.getStatusCode(), e.getStatusMessage(), effectiveStatus.getTotalContentLength() + contentLength, effectiveStatus.getResumableUploadUri());
            return batchJobUploadResponse;
        }
        exception = e;
        throw new BatchJobException("Failed response status from batch upload URL.", e);
    } catch (IOException e) {
        exception = e;
        throw new BatchJobException("Problem sending data to batch upload URL.", e);
    } finally {
        batchJobLogger.logUpload(requestXml, effectiveStatus.getResumableUploadUri(), batchJobUploadResponse, exception);
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) HttpResponse(com.google.api.client.http.HttpResponse) HttpResponseException(com.google.api.client.http.HttpResponseException) IOException(java.io.IOException) GenericUrl(com.google.api.client.http.GenericUrl) URI(java.net.URI) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayContent(com.google.api.client.http.ByteArrayContent)

Example 59 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project googleads-java-lib by googleads.

the class BatchJobUploader method initiateResumableUpload.

/**
 * Initiates the resumable upload by sending a request to Google Cloud Storage.
 *
 * @param batchJobUploadUrl the {@code uploadUrl} of a {@code BatchJob}
 * @return the URI for the initiated resumable upload
 */
private URI initiateResumableUpload(URI batchJobUploadUrl) throws BatchJobException {
    // This follows the Google Cloud Storage guidelines for initiating resumable uploads:
    // https://cloud.google.com/storage/docs/resumable-uploads-xml
    HttpRequestFactory requestFactory = httpTransport.createRequestFactory(req -> {
        HttpHeaders headers = createHttpHeaders();
        headers.setContentLength(0L);
        headers.set("x-goog-resumable", "start");
        req.setHeaders(headers);
        req.setLoggingEnabled(true);
    });
    try {
        HttpRequest httpRequest = requestFactory.buildPostRequest(new GenericUrl(batchJobUploadUrl), new EmptyContent());
        HttpResponse response = httpRequest.execute();
        if (response.getHeaders() == null || response.getHeaders().getLocation() == null) {
            throw new BatchJobException("Initiate upload failed. Resumable upload URI was not in the response.");
        }
        return URI.create(response.getHeaders().getLocation());
    } catch (IOException e) {
        throw new BatchJobException("Failed to initiate upload", e);
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpHeaders(com.google.api.client.http.HttpHeaders) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) EmptyContent(com.google.api.client.http.EmptyContent)

Example 60 with HttpHeaders

use of com.google.api.client.http.HttpHeaders in project googleads-java-lib by googleads.

the class ReportRequestFactoryHelper method createHeaders.

/**
 * Creates the http headers object for this request, populated from data in
 * the session.
 * @throws AuthenticationException If OAuth authorization fails.
 */
private HttpHeaders createHeaders(String reportUrl, String version) throws AuthenticationException {
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setAuthorization(authorizationHeaderProvider.getAuthorizationHeader(session, reportUrl));
    httpHeaders.setUserAgent(userAgentCombiner.getUserAgent(session.getUserAgent()));
    httpHeaders.set("developerToken", session.getDeveloperToken());
    httpHeaders.set("clientCustomerId", session.getClientCustomerId());
    ReportingConfiguration reportingConfiguration = session.getReportingConfiguration();
    if (reportingConfiguration != null) {
        reportingConfiguration.validate(version);
        if (reportingConfiguration.isSkipReportHeader() != null) {
            httpHeaders.set("skipReportHeader", Boolean.toString(reportingConfiguration.isSkipReportHeader()));
        }
        if (reportingConfiguration.isSkipColumnHeader() != null) {
            httpHeaders.set("skipColumnHeader", Boolean.toString(reportingConfiguration.isSkipColumnHeader()));
        }
        if (reportingConfiguration.isSkipReportSummary() != null) {
            httpHeaders.set("skipReportSummary", Boolean.toString(reportingConfiguration.isSkipReportSummary()));
        }
        if (reportingConfiguration.isIncludeZeroImpressions() != null) {
            httpHeaders.set("includeZeroImpressions", Boolean.toString(reportingConfiguration.isIncludeZeroImpressions()));
        }
        if (reportingConfiguration.isUseRawEnumValues() != null) {
            httpHeaders.set("useRawEnumValues", Boolean.toString(reportingConfiguration.isUseRawEnumValues()));
        }
    }
    return httpHeaders;
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) ReportingConfiguration(com.google.api.ads.adwords.lib.client.reporting.ReportingConfiguration)

Aggregations

HttpHeaders (com.google.api.client.http.HttpHeaders)63 HttpRequest (com.google.api.client.http.HttpRequest)32 IOException (java.io.IOException)26 GenericUrl (com.google.api.client.http.GenericUrl)22 HttpResponse (com.google.api.client.http.HttpResponse)21 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)15 Test (org.junit.Test)8 GoogleJsonError (com.google.api.client.googleapis.json.GoogleJsonError)7 ByteArrayContent (com.google.api.client.http.ByteArrayContent)6 HttpContent (com.google.api.client.http.HttpContent)6 HttpRequestInitializer (com.google.api.client.http.HttpRequestInitializer)6 HttpResponseException (com.google.api.client.http.HttpResponseException)6 JsonObjectParser (com.google.api.client.json.JsonObjectParser)5 Map (java.util.Map)5 HttpTransport (com.google.api.client.http.HttpTransport)4 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)4 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)4 Objects (com.google.api.services.storage.model.Objects)4 SocketTimeoutException (java.net.SocketTimeoutException)4 URI (java.net.URI)4