Search in sources :

Example 36 with ByteArrayContent

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

the class MockHttpServerTest method testUrlMismatch_fails.

/**
 * Tests behavior when URL validation is enabled and the URL of the request does not match the
 * server's URL.
 */
@Test
public void testUrlMismatch_fails() throws IOException {
    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)));
    mockHttpServer.setMockResponse(new MockResponse("test response"));
    thrown.expect(ConnectException.class);
    request.execute();
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) GenericUrl(com.google.api.client.http.GenericUrl) ByteArrayContent(com.google.api.client.http.ByteArrayContent) Test(org.junit.Test)

Example 37 with ByteArrayContent

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

the class MockHttpServerTest method testMultipleResponseBodiesSet.

/**
 * Tests behavior when response body is set for multiple requests.
 */
@Test
public void testMultipleResponseBodiesSet() throws IOException {
    HttpRequest request = mockHttpServer.getHttpTransport().createRequestFactory().buildGetRequest(new GenericUrl(mockHttpServer.getServerUrl()));
    String requestContent = "test request";
    request.setContent(new ByteArrayContent("text", requestContent.getBytes(UTF_8)));
    List<MockResponse> expectedResponses = Lists.newArrayList(new MockResponse("test response 1"), new MockResponse("test response 2"));
    mockHttpServer.setMockResponses(expectedResponses);
    for (int i = 0; i < expectedResponses.size(); i++) {
        HttpResponse response = request.execute();
        ActualResponse actualResponse = mockHttpServer.getAllResponses().get(i);
        assertEquals(200, response.getStatusCode());
        assertEquals("Response contents incorrect", expectedResponses.get(i).getBody(), Streams.readAll(response.getContent(), response.getContentCharset()));
        assertEquals("Location header incorrect on response", mockHttpServer.getServerUrl(), response.getHeaders().getLocation());
        assertFalse("No gzip header passed, but request was compressed", actualResponse.wasRequestBodyCompressed());
        assertEquals("Incorrect request contents", requestContent, actualResponse.getRequestBody());
        assertEquals("Incorrect response contents", i + 1, mockHttpServer.getAllResponses().size());
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) 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 38 with ByteArrayContent

use of com.google.api.client.http.ByteArrayContent 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 39 with ByteArrayContent

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

the class BatchJobUploaderTest method testUploadIncrementalBatchJobOperations_notFirst.

@Test
public void testUploadIncrementalBatchJobOperations_notFirst() throws Exception {
    BatchJobUploadStatus status = new BatchJobUploadStatus(10, URI.create(mockHttpServer.getServerUrl()));
    String uploadRequestBody = "<mutate>testUpload</mutate>";
    when(uploadBodyProvider.getHttpContent(request, false, true)).thenReturn(new ByteArrayContent(null, uploadRequestBody.getBytes(UTF_8)));
    mockHttpServer.setMockResponse(new MockResponse("testUploadResponse"));
    // Invoked the incremental upload method.
    BatchJobUploadResponse response = uploader.uploadIncrementalBatchJobOperations(request, true, status);
    assertEquals("Should have made one request", 1, mockHttpServer.getAllResponses().size());
    // Check the request.
    String firstRequest = mockHttpServer.getLastResponse().getRequestBody();
    String expectedBody = "testUpload</mutate>";
    expectedBody = Strings.padEnd(expectedBody, BatchJobUploader.REQUIRED_CONTENT_LENGTH_INCREMENT, ' ');
    assertEquals("Request body is incorrect", expectedBody, firstRequest);
    assertEquals("Request should have succeeded", 200, response.getHttpStatus());
    // Check the BatchJobUploadStatus.
    BatchJobUploadStatus expectedStatus = new BatchJobUploadStatus(status.getTotalContentLength() + expectedBody.getBytes(UTF_8).length, URI.create(mockHttpServer.getServerUrl()));
    BatchJobUploadStatus actualStatus = response.getBatchJobUploadStatus();
    assertEquals("Status total content length is incorrect", expectedStatus.getTotalContentLength(), actualStatus.getTotalContentLength());
    assertEquals("Status resumable upload URI is incorrect", expectedStatus.getResumableUploadUri(), actualStatus.getResumableUploadUri());
}
Also used : MockResponse(com.google.api.ads.common.lib.testing.MockResponse) ByteArrayContent(com.google.api.client.http.ByteArrayContent) Test(org.junit.Test)

Example 40 with ByteArrayContent

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

the class BatchJobUploaderTest method testUploadBatchJobOperations_initiateFails_fails.

/**
 * Tests that IOExceptions from initiating an upload are propagated properly.
 */
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_initiateFails_fails() throws Exception {
    final IOException ioException = new IOException("mock IO exception");
    MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest() {

        @Override
        public LowLevelHttpResponse execute() throws IOException {
            throw ioException;
        }
    };
    when(uploadBodyProvider.getHttpContent(request, true, true)).thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
    MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpRequest(lowLevelHttpRequest).build();
    uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
    thrown.expect(BatchJobException.class);
    thrown.expectCause(Matchers.sameInstance(ioException));
    thrown.expectMessage("initiate upload");
    uploader.uploadIncrementalBatchJobOperations(request, true, new BatchJobUploadStatus(0, URI.create("http://www.example.com")));
}
Also used : MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) IOException(java.io.IOException) ByteArrayContent(com.google.api.client.http.ByteArrayContent) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Test(org.junit.Test)

Aggregations

ByteArrayContent (com.google.api.client.http.ByteArrayContent)43 GenericUrl (com.google.api.client.http.GenericUrl)24 HttpRequest (com.google.api.client.http.HttpRequest)17 IOException (java.io.IOException)12 Test (org.junit.Test)12 HttpResponse (com.google.api.client.http.HttpResponse)10 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)7 HttpContent (com.google.api.client.http.HttpContent)6 HttpHeaders (com.google.api.client.http.HttpHeaders)6 Gson (com.google.gson.Gson)6 MockResponse (com.google.api.ads.common.lib.testing.MockResponse)4 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)4 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)4 File (com.google.api.services.drive.model.File)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 Credential (com.google.api.client.auth.oauth2.Credential)3 GoogleCredential (com.google.api.client.googleapis.auth.oauth2.GoogleCredential)3 HttpResponseException (com.google.api.client.http.HttpResponseException)3 InputStreamContent (com.google.api.client.http.InputStreamContent)3 AbstractInputStreamContent (com.google.api.client.http.AbstractInputStreamContent)2