com.google.api.client.http.HttpResponse

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

1. StubsAdminPortalsTest#should_AdjustResourceIdHeaderAccordingly_WhenSuccessfulDeleteMade()

Project: stubby4j
Source File: StubsAdminPortalsTest.java
View license
@Test
public void should_AdjustResourceIdHeaderAccordingly_WhenSuccessfulDeleteMade() throws Exception {
    final String stubsRequestUrl = String.format("%s%s", STUBS_URL, "/this/stub/should/always/be/second/in/this/file");
    final HttpRequest stubsGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, stubsRequestUrl);
    final HttpResponse preDeletionStubGetResponse = stubsGetRequest.execute();
    final HttpHeaders preDeletionResponseHeaders = preDeletionStubGetResponse.getHeaders();
    assertThat(preDeletionResponseHeaders.containsKey(StubResponse.STUBBY_RESOURCE_ID_HEADER)).isTrue();
    assertThat(preDeletionResponseHeaders.getFirstHeaderStringValue(StubResponse.STUBBY_RESOURCE_ID_HEADER)).isEqualTo("1");
    final HttpRequest httpDeleteRequest = HttpUtils.constructHttpRequest(HttpMethods.DELETE, String.format("%s%s", ADMIN_URL, "/0"));
    final HttpResponse httpDeleteResponse = httpDeleteRequest.execute();
    final String deleteResponseContent = httpDeleteResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpDeleteResponse.getStatusCode());
    assertThat(deleteResponseContent).isEqualTo("Stub request index#0 deleted successfully");
    final HttpRequest postDeletionStubGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, stubsRequestUrl);
    final HttpResponse postDeletionStubGetResponse = postDeletionStubGetRequest.execute();
    final HttpHeaders postDeletionResponseHeaders = postDeletionStubGetResponse.getHeaders();
    assertThat(postDeletionResponseHeaders.containsKey(StubResponse.STUBBY_RESOURCE_ID_HEADER)).isTrue();
    assertThat(postDeletionResponseHeaders.getFirstHeaderStringValue(StubResponse.STUBBY_RESOURCE_ID_HEADER)).isEqualTo("0");
}

2. StubsAdminPortalsTest#should_ReturnAjaxRequestContent_WhenSuccessfulRequestMade()

Project: stubby4j
Source File: StubsAdminPortalsTest.java
View license
@Test
public void should_ReturnAjaxRequestContent_WhenSuccessfulRequestMade() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/invoice/new");
    final String postContent = "{\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, postContent);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201);
    final String resourceID = response.getHeaders().getFirstHeaderStringValue(StubResponse.STUBBY_RESOURCE_ID_HEADER);
    final String ajaxRequestUrl = String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/request/post");
    final HttpRequest ajaxRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, ajaxRequestUrl);
    final HttpResponse ajaxResponse = ajaxRequest.execute();
    assertThat(ajaxResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(ajaxResponse.parseAsString().trim()).contains(postContent);
}

3. StubsAdminPortalsTest#should_ReturnAjaxResponseContent_WhenSuccessfulRequestMade()

Project: stubby4j
Source File: StubsAdminPortalsTest.java
View license
@Test
public void should_ReturnAjaxResponseContent_WhenSuccessfulRequestMade() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/invoice/new");
    final String postContent = "{\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, postContent);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    final String responseContent = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201);
    final String resourceID = response.getHeaders().getFirstHeaderStringValue(StubResponse.STUBBY_RESOURCE_ID_HEADER);
    final String ajaxRequestUrl = String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/response/body");
    final HttpRequest ajaxRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, ajaxRequestUrl);
    final HttpResponse ajaxResponse = ajaxRequest.execute();
    assertThat(ajaxResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(ajaxResponse.parseAsString().trim()).contains(responseContent);
}

4. StubsAdminPortalsTest#should_ReturnAjaxSequencedResponseContent_WhenSuccessfulRequestMade()

Project: stubby4j
Source File: StubsAdminPortalsTest.java
View license
@Test
public void should_ReturnAjaxSequencedResponseContent_WhenSuccessfulRequestMade() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/uri/with/sequenced/responses/infile");
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    final HttpResponse response = request.execute();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201);
    final String resourceID = response.getHeaders().getFirstHeaderStringValue(StubResponse.STUBBY_RESOURCE_ID_HEADER);
    final String ajaxRequestUrl = String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/response/1/file");
    final HttpRequest ajaxRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, ajaxRequestUrl);
    final HttpResponse ajaxResponse = ajaxRequest.execute();
    assertThat(ajaxResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(ajaxResponse.parseAsString().trim()).contains("Still going strong!");
}

5. GitHubRequest#execute()

View license
@Override
public T execute() throws IOException {
    HttpResponse response = super.executeUnparsed();
    ObjectParser parser = response.getRequest().getParser();
    // This will degrade parsing performance but is an inevitable workaround
    // for the inability to parse JSON arrays.
    String content = response.parseAsString();
    if (response.isSuccessStatusCode() && !TextUtils.isEmpty(content) && content.charAt(0) == '[') {
        content = TextUtils.concat("{\"", GitHubResponse.KEY_DATA, "\":", content, "}").toString();
    }
    Reader reader = new StringReader(content);
    T parsedResponse = parser.parseAndClose(reader, getResponseClass());
    // parse pagination from Link header
    if (parsedResponse instanceof GitHubResponse) {
        Pagination pagination = new Pagination(response.getHeaders().getFirstHeaderStringValue("Link"));
        ((GitHubResponse) parsedResponse).setPagination(pagination);
    }
    return parsedResponse;
}

6. TwitterRequest#execute()

View license
@Override
public T execute() throws IOException {
    HttpResponse response = super.executeUnparsed();
    ObjectParser parser = response.getRequest().getParser();
    // This will degrade parsing performance but is an inevitable workaround
    // for the inability to parse JSON arrays.
    String content = response.parseAsString();
    if (response.isSuccessStatusCode() && !TextUtils.isEmpty(content) && content.charAt(0) == '[') {
        content = TextUtils.concat("{\"", TwitterResponse.KEY_DATA, "\":", content, "}").toString();
    }
    Reader reader = new StringReader(content);
    return parser.parseAndClose(reader, getResponseClass());
}

7. RetryHttpRequestInitializerTest#testBasicOperation()

View license
@Test
public void testBasicOperation() throws IOException {
    when(mockLowLevelRequest.execute()).thenReturn(mockLowLevelResponse);
    when(mockLowLevelResponse.getStatusCode()).thenReturn(200);
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
    verify(mockCredential).initialize(any(HttpRequest.class));
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest).execute();
    verify(mockLowLevelResponse).getStatusCode();
}

8. RetryHttpRequestInitializerTest#testRetryableError()

View license
/**
   * Tests that a retriable error is retried.
   */
@Test
public void testRetryableError() throws IOException {
    when(mockLowLevelRequest.execute()).thenReturn(mockLowLevelResponse).thenReturn(mockLowLevelResponse).thenReturn(mockLowLevelResponse);
    when(mockLowLevelResponse.getStatusCode()).thenReturn(// Retryable
    503).thenReturn(// We also retry on 429 Too Many Requests.
    429).thenReturn(200);
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
    verify(mockCredential).initialize(any(HttpRequest.class));
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest, times(3)).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest, times(3)).execute();
    verify(mockLowLevelResponse, times(3)).getStatusCode();
}

9. RetryHttpRequestInitializerTest#testThrowIOException()

View license
/**
   * Tests that an IOException is retried.
   */
@Test
public void testThrowIOException() throws IOException {
    when(mockLowLevelRequest.execute()).thenThrow(new IOException("Fake Error")).thenReturn(mockLowLevelResponse);
    when(mockLowLevelResponse.getStatusCode()).thenReturn(200);
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
    verify(mockCredential).initialize(any(HttpRequest.class));
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest, times(2)).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest, times(2)).execute();
    verify(mockLowLevelResponse).getStatusCode();
}

10. RetryHttpRequestInitializerTest#testRetryableErrorRetryEnoughTimes()

View license
/**
   * Tests that a retryable error is retried enough times.
   */
@Test
public void testRetryableErrorRetryEnoughTimes() throws IOException {
    when(mockLowLevelRequest.execute()).thenReturn(mockLowLevelResponse);
    final int retries = 10;
    when(mockLowLevelResponse.getStatusCode()).thenAnswer(new Answer<Integer>() {

        int n = 0;

        @Override
        public Integer answer(InvocationOnMock invocation) {
            return (n++ < retries - 1) ? 503 : 200;
        }
    });
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
    verify(mockCredential).initialize(any(HttpRequest.class));
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest, times(retries)).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest, times(retries)).execute();
    verify(mockLowLevelResponse, times(retries)).getStatusCode();
}

11. RetryHttpInitializerWrapperTests#testSimpleRetry()

View license
public void testSimpleRetry() throws Exception {
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 3);
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper mockSleeper = new MockSleeper();
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueSeconds(5));
    Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
    HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    HttpResponse response = request.execute();
    assertThat(mockSleeper.getCount(), equalTo(3));
    assertThat(response.getStatusCode(), equalTo(200));
}

12. RetryHttpInitializerWrapperTests#testIOExceptionRetry()

View license
public void testIOExceptionRetry() throws Exception {
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 1, true);
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper mockSleeper = new MockSleeper();
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueMillis(500));
    Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
    HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    HttpResponse response = request.execute();
    assertThat(mockSleeper.getCount(), equalTo(1));
    assertThat(response.getStatusCode(), equalTo(200));
}

13. GoogleJsonResponseException#execute()

View license
/**
   * Executes an HTTP request using {@link HttpRequest#execute()}, but throws a
   * {@link GoogleJsonResponseException} on error instead of {@link HttpResponseException}.
   *
   * <p>
   * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is
   * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the
   * response stream is properly closed. Example usage:
   * </p>
   *
   * <pre>
     HttpResponse response = GoogleJsonResponseException.execute(jsonFactory, request);
     try {
       // process the HTTP response object
     } finally {
       response.disconnect();
     }
   * </pre>
   *
   * @param jsonFactory JSON factory
   * @param request HTTP request
   * @return HTTP response for an HTTP success code (or error code if
   *         {@link HttpRequest#getThrowExceptionOnExecuteError()})
   * @throws GoogleJsonResponseException for an HTTP error code (only if not
   *         {@link HttpRequest#getThrowExceptionOnExecuteError()})
   * @throws IOException some other kind of I/O exception
   * @since 1.7
   */
public static HttpResponse execute(JsonFactory jsonFactory, HttpRequest request) throws GoogleJsonResponseException, IOException {
    Preconditions.checkNotNull(jsonFactory);
    boolean originalThrowExceptionOnExecuteError = request.getThrowExceptionOnExecuteError();
    if (originalThrowExceptionOnExecuteError) {
        request.setThrowExceptionOnExecuteError(false);
    }
    HttpResponse response = request.execute();
    request.setThrowExceptionOnExecuteError(originalThrowExceptionOnExecuteError);
    if (!originalThrowExceptionOnExecuteError || response.isSuccessStatusCode()) {
        return response;
    }
    throw GoogleJsonResponseException.from(jsonFactory, response);
}

14. MediaHttpUploader#executeUploadInitiation()

View license
/**
   * This method sends a POST request with empty content to get the unique upload URL.
   *
   * @param initiationRequestUrl The request URL where the initiation request will be sent
   */
private HttpResponse executeUploadInitiation(GenericUrl initiationRequestUrl) throws IOException {
    updateStateAndNotifyListener(UploadState.INITIATION_STARTED);
    initiationRequestUrl.put("uploadType", "resumable");
    HttpContent content = metadata == null ? new EmptyContent() : metadata;
    HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content);
    initiationHeaders.set(CONTENT_TYPE_HEADER, mediaContent.getType());
    if (isMediaLengthKnown()) {
        initiationHeaders.set(CONTENT_LENGTH_HEADER, getMediaContentLength());
    }
    request.getHeaders().putAll(initiationHeaders);
    HttpResponse response = executeCurrentRequest(request);
    boolean notificationCompleted = false;
    try {
        updateStateAndNotifyListener(UploadState.INITIATION_COMPLETE);
        notificationCompleted = true;
    } finally {
        if (!notificationCompleted) {
            response.disconnect();
        }
    }
    return response;
}

15. GoogleJsonResponseExceptionFactoryTesting#newMock()

View license
/**
   * Convenience factory method that builds a {@link GoogleJsonResponseException}
   * from its arguments. The method builds a dummy {@link HttpRequest} and
   * {@link HttpResponse}, sets the response's status to a user-specified HTTP
   * error code, suppresses exceptions, and executes the request. This forces
   * the underlying framework to create, but not throw, a
   * {@link GoogleJsonResponseException}, which the method retrieves and returns
   * to the invoker.
   *
   * @param jsonFactory the JSON factory that will create all JSON required
   *        by the underlying framework
   * @param httpCode the desired HTTP error code. Note: do nut specify any codes
   *        that indicate successful completion, e.g. 2XX.
   * @param reasonPhrase the HTTP reason code that explains the error. For example,
   *        if {@code httpCode} is {@code 404}, the reason phrase should be
   *        {@code NOT FOUND}.
   * @return the generated {@link GoogleJsonResponseException}, as specified.
   * @throws IOException if request transport fails.
   */
public static GoogleJsonResponseException newMock(JsonFactory jsonFactory, int httpCode, String reasonPhrase) throws IOException {
    MockLowLevelHttpResponse otherServiceUnavaiableLowLevelResponse = new MockLowLevelHttpResponse().setStatusCode(httpCode).setReasonPhrase(reasonPhrase);
    MockHttpTransport otherTransport = new MockHttpTransport.Builder().setLowLevelHttpResponse(otherServiceUnavaiableLowLevelResponse).build();
    HttpRequest otherRequest = otherTransport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    otherRequest.setThrowExceptionOnExecuteError(false);
    HttpResponse otherServiceUnavailableResponse = otherRequest.execute();
    return GoogleJsonResponseException.from(jsonFactory, otherServiceUnavailableResponse);
}

16. GoogleJsonResponseExceptionTest#testFrom_withDetails()

View license
public void testFrom_withDetails() throws Exception {
    HttpTransport transport = new ErrorTransport();
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge = GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
    assertEquals(GoogleJsonErrorTest.ERROR, GoogleJsonErrorTest.FACTORY.toString(ge.getDetails()));
    assertTrue(ge.getMessage(), ge.getMessage().startsWith("403" + StringUtils.LINE_SEPARATOR + "{"));
}

17. GoogleJsonResponseExceptionTest#testFrom_detailsArbitraryXmlContent()

View license
public void testFrom_detailsArbitraryXmlContent() throws Exception {
    HttpTransport transport = new ErrorTransport("<foo>", "application/atom+xml; charset=utf-8");
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge = GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertTrue(ge.getMessage(), ge.getMessage().startsWith("403" + StringUtils.LINE_SEPARATOR + "<"));
}

18. MediaHttpUploaderTest#testUploadServerError_WithoutUnsuccessfulHandler()

View license
public void testUploadServerError_WithoutUnsuccessfulHandler() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.testServerError = true;
    InputStream is = new ByteArrayInputStream(new byte[contentLength]);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    mediaContent.setLength(contentLength);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
    HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
    assertEquals(500, response.getStatusCode());
    // There should be 3 calls made. 1 initiation request, 1 successful upload request and 1 upload
    // request with server error
    assertEquals(3, fakeTransport.lowLevelExecCalls);
}

19. MediaHttpUploaderTest#testUploadServerErrorWithBackOffDisabled_WithNoContentSizeProvided()

View license
public void testUploadServerErrorWithBackOffDisabled_WithNoContentSizeProvided() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.testServerError = true;
    fakeTransport.contentLengthNotSpecified = true;
    InputStream is = new ByteArrayInputStream(new byte[contentLength]);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
    HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
    assertEquals(500, response.getStatusCode());
    // There should be 3 calls made. 1 initiation request, 1 successful upload request and 1 upload
    // request with server error
    assertEquals(3, fakeTransport.lowLevelExecCalls);
}

20. MediaHttpUploaderTest#testUploadAuthenticationError()

View license
public void testUploadAuthenticationError() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.testAuthenticationError = true;
    InputStream is = new ByteArrayInputStream(new byte[contentLength]);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    mediaContent.setLength(contentLength);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
    HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
    assertEquals(404, response.getStatusCode());
    // There should be only 1 initiation request made with a 404.
    assertEquals(1, fakeTransport.lowLevelExecCalls);
}

21. MediaHttpUploaderTest#testUploadClientErrorInUploadCalls()

View license
public void testUploadClientErrorInUploadCalls() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.testClientError = true;
    InputStream is = new ByteArrayInputStream(new byte[contentLength]);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    mediaContent.setLength(contentLength);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
    HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
    assertEquals(411, response.getStatusCode());
    // There should be 2 calls made. 1 initiation request and 1 upload request that returned a 411.
    assertEquals(2, fakeTransport.lowLevelExecCalls);
}

22. MediaHttpUploaderTest#testUploadClientErrorInUploadCalls_WithNoContentSizeProvided()

View license
public void testUploadClientErrorInUploadCalls_WithNoContentSizeProvided() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.testClientError = true;
    fakeTransport.contentLengthNotSpecified = true;
    InputStream is = new ByteArrayInputStream(new byte[contentLength]);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
    HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
    assertEquals(411, response.getStatusCode());
    // There should be 2 calls made. 1 initiation request and 1 upload request that returned a 411.
    assertEquals(2, fakeTransport.lowLevelExecCalls);
}

23. MediaHttpUploaderTest#testDirectMediaUpload()

View license
public void testDirectMediaUpload() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.directUploadEnabled = true;
    InputStream is = new ByteArrayInputStream(new byte[contentLength]);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    mediaContent.setLength(contentLength);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
    uploader.setProgressListener(new DirectProgressListener());
    // Enable direct media upload.
    uploader.setDirectUploadEnabled(true);
    HttpResponse response = uploader.upload(new GenericUrl(TEST_DIRECT_REQUEST_URL));
    assertEquals(200, response.getStatusCode());
    // There should be only 1 call made for direct media upload.
    assertEquals(1, fakeTransport.lowLevelExecCalls);
}

24. MediaHttpUploaderTest#testDirectMediaUpload_WithSpecifiedHeader()

View license
public void testDirectMediaUpload_WithSpecifiedHeader() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.directUploadEnabled = true;
    fakeTransport.assertTestHeaders = true;
    InputStream is = new ByteArrayInputStream(new byte[contentLength]);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    mediaContent.setLength(contentLength);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
    uploader.getInitiationHeaders().set("test-header-name", "test-header-value");
    uploader.setProgressListener(new DirectProgressListener());
    // Enable direct media upload.
    uploader.setDirectUploadEnabled(true);
    HttpResponse response = uploader.upload(new GenericUrl(TEST_DIRECT_REQUEST_URL));
    assertEquals(200, response.getStatusCode());
    // There should be only 1 call made for direct media upload.
    assertEquals(1, fakeTransport.lowLevelExecCalls);
}

25. MediaHttpUploaderTest#testDirectMediaUpload_WithNoContentSizeProvided()

View license
public void testDirectMediaUpload_WithNoContentSizeProvided() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.directUploadEnabled = true;
    fakeTransport.contentLengthNotSpecified = true;
    InputStream is = new ByteArrayInputStream(new byte[contentLength]);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
    DirectProgressListener listener = new DirectProgressListener();
    listener.contentLengthNotSpecified = true;
    uploader.setProgressListener(listener);
    // Enable direct media upload.
    uploader.setDirectUploadEnabled(true);
    HttpResponse response = uploader.upload(new GenericUrl(TEST_DIRECT_REQUEST_URL));
    assertEquals(200, response.getStatusCode());
    // There should be only 1 call made for direct media upload.
    assertEquals(1, fakeTransport.lowLevelExecCalls);
}

26. MediaHttpUploaderTest#testDirectMediaUploadWithMetadata()

View license
public void testDirectMediaUploadWithMetadata() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.directUploadEnabled = true;
    fakeTransport.directUploadWithMetadata = true;
    InputStream is = new ByteArrayInputStream(new byte[contentLength]);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    mediaContent.setLength(contentLength);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
    uploader.setProgressListener(new DirectProgressListener());
    // Enable direct media upload.
    uploader.setDirectUploadEnabled(true);
    // Set Metadata
    uploader.setMetadata(new MockHttpContent());
    HttpResponse response = uploader.upload(new GenericUrl(TEST_MULTIPART_REQUEST_URL));
    assertEquals(200, response.getStatusCode());
    // There should be only 1 call made for direct media upload.
    assertEquals(1, fakeTransport.lowLevelExecCalls);
}

27. MediaHttpUploaderTest#testDirectMediaUploadWithMetadata_WithNoContentSizeProvided()

View license
public void testDirectMediaUploadWithMetadata_WithNoContentSizeProvided() throws Exception {
    int contentLength = MediaHttpUploader.DEFAULT_CHUNK_SIZE * 2;
    MediaTransport fakeTransport = new MediaTransport(contentLength);
    fakeTransport.directUploadEnabled = true;
    fakeTransport.contentLengthNotSpecified = true;
    fakeTransport.directUploadWithMetadata = true;
    InputStream is = new ByteArrayInputStream(new byte[contentLength]);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, null);
    DirectProgressListener listener = new DirectProgressListener();
    listener.contentLengthNotSpecified = true;
    uploader.setProgressListener(listener);
    // Enable direct media upload.
    uploader.setDirectUploadEnabled(true);
    // Set Metadata
    uploader.setMetadata(new MockHttpContent());
    HttpResponse response = uploader.upload(new GenericUrl(TEST_MULTIPART_REQUEST_URL));
    assertEquals(200, response.getStatusCode());
    // There should be only 1 call made for direct media upload.
    assertEquals(1, fakeTransport.lowLevelExecCalls);
}

28. RetryHttpRequestInitializerTest#testBasicOperation()

View license
@Test
public void testBasicOperation() throws IOException {
    when(mockLowLevelRequest.execute()).thenReturn(mockLowLevelResponse);
    when(mockLowLevelResponse.getStatusCode()).thenReturn(200);
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
    verify(mockCredential).initialize(any(HttpRequest.class));
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest).execute();
    verify(mockLowLevelResponse).getStatusCode();
}

29. RetryHttpRequestInitializerTest#testRetryableError()

View license
/**
   * Tests that a retriable error is retried.
   */
@Test
public void testRetryableError() throws IOException {
    when(mockLowLevelRequest.execute()).thenReturn(mockLowLevelResponse).thenReturn(mockLowLevelResponse).thenReturn(mockLowLevelResponse);
    when(mockLowLevelResponse.getStatusCode()).thenReturn(// Retryable
    503).thenReturn(// We also retry on 429 Too Many Requests.
    429).thenReturn(200);
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
    verify(mockCredential).initialize(any(HttpRequest.class));
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest, times(3)).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest, times(3)).execute();
    verify(mockLowLevelResponse, times(3)).getStatusCode();
}

30. RetryHttpRequestInitializerTest#testThrowIOException()

View license
/**
   * Tests that an IOException is retried.
   */
@Test
public void testThrowIOException() throws IOException {
    when(mockLowLevelRequest.execute()).thenThrow(new IOException("Fake Error")).thenReturn(mockLowLevelResponse);
    when(mockLowLevelResponse.getStatusCode()).thenReturn(200);
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
    verify(mockCredential).initialize(any(HttpRequest.class));
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest, times(2)).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest, times(2)).execute();
    verify(mockLowLevelResponse).getStatusCode();
}

31. RetryHttpRequestInitializerTest#testRetryableErrorRetryEnoughTimes()

View license
/**
   * Tests that a retryable error is retried enough times.
   */
@Test
public void testRetryableErrorRetryEnoughTimes() throws IOException {
    when(mockLowLevelRequest.execute()).thenReturn(mockLowLevelResponse);
    final int retries = 10;
    when(mockLowLevelResponse.getStatusCode()).thenAnswer(new Answer<Integer>() {

        int n = 0;

        @Override
        public Integer answer(InvocationOnMock invocation) {
            return (n++ < retries - 1) ? 503 : 200;
        }
    });
    Storage.Buckets.Get result = storage.buckets().get("test");
    HttpResponse response = result.executeUnparsed();
    assertNotNull(response);
    verify(mockCredential).initialize(any(HttpRequest.class));
    verify(mockHttpResponseInterceptor).interceptResponse(any(HttpResponse.class));
    verify(mockLowLevelRequest, atLeastOnce()).addHeader(anyString(), anyString());
    verify(mockLowLevelRequest, times(retries)).setTimeout(anyInt(), anyInt());
    verify(mockLowLevelRequest, times(retries)).execute();
    verify(mockLowLevelResponse, times(retries)).getStatusCode();
}

32. AdminPortalTest#should_ReturnMethodNotImplemented_WhenSuccessfulOptionsMade_ToAdminPortalRoot()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnMethodNotImplemented_WhenSuccessfulOptionsMade_ToAdminPortalRoot() throws Exception {
    final String requestUrl = String.format("%s/", ADMIN_URL);
    final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.OPTIONS, requestUrl);
    final HttpResponse httpResponse = httpPutRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String responseMessage = httpResponse.parseAsString().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_IMPLEMENTED_501);
    assertThat(statusMessage).isEqualTo("Not Implemented");
    assertThat(responseMessage).isEqualTo("Method OPTIONS is not implemented on URI /");
}

33. AdminPortalTest#should_ReturnMethodNotImplemented_WhenSuccessfulHeadMade_ToAdminPortalRoot()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnMethodNotImplemented_WhenSuccessfulHeadMade_ToAdminPortalRoot() throws Exception {
    final String requestUrl = String.format("%s/", ADMIN_URL);
    final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.HEAD, requestUrl);
    final HttpResponse httpResponse = httpPutRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String responseMessage = httpResponse.parseAsString().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_IMPLEMENTED_501);
    assertThat(statusMessage).isEqualTo("Not Implemented");
    assertThat(responseMessage).isEqualTo("");
}

34. AdminPortalTest#should_ReturnMethodNotImplemented_WhenSuccessfulTraceMade_ToAdminPortalRoot()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnMethodNotImplemented_WhenSuccessfulTraceMade_ToAdminPortalRoot() throws Exception {
    final String requestUrl = String.format("%s/", ADMIN_URL);
    final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.TRACE, requestUrl);
    final HttpResponse httpResponse = httpPutRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String responseMessage = httpResponse.parseAsString().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NOT_IMPLEMENTED_501);
    assertThat(statusMessage).isEqualTo("Not Implemented");
    assertThat(responseMessage).isEqualTo("Method TRACE is not implemented on URI /");
}

35. AdminPortalTest#shouldMakeSuccessfulGetRequestToStatusPage()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void shouldMakeSuccessfulGetRequestToStatusPage() throws Exception {
    final String requestUrl = String.format("%s%s", ADMIN_URL, "/status");
    final HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    final HttpResponse httpResponse = httpGetRequest.execute();
    final String responseContentAsString = httpResponse.parseAsString().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(responseContentAsString).contains("/pdf/hello-world");
    assertThat(responseContentAsString).contains("STATUS");
    assertThat(responseContentAsString).contains("/uri/with/single/sequenced/response");
}

36. AdminPortalTest#should_ReturnAllStubbedRequestsAsYAML_WhenSuccessfulGetMade_ToAdminPortalRoot()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnAllStubbedRequestsAsYAML_WhenSuccessfulGetMade_ToAdminPortalRoot() throws Exception {
    final String requestUrl = String.format("%s%s", ADMIN_URL, "/");
    final HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    final HttpResponse httpResponse = httpGetRequest.execute();
    final String responseContentAsString = httpResponse.parseAsString().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(responseContentAsString).contains("request");
    assertThat(responseContentAsString).contains("url: ^/resources/asn/");
    assertThat(responseContentAsString).contains("content-disposition: attachment; filename=hello-world.pdf");
    assertThat(responseContentAsString).contains("file: ../json/response.json");
    assertThat(responseContentAsString).contains("url: /uri/with/single/sequenced/response");
}

37. AdminPortalTest#should_ReturnSingleStubbedRequestAsYAML_WhenSuccessfulGetMade_ToAdminPortalRootWithValidIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnSingleStubbedRequestAsYAML_WhenSuccessfulGetMade_ToAdminPortalRootWithValidIndexURI() throws Exception {
    final String requestUrl = String.format("%s%s", ADMIN_URL, "/0");
    final HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    final HttpResponse httpResponse = httpGetRequest.execute();
    final String responseContentAsString = httpResponse.parseAsString().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(responseContentAsString).containsOnlyOnce("request");
    assertThat(responseContentAsString).containsOnlyOnce("url: ^/resources/asn/");
    assertThat(responseContentAsString).containsOnlyOnce("response");
    assertThat(responseContentAsString).containsOnlyOnce("content-type: application/json");
}

38. AdminPortalTest#should_ReturnExpectedError_WhenSuccessfulGetMade_ToAdminPortalRootWithInvalidIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnExpectedError_WhenSuccessfulGetMade_ToAdminPortalRootWithInvalidIndexURI() throws Exception {
    final int invalidIndex = 88888888;
    final String requestUrl = String.format("%s/%s", ADMIN_URL, invalidIndex);
    final HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    final HttpResponse httpResponse = httpGetRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String expectedMessage = String.format("Stub request index#%s does not exist, cannot display", invalidIndex);
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT_204);
    assertThat(statusMessage).isEqualTo(expectedMessage);
}

39. AdminPortalTest#should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRoot()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRoot() throws Exception {
    final String requestUrl = String.format("%s/", ADMIN_URL);
    final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl);
    final HttpResponse httpResponse = httpPutRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String responseMessage = httpResponse.parseAsString().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED_405);
    assertThat(statusMessage).isEqualTo("Method Not Allowed");
    assertThat(responseMessage).isEqualTo("Method PUT is not allowed on URI /");
}

40. AdminPortalTest#should_ReturnExpectedError_WhenSuccessfulEmptyPutMade_ToAdminPortalRootWithValidIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnExpectedError_WhenSuccessfulEmptyPutMade_ToAdminPortalRootWithValidIndexURI() throws Exception {
    final String requestUrl = String.format("%s/1", ADMIN_URL);
    final HttpRequest httpPuttRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl);
    final HttpResponse httpResponse = httpPuttRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT_204);
    assertThat(statusMessage).isEqualTo("PUT request on URI /1 was empty");
}

41. AdminPortalTest#should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRootWithInvalidIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnExpectedError_WhenSuccessfulPutMade_ToAdminPortalRootWithInvalidIndexURI() throws Exception {
    final int invalidIndex = 88888888;
    final String requestUrl = String.format("%s/%s", ADMIN_URL, invalidIndex);
    final HttpRequest httpPuttRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl);
    final HttpResponse httpResponse = httpPuttRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String expectedMessage = String.format("Stub request index#%s does not exist, cannot update", invalidIndex);
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT_204);
    assertThat(statusMessage).isEqualTo(expectedMessage);
}

42. AdminPortalTest#should_ReturnExpectedError_WhenSuccessfulDeleteMade_ToAdminPortalRoot()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnExpectedError_WhenSuccessfulDeleteMade_ToAdminPortalRoot() throws Exception {
    final String requestUrl = String.format("%s/", ADMIN_URL);
    final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.DELETE, requestUrl);
    final HttpResponse httpResponse = httpPutRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String responseMessage = httpResponse.parseAsString().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED_405);
    assertThat(statusMessage).isEqualTo("Method Not Allowed");
    assertThat(responseMessage).isEqualTo("Method DELETE is not allowed on URI /");
}

43. AdminPortalTest#should_ReturnExpectedError_WhenSuccessfulDeleteMade_ToAdminPortalRootWithInvalidIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnExpectedError_WhenSuccessfulDeleteMade_ToAdminPortalRootWithInvalidIndexURI() throws Exception {
    final int invalidIndex = 88888888;
    final String requestUrl = String.format("%s/%s", ADMIN_URL, invalidIndex);
    final HttpRequest httpPuttRequest = HttpUtils.constructHttpRequest(HttpMethods.DELETE, requestUrl);
    final HttpResponse httpResponse = httpPuttRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String expectedMessage = String.format("Stub request index#%s does not exist, cannot delete", invalidIndex);
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT_204);
    assertThat(statusMessage).isEqualTo(expectedMessage);
}

44. AdminPortalTest#should_ReturnExpectedError_WhenSuccessfulPostMade_ToAdminPortalRootWithAnIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnExpectedError_WhenSuccessfulPostMade_ToAdminPortalRootWithAnIndexURI() throws Exception {
    final int invalidIndex = 5;
    final String requestUrl = String.format("%s/%s", ADMIN_URL, invalidIndex);
    final HttpRequest httpPuttRequest = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl);
    final HttpResponse httpResponse = httpPuttRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String responseMessage = httpResponse.parseAsString().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED_405);
    assertThat(statusMessage).isEqualTo("Method Not Allowed");
    assertThat(responseMessage).isEqualTo("Method POST is not allowed on URI /5");
}

45. AdminPortalTest#should_ReturnExpectedError_WhenSuccessfulEmptyPostMade_ToAdminPortalRoot()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnExpectedError_WhenSuccessfulEmptyPostMade_ToAdminPortalRoot() throws Exception {
    final String requestUrl = String.format("%s/", ADMIN_URL);
    final HttpRequest httpPuttRequest = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl);
    final HttpResponse httpResponse = httpPuttRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT_204);
    assertThat(statusMessage).isEqualTo("POST request on URI / was empty");
}

46. AdminPortalTest#should_ReturnExpectedError_WhenSuccessfulInvalidPostMade_ToAdminPortalRoot()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_ReturnExpectedError_WhenSuccessfulInvalidPostMade_ToAdminPortalRoot() throws Exception {
    final String requestUrl = String.format("%s/", ADMIN_URL);
    final HttpRequest httpPuttRequest = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, "unparseable rubbish post content");
    final HttpResponse httpResponse = httpPuttRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String responseMessage = httpResponse.parseAsString().trim();
    final String expectedMessage = "Problem handling request in Admin handler: java.io.IOException: Loaded YAML root node must be an instance of ArrayList, otherwise something went wrong. Check provided YAML";
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR_500);
    assertThat(statusMessage).isEqualTo(expectedMessage);
    assertThat(responseMessage).contains(expectedMessage);
}

47. StubsPortalTest#should_FindPostContentsEqual_WhenJsonContentOrderIrrelevant()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_FindPostContentsEqual_WhenJsonContentOrderIrrelevant() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/complex/json/tree");
    final URL jsonContentUrl = StubsPortalTest.class.getResource("/json/graph.2.json");
    assertThat(jsonContentUrl).isNotNull();
    final String content = StringUtils.inputStreamToString(jsonContentUrl.openStream());
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(response.parseAsString().trim()).isEqualTo("OK");
}

48. StubsPortalTest#should_FindPostContentsEqual_WhenXmlContentOrderIrrelevant()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_FindPostContentsEqual_WhenXmlContentOrderIrrelevant() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/complex/xml/tree");
    final URL jsonContentUrl = StubsPortalTest.class.getResource("/xml/graph.2.xml");
    assertThat(jsonContentUrl).isNotNull();
    final String content = StringUtils.inputStreamToString(jsonContentUrl.openStream());
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_XML);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(response.parseAsString().trim()).isEqualTo("OK");
}

49. StubsPortalTest#should_ReturnAllProducts_WhenGetRequestMade()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_ReturnAllProducts_WhenGetRequestMade() throws Exception {
    final URL jsonContentUrl = StubsPortalTest.class.getResource("/json/response.json");
    assertThat(jsonContentUrl).isNotNull();
    final String expectedContent = StringUtils.inputStreamToString(jsonContentUrl.openStream());
    final String requestUrl = String.format("%s%s", STUBS_URL, "/invoice?status=active&type=full");
    final HttpResponse response = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute();
    final String contentTypeHeader = response.getContentType();
    final String responseContent = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(expectedContent).isEqualTo(responseContent);
    assertThat(contentTypeHeader).contains(Common.HEADER_APPLICATION_JSON);
}

50. StubsPortalTest#should_ReturnAllProducts_WhenGetRequestMadeOverSsl()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_ReturnAllProducts_WhenGetRequestMadeOverSsl() throws Exception {
    final URL jsonContentUrl = StubsPortalTest.class.getResource("/json/response.json");
    assertThat(jsonContentUrl).isNotNull();
    final String expectedContent = StringUtils.inputStreamToString(jsonContentUrl.openStream());
    final String requestUrl = String.format("%s%s", STUBS_SSL_URL, "/invoice?status=active&type=full");
    final HttpResponse response = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl).execute();
    final String contentTypeHeader = response.getContentType();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(expectedContent).isEqualTo(response.parseAsString().trim());
    assertThat(contentTypeHeader).contains(Common.HEADER_APPLICATION_JSON);
}

51. StubsPortalTest#should_UpdateProduct_WhenPutRequestMade()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_UpdateProduct_WhenPutRequestMade() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/invoice/123");
    final String content = "{\"name\": \"milk\", \"description\": \"full\", \"department\": \"savoury\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    final String contentTypeHeader = response.getContentType();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat("{\"id\": \"123\", \"status\": \"updated\"}").isEqualTo(response.parseAsString().trim());
    assertThat(contentTypeHeader).contains(Common.HEADER_APPLICATION_JSON);
}

52. StubsPortalTest#should_UpdateProduct_WhenPutRequestMadeOverSsl()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_UpdateProduct_WhenPutRequestMadeOverSsl() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_SSL_URL, "/invoice/123");
    final String content = "{\"name\": \"milk\", \"description\": \"full\", \"department\": \"savoury\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    final String contentTypeHeader = response.getContentType();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat("{\"id\": \"123\", \"status\": \"updated\"}").isEqualTo(response.parseAsString().trim());
    assertThat(contentTypeHeader).contains(Common.HEADER_APPLICATION_JSON);
}

53. StubsPortalTest#should_UpdateProduct_WhenPutRequestMadeWithWrongPost()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_UpdateProduct_WhenPutRequestMadeWithWrongPost() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/invoice/123");
    final String content = "{\"wrong\": \"post\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    final String responseContentAsString = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND_404);
    assertThat(responseContentAsString).contains("(404) Nothing found for PUT request at URI /invoice/123");
}

54. StubsPortalTest#should_UpdateProduct_WhenPutRequestMadeWithWrongPostOverSsl()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_UpdateProduct_WhenPutRequestMadeWithWrongPostOverSsl() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_SSL_URL, "/invoice/123");
    final String content = "{\"wrong\": \"post\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    final String responseContentAsString = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND_404);
    assertThat(responseContentAsString).contains("(404) Nothing found for PUT request at URI /invoice/123");
}

55. StubsPortalTest#should_CreateNewProduct_WhenPostRequestMade()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_CreateNewProduct_WhenPostRequestMade() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/invoice/new");
    final String content = "{\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    final String contentTypeHeader = response.getContentType();
    final String responseContentAsString = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201);
    assertThat("{\"id\": \"456\", \"status\": \"created\"}").isEqualTo(responseContentAsString);
    assertThat(contentTypeHeader).contains(Common.HEADER_APPLICATION_JSON);
}

56. StubsPortalTest#should_CreateNewProduct_WhenPostRequestMadeOverSsl()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_CreateNewProduct_WhenPostRequestMadeOverSsl() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_SSL_URL, "/invoice/new");
    final String content = "{\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    final String contentTypeHeader = response.getContentType();
    final String responseContentAsString = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201);
    assertThat("{\"id\": \"456\", \"status\": \"created\"}").isEqualTo(responseContentAsString);
    assertThat(contentTypeHeader).contains(Common.HEADER_APPLICATION_JSON);
}

57. StubsPortalTest#should_FailedToCreateNewProduct_WhenPostRequestMadeWhenWrongHeaderSet()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_FailedToCreateNewProduct_WhenPostRequestMadeWhenWrongHeaderSet() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/invoice/new");
    final String content = "{\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType("application/wrong");
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    final String responseContentAsString = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND_404);
    assertThat(responseContentAsString).contains("(404) Nothing found for POST request at URI /invoice/new");
}

58. StubsPortalTest#should_FailedToCreateNewProduct_WhenPostRequestMadeWhenWrongHeaderSetOverSsl()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_FailedToCreateNewProduct_WhenPostRequestMadeWhenWrongHeaderSetOverSsl() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_SSL_URL, "/invoice/new");
    final String content = "{\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType("application/wrong");
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    final String responseContentAsString = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND_404);
    assertThat(responseContentAsString).contains("(404) Nothing found for POST request at URI /invoice/new");
}

59. StubsPortalTest#should_MakeSuccessfulRequest_AndReturnSingleSequencedResponse()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_MakeSuccessfulRequest_AndReturnSingleSequencedResponse() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/uri/with/single/sequenced/response");
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse firstSequenceResponse = request.execute();
    String firstResponseContent = firstSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(firstSequenceResponse.getStatusCode());
    assertThat(firstResponseContent).isEqualTo("Still going strong!");
    firstSequenceResponse = request.execute();
    firstResponseContent = firstSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(firstSequenceResponse.getStatusCode());
    assertThat(firstResponseContent).isEqualTo("Still going strong!");
}

60. StubsPortalTest#should_MakeSuccessfulRequest_WhenPostRegexMatchingPostWithLineChars()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_MakeSuccessfulRequest_WhenPostRegexMatchingPostWithLineChars() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/uri/with/post/regex");
    final String content = "Here's the story of a lovely lady," + BR + "Who was bringing up three very lovely girls." + BR + "All of them had hair of gold, like their mother," + BR + "The youngest one in curls." + BR + "Here's the story, of a man named Brady," + BR + "Who was busy with three boys of his own." + BR + "They were four men, living all together," + BR + "Yet they were all alone.";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content);
    final HttpResponse response = request.execute();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(response.parseAsString().trim()).isEqualTo("OK");
}

61. StubsPortalTest#should_ReturnExpectedResourceIdHeader_WhenSuccessfulRequestMade()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@SuppressWarnings("unchecked")
@Test
public void should_ReturnExpectedResourceIdHeader_WhenSuccessfulRequestMade() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/this/stub/should/always/be/second/in/this/file");
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    final HttpResponse response = request.execute();
    final HttpHeaders headers = response.getHeaders();
    assertThat(headers.getContentType().contains(Common.HEADER_APPLICATION_JSON)).isTrue();
    assertThat(headers.containsKey(StubResponse.STUBBY_RESOURCE_ID_HEADER)).isTrue();
    final List<String> headerValues = (List<String>) headers.get(StubResponse.STUBBY_RESOURCE_ID_HEADER);
    assertThat(headerValues.get(0)).isEqualTo("1");
}

62. StubsPortalTest#should_ReturnReplacedTokenizedResponse_WhenCapturingGroupsEqualToNumberOfTokens()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_ReturnReplacedTokenizedResponse_WhenCapturingGroupsEqualToNumberOfTokens() throws Exception {
    String requestUrl = String.format("%s%s", STUBS_URL, "/resources/invoices/12345/category/milk");
    HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse response = request.execute();
    String responseContent = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(responseContent).isEqualTo("Returned invoice number# 12345 in category 'milk'");
    requestUrl = String.format("%s%s", STUBS_URL, "/resources/invoices/88888/category/army");
    request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    response = request.execute();
    responseContent = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(responseContent).isEqualTo("Returned invoice number# 88888 in category 'army'");
}

63. StubsPortalTest#should_ReturnReplacedTokenizedResponse_WhenUsingExternalFile()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_ReturnReplacedTokenizedResponse_WhenUsingExternalFile() throws Exception {
    String requestUrl = String.format("%s%s", STUBS_URL, "/account/12345/category/milk?date=Saturday");
    HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse response = request.execute();
    String responseContent = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(responseContent).isEqualTo("Returned invoice number# 12345 in category 'milk' on the date 'Saturday'");
    requestUrl = String.format("%s%s", STUBS_URL, "/account/88888/category/army?date=NOW");
    request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    response = request.execute();
    responseContent = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(responseContent).isEqualTo("Returned invoice number# 88888 in category 'army' on the date 'NOW'");
}

64. StubsPortalTest#should_ReturnReplacedTokenizedResponse_WhenFullMatchCapturingGroupsAreUsed()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_ReturnReplacedTokenizedResponse_WhenFullMatchCapturingGroupsAreUsed() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/no/explicit/groups/22222?param=ABC");
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("custom-header", "XYZ");
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    String responseContent = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(responseContent).isEqualTo("Returned content with URL /no/explicit/groups/22222, query param ABC and custom-header XYZ");
}

65. StubsPortalTest#should_ReturnExpectedRecordedResponse_FromAnotherValidUrl()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_ReturnExpectedRecordedResponse_FromAnotherValidUrl() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/feed/1?language=chinese&greeting=nihao");
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    final HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(requestHeaders);
    final HttpResponse response = request.execute();
    final HttpHeaders headers = response.getHeaders();
    assertThat(headers.getContentType().contains("application/xml")).isTrue();
    String responseContent = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(responseContent).contains("<payment><invoiceTypeLookupCode>STANDARD</invoiceTypeLookupCode></payment>");
}

66. StubsPortalTest#should_NotReturnExpectedRecordedResponse_FromValidUrl_WhenQueryValueNotCorrect()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_NotReturnExpectedRecordedResponse_FromValidUrl_WhenQueryValueNotCorrect() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/feed/2?language=russian&greeting=nihao");
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    final HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(requestHeaders);
    final HttpResponse response = request.execute();
    final HttpHeaders headers = response.getHeaders();
    assertThat(headers.getContentType().contains("application/xml")).isTrue();
    String responseContent = response.parseAsString().trim();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(responseContent).contains("(404) Nothing found for GET request at URI /recordable/feed/2?greeting=nihao&language=russian");
}

67. StubsPortalTest#should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/uri/with/sequenced/responses");
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse firstSequenceResponse = request.execute();
    String firstResponseContent = firstSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(firstSequenceResponse.getStatusCode());
    assertThat(firstResponseContent).isEqualTo("OK");
    final HttpResponse secondSequenceResponse = request.execute();
    final String secondResponseContent = secondSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(secondSequenceResponse.getStatusCode());
    assertThat(secondResponseContent).isEqualTo("Still going strong!");
    final HttpResponse thridSequenceResponse = request.execute();
    final String thirdResponseContent = thridSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.INTERNAL_SERVER_ERROR_500).isEqualTo(thridSequenceResponse.getStatusCode());
    assertThat(thirdResponseContent).isEqualTo("OMFG!!!");
    firstSequenceResponse = request.execute();
    firstResponseContent = firstSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(firstSequenceResponse.getStatusCode());
    assertThat(firstResponseContent).isEqualTo("OK");
}

68. StubsPortalTest#should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses_FromFile()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses_FromFile() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/uri/with/sequenced/responses/infile");
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse firstSequenceResponse = request.execute();
    String firstResponseContent = firstSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(firstSequenceResponse.getStatusCode());
    assertThat(firstResponseContent).isEqualTo("OK");
    final HttpResponse secondSequenceResponse = request.execute();
    final String secondResponseContent = secondSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(secondSequenceResponse.getStatusCode());
    assertThat(secondResponseContent).isEqualTo("Still going strong!");
    final HttpResponse thirdSequenceResponse = request.execute();
    final String thirdResponseContent = thirdSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.INTERNAL_SERVER_ERROR_500).isEqualTo(thirdSequenceResponse.getStatusCode());
    assertThat(thirdResponseContent).isEqualTo("OMFG!!!");
    firstSequenceResponse = request.execute();
    firstResponseContent = firstSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(firstSequenceResponse.getStatusCode());
    assertThat(firstResponseContent).isEqualTo("OK");
}

69. StubsPortalTest#should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses_FromFile_WithBadUrls()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_MakeSuccessfulRequest_AndReturnMultipleSequencedResponses_FromFile_WithBadUrls() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/uri/with/sequenced/responses/infile/withbadurls");
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse firstSequenceResponse = request.execute();
    String firstResponseContent = firstSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(firstSequenceResponse.getStatusCode());
    assertThat(firstResponseContent).isEmpty();
    final HttpResponse secondSequenceResponse = request.execute();
    final String secondResponseContent = secondSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(secondSequenceResponse.getStatusCode());
    assertThat(secondResponseContent).isEqualTo("Still going strong!");
    final HttpResponse thirdSequenceResponse = request.execute();
    final String thirdResponseContent = thirdSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.INTERNAL_SERVER_ERROR_500).isEqualTo(thirdSequenceResponse.getStatusCode());
    assertThat(thirdResponseContent).isEmpty();
    firstSequenceResponse = request.execute();
    firstResponseContent = firstSequenceResponse.parseAsString().trim();
    assertThat(HttpStatus.CREATED_201).isEqualTo(firstSequenceResponse.getStatusCode());
    assertThat(firstResponseContent).isEmpty();
}

70. LenientAuthorizationCodeTokenRequest#executeLeniently()

View license
/**
     * Executes request for an access token, and returns the HTTP response.
     * <p>
     * To execute and parse the response to {@link TokenResponse}, instead use
     * {@link #execute()}.
     * </p>
     * <p>
     * Callers should call {@link HttpResponse#disconnect} when the returned
     * HTTP response object is no longer needed. However,
     * {@link HttpResponse#disconnect} does not have to be called if the
     * response stream is properly closed. Example usage:
     * </p>
     * 
     * <pre>
     * HttpResponse response = tokenRequest.executeUnparsed();
     * try {
     *     // process the HTTP response object
     * } finally {
     *     response.disconnect();
     * }
     * </pre>
     * 
     * @return successful access token response, which can then be parsed
     *         directly using {@link HttpResponse#parseAs(Class)} or some other
     *         parsing method
     * @throws TokenResponseException for an error response
     */
private TokenResponse executeLeniently() throws IOException {
    // must set clientAuthentication as last execute interceptor in case it
    // needs to sign request
    HttpRequestFactory requestFactory = getTransport().createRequestFactory(new HttpRequestInitializer() {

        public void initialize(HttpRequest request) throws IOException {
            if (getRequestInitializer() != null) {
                getRequestInitializer().initialize(request);
            }
            final HttpExecuteInterceptor interceptor = request.getInterceptor();
            request.setInterceptor(new HttpExecuteInterceptor() {

                public void intercept(HttpRequest request) throws IOException {
                    if (interceptor != null) {
                        interceptor.intercept(request);
                    }
                    if (getClientAuthentication() != null) {
                        getClientAuthentication().intercept(request);
                    }
                }
            });
        }
    });
    // make request
    HttpRequest request = requestFactory.buildPostRequest(getTokenServerUrl(), new UrlEncodedContent(this));
    request.setParser(new JsonObjectParser(getJsonFactory()));
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    if (response.isSuccessStatusCode()) {
        if (!HttpResponseUtils.hasMessageBody(response)) {
            return null;
        }
        // check and see if status code is 200 but has error response
        String responseContent = HttpResponseUtils.parseAsStringWithoutClosing(response);
        TokenResponse tokenResponse = response.getRequest().getParser().parseAndClose(new StringReader(responseContent), TokenResponse.class);
        if (tokenResponse.containsKey("error")) {
            throw LenientTokenResponseException.from(getJsonFactory(), response, responseContent);
        }
        return response.getRequest().getParser().parseAndClose(new StringReader(responseContent), TokenResponse.class);
    }
    throw TokenResponseException.from(getJsonFactory(), response);
}

71. 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);
}

72. 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();
            }
        }
    }
}

73. AbstractGoogleClientRequest#executeUsingHead()

View license
/**
   * Sends the metadata request using HEAD to the server and returns the raw metadata
   * {@link HttpResponse} for the response headers.
   *
   * <p>
   * Only supported when the original request method is GET. The response content is assumed to be
   * empty and ignored. Calls {@link HttpResponse#ignore()} so there is no need to disconnect the
   * response. Example usage:
   * </p>
   *
   * <pre>
     HttpResponse response = request.executeUsingHead();
     // look at response.getHeaders()
   * </pre>
   *
   * <p>
   * Subclasses may override by calling the super implementation.
   * </p>
   *
   * @return the {@link HttpResponse}
   */
protected HttpResponse executeUsingHead() throws IOException {
    Preconditions.checkArgument(uploader == null);
    HttpResponse response = executeUnparsed(true);
    response.ignore();
    return response;
}

74. AbstractOAuthGetToken#execute()

View license
/**
   * Executes the HTTP request for a temporary or long-lived token.
   *
   * @return OAuth credentials response object
   */
public final OAuthCredentialsResponse execute() throws IOException {
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request = requestFactory.buildRequest(usePost ? HttpMethods.POST : HttpMethods.GET, this, null);
    createParameters().intercept(request);
    HttpResponse response = request.execute();
    response.setContentLoggingLimit(0);
    OAuthCredentialsResponse oauthResponse = new OAuthCredentialsResponse();
    UrlEncodedParser.parse(response.parseAsString(), oauthResponse);
    return oauthResponse;
}

75. TokenRequest#executeUnparsed()

View license
/**
   * Executes request for an access token, and returns the HTTP response.
   *
   * <p>
   * To execute and parse the response to {@link TokenResponse}, instead use {@link #execute()}.
   * </p>
   *
   * <p>
   * Callers should call {@link HttpResponse#disconnect} when the returned HTTP response object is
   * no longer needed. However, {@link HttpResponse#disconnect} does not have to be called if the
   * response stream is properly closed. Example usage:
   * </p>
   *
   * <pre>
     HttpResponse response = tokenRequest.executeUnparsed();
     try {
       // process the HTTP response object
     } finally {
       response.disconnect();
     }
   * </pre>
   *
   * @return successful access token response, which can then be parsed directly using
   *         {@link HttpResponse#parseAs(Class)} or some other parsing method
   * @throws TokenResponseException for an error response
   */
public final HttpResponse executeUnparsed() throws IOException {
    // must set clientAuthentication as last execute interceptor in case it needs to sign request
    HttpRequestFactory requestFactory = transport.createRequestFactory(new HttpRequestInitializer() {

        public void initialize(HttpRequest request) throws IOException {
            if (requestInitializer != null) {
                requestInitializer.initialize(request);
            }
            final HttpExecuteInterceptor interceptor = request.getInterceptor();
            request.setInterceptor(new HttpExecuteInterceptor() {

                public void intercept(HttpRequest request) throws IOException {
                    if (interceptor != null) {
                        interceptor.intercept(request);
                    }
                    if (clientAuthentication != null) {
                        clientAuthentication.intercept(request);
                    }
                }
            });
        }
    });
    // make request
    HttpRequest request = requestFactory.buildPostRequest(tokenServerUrl, new UrlEncodedContent(this));
    request.setParser(new JsonObjectParser(jsonFactory));
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    if (response.isSuccessStatusCode()) {
        return response;
    }
    throw TokenResponseException.from(jsonFactory, response);
}

76. AdminPortalTest#should_UpdateStubbedRequest_WhenSuccessfulPutMade_ToAdminPortalRootWithValidIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_UpdateStubbedRequest_WhenSuccessfulPutMade_ToAdminPortalRootWithValidIndexURI() throws Exception {
    final String requestUrl = String.format("%s%s", ADMIN_URL, "/0");
    HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse httpGetResponse = httpGetRequest.execute();
    String getResponseContent = httpGetResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(getResponseContent).containsOnlyOnce("request");
    assertThat(getResponseContent).containsOnlyOnce("url: ^/resources/asn/");
    assertThat(getResponseContent).containsOnlyOnce("response");
    assertThat(getResponseContent).containsOnlyOnce("content-type: application/json");
    final String yamlToUpdate = new YamlBuilder().newStubbedRequest().withUrl("^/resources/something/new").withMethodGet().withQuery("someKey", "someValue").newStubbedResponse().withHeaderContentType("application/xml").withLiteralBody("OK").withStatus("201").build();
    final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, yamlToUpdate);
    final HttpResponse httpPutResponse = httpPutRequest.execute();
    final String putResponseContent = httpPutResponse.parseAsString().trim();
    final String putResponseLocationHeader = httpPutResponse.getHeaders().getLocation();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(putResponseLocationHeader).isEqualTo("^/resources/something/new?someKey=someValue");
    assertThat(putResponseContent).isEqualTo("Stub request index#0 updated successfully");
    httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    httpGetResponse = httpGetRequest.execute();
    getResponseContent = httpGetResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(getResponseContent).containsOnlyOnce("request");
    assertThat(getResponseContent).containsOnlyOnce("query");
    assertThat(getResponseContent).containsOnlyOnce("url: ^/resources/something/new");
    assertThat(getResponseContent).containsOnlyOnce("response");
    assertThat(getResponseContent).containsOnlyOnce("content-type: application/xml");
    assertThat(getResponseContent).doesNotContain("url: ^/resources/asn/");
    assertThat(getResponseContent).doesNotContain("content-type: application/json");
}

77. AdminPortalTest#should_UpdateStubbedRequest_WithJsonRequest_ToAdminPortalRootWithValidIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_UpdateStubbedRequest_WithJsonRequest_ToAdminPortalRootWithValidIndexURI() throws Exception {
    final String requestUrl = String.format("%s%s", ADMIN_URL, "/0");
    HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse httpGetResponse = httpGetRequest.execute();
    String getResponseContent = httpGetResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(getResponseContent).containsOnlyOnce("request");
    assertThat(getResponseContent).containsOnlyOnce("url: ^/resources/asn/");
    assertThat(getResponseContent).containsOnlyOnce("response");
    assertThat(getResponseContent).containsOnlyOnce("content-type: application/json");
    final URL url = AdminPortalTest.class.getResource("/json/update.request.without.escaped.slashes.json");
    final InputStream jsonInputStream = url.openStream();
    final String jsonToUpdate = StringUtils.inputStreamToString(jsonInputStream);
    final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, jsonToUpdate);
    final HttpResponse httpPutResponse = httpPutRequest.execute();
    final String putResponseContent = httpPutResponse.parseAsString().trim();
    final String putResponseLocationHeader = httpPutResponse.getHeaders().getLocation();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(putResponseLocationHeader).isEqualTo("^/resources/something/new?someKey=someValue");
    assertThat(putResponseContent).isEqualTo("Stub request index#0 updated successfully");
    httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    httpGetResponse = httpGetRequest.execute();
    getResponseContent = httpGetResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(getResponseContent).containsOnlyOnce("request");
    assertThat(getResponseContent).containsOnlyOnce("query");
    assertThat(getResponseContent).containsOnlyOnce("url: ^/resources/something/new");
    assertThat(getResponseContent).containsOnlyOnce("response");
    assertThat(getResponseContent).containsOnlyOnce("content-type: application/xml");
    assertThat(getResponseContent).doesNotContain("url: ^/resources/asn/");
    assertThat(getResponseContent).doesNotContain("content-type: application/json");
}

78. AdminPortalTest#should_UpdateStubbedRequest_WithEnquotedForwardSlashesEscapedJsonRequest_ToAdminPortalRootWithValidIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_UpdateStubbedRequest_WithEnquotedForwardSlashesEscapedJsonRequest_ToAdminPortalRootWithValidIndexURI() throws Exception {
    final String requestUrl = String.format("%s%s", ADMIN_URL, "/0");
    HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse httpGetResponse = httpGetRequest.execute();
    String getResponseContent = httpGetResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(getResponseContent).containsOnlyOnce("request");
    assertThat(getResponseContent).containsOnlyOnce("url: ^/resources/asn/");
    assertThat(getResponseContent).containsOnlyOnce("response");
    assertThat(getResponseContent).containsOnlyOnce("content-type: application/json");
    final URL url = AdminPortalTest.class.getResource("/json/update.request.with.enquoted.escaped.forward.slashes.json");
    final InputStream jsonInputStream = url.openStream();
    final String escapedJsonToUpdate = StringUtils.inputStreamToString(jsonInputStream);
    final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, escapedJsonToUpdate);
    final HttpResponse httpPutResponse = httpPutRequest.execute();
    final String putResponseContent = httpPutResponse.parseAsString().trim();
    final String putResponseLocationHeader = httpPutResponse.getHeaders().getLocation();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(putResponseLocationHeader).isEqualTo("^/resources/something/new?someKey=someValue");
    assertThat(putResponseContent).isEqualTo("Stub request index#0 updated successfully");
    httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    httpGetResponse = httpGetRequest.execute();
    getResponseContent = httpGetResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(getResponseContent).containsOnlyOnce("request");
    assertThat(getResponseContent).containsOnlyOnce("query");
    assertThat(getResponseContent).containsOnlyOnce("url: ^/resources/something/new");
    assertThat(getResponseContent).containsOnlyOnce("response");
    assertThat(getResponseContent).containsOnlyOnce("content-type: application/xml");
    assertThat(getResponseContent).doesNotContain("url: ^/resources/asn/");
    assertThat(getResponseContent).doesNotContain("content-type: application/json");
}

79. AdminPortalTest#should_UpdateStubbedRequest_WithForwardSlashesEscapedJsonRequest_ToAdminPortalRootWithValidIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_UpdateStubbedRequest_WithForwardSlashesEscapedJsonRequest_ToAdminPortalRootWithValidIndexURI() throws Exception {
    final String requestUrl = String.format("%s%s", ADMIN_URL, "/0");
    HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse httpGetResponse = httpGetRequest.execute();
    String getResponseContent = httpGetResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(getResponseContent).containsOnlyOnce("request");
    assertThat(getResponseContent).containsOnlyOnce("url: ^/resources/asn/");
    assertThat(getResponseContent).containsOnlyOnce("response");
    assertThat(getResponseContent).containsOnlyOnce("content-type: application/json");
    final URL url = AdminPortalTest.class.getResource("/json/update.request.with.escaped.forward.slashes.json");
    final InputStream jsonInputStream = url.openStream();
    final String escapedJsonToUpdate = StringUtils.inputStreamToString(jsonInputStream);
    final HttpRequest httpPutRequest = HttpUtils.constructHttpRequest(HttpMethods.PUT, requestUrl, escapedJsonToUpdate);
    final HttpResponse httpPutResponse = httpPutRequest.execute();
    final String putResponseContent = httpPutResponse.parseAsString().trim();
    final String putResponseLocationHeader = httpPutResponse.getHeaders().getLocation();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(putResponseLocationHeader).isEqualTo("^/resources/something/new?someKey=someValue");
    assertThat(putResponseContent).isEqualTo("Stub request index#0 updated successfully");
    httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    httpGetResponse = httpGetRequest.execute();
    getResponseContent = httpGetResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(getResponseContent).containsOnlyOnce("request");
    assertThat(getResponseContent).containsOnlyOnce("query");
    assertThat(getResponseContent).containsOnlyOnce("url: ^/resources/something/new");
    assertThat(getResponseContent).containsOnlyOnce("response");
    assertThat(getResponseContent).containsOnlyOnce("content-type: application/xml");
    assertThat(getResponseContent).doesNotContain("url: ^/resources/asn/");
    assertThat(getResponseContent).doesNotContain("content-type: application/json");
}

80. AdminPortalTest#should_DeleteStubbedRequest_WhenSuccessfulDeleteMade_ToAdminPortalRootWithValidIndexURI()

Project: stubby4j
Source File: AdminPortalTest.java
View license
@Test
public void should_DeleteStubbedRequest_WhenSuccessfulDeleteMade_ToAdminPortalRootWithValidIndexURI() throws Exception {
    final String requestUrl = String.format("%s%s", ADMIN_URL, "/2");
    HttpRequest httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    HttpResponse httpGetResponse = httpGetRequest.execute();
    String getResponseContent = httpGetResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(getResponseContent).containsOnlyOnce("request");
    assertThat(getResponseContent).containsOnlyOnce("url: ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{3,8}¶mTwo=[a-zA-Z]{3,8}");
    assertThat(getResponseContent).containsOnlyOnce("response");
    assertThat(getResponseContent).containsOnlyOnce("content-type: application/json");
    final HttpRequest httpDeleteRequest = HttpUtils.constructHttpRequest(HttpMethods.DELETE, requestUrl);
    final HttpResponse httpDeleteResponse = httpDeleteRequest.execute();
    final String deleteResponseContent = httpDeleteResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpDeleteResponse.getStatusCode());
    assertThat(deleteResponseContent).isEqualTo("Stub request index#2 deleted successfully");
    httpGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, requestUrl);
    httpGetResponse = httpGetRequest.execute();
    getResponseContent = httpGetResponse.parseAsString().trim();
    assertThat(HttpStatus.OK_200).isEqualTo(httpGetResponse.getStatusCode());
    assertThat(getResponseContent).doesNotContain("url: ^/[a-z]{3}-[a-z]{3}/[0-9]{2}/[A-Z]{2}/[a-z0-9]+\\?paramOne=[a-zA-Z]{3,8}¶mTwo=[a-zA-Z]{3,8}");
}

81. StubsAdminPortalsTest#should_UpdateStubsDataAndGetNewResource_WhenSuccessfulValidPostMade_ToAdminPortalRoot()

Project: stubby4j
Source File: StubsAdminPortalsTest.java
View license
@Test
public void should_UpdateStubsDataAndGetNewResource_WhenSuccessfulValidPostMade_ToAdminPortalRoot() throws Exception {
    final String yamlToUpdate = new YamlBuilder().newStubbedRequest().withUrl("^/new/resource/.*$").withMethodGet().withQuery("someKey", "someValue").newStubbedResponse().withHeaderContentType("application/xml").withLiteralBody("OK").withStatus("200").build();
    final String adminRequestUrl = String.format("%s/", ADMIN_URL);
    final HttpRequest httpPuttRequest = HttpUtils.constructHttpRequest(HttpMethods.POST, adminRequestUrl, yamlToUpdate);
    final HttpResponse httpResponse = httpPuttRequest.execute();
    final String statusMessage = httpResponse.getStatusMessage().trim();
    final String responseMessage = httpResponse.parseAsString().trim();
    assertThat(httpResponse.getStatusCode()).isEqualTo(HttpStatus.CREATED_201);
    assertThat(statusMessage).isEqualTo("Created");
    assertThat(responseMessage).contains("Configuration created successfully");
    final String stubsRequestUrl = String.format("%s%s", STUBS_URL, "/new/resource/account?someKey=someValue");
    final HttpRequest stubsGetRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, stubsRequestUrl);
    final HttpResponse stubsGetResponse = stubsGetRequest.execute();
    final String stubsGetResponseContentTypeHeader = stubsGetResponse.getContentType();
    final String stubsGetResponseContent = stubsGetResponse.parseAsString().trim();
    assertThat(stubsGetResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(stubsGetResponseContent).isEqualTo("OK");
    assertThat(stubsGetResponseContentTypeHeader).contains("application/xml");
}

82. StubsAdminPortalsTest#should_ReturnAjaxResponseContentYaml_WhenSuccessfulRequestMade()

Project: stubby4j
Source File: StubsAdminPortalsTest.java
View license
@Test
public void should_ReturnAjaxResponseContentYaml_WhenSuccessfulRequestMade() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/invoice/new");
    final String postContent = "{\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, postContent);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    final HttpResponse response = request.execute();
    assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED_201);
    final String resourceID = response.getHeaders().getFirstHeaderStringValue(StubResponse.STUBBY_RESOURCE_ID_HEADER);
    final String ajaxRequestUrl = String.format("%s%s%s%s", ADMIN_URL, "/ajax/resource/", resourceID, "/httplifecycle/httpLifeCycleAsYaml");
    final HttpRequest ajaxRequest = HttpUtils.constructHttpRequest(HttpMethods.GET, ajaxRequestUrl);
    final HttpResponse ajaxResponse = ajaxRequest.execute();
    assertThat(ajaxResponse.getStatusCode()).isEqualTo(HttpStatus.OK_200);
    assertThat(ajaxResponse.parseAsString().trim()).contains("- request:" + BR + "    method: POST" + BR + "    url: /invoice/new" + BR + "    headers:" + BR + "      content-type: " + Common.HEADER_APPLICATION_JSON + BR + "    post: |" + BR + "      {\"name\": \"chocolate\", \"description\": \"full\", \"department\": \"savoury\"}" + BR + "  response:" + BR + "    headers:" + BR + "      content-type: " + Common.HEADER_APPLICATION_JSON + BR + "      pragma: no-cache" + BR + "    status: 201" + BR + "    body: |" + BR + "      {\"id\": \"456\", \"status\": \"created\"}");
}

83. DriveTask#downloadFile()

View license
/**
   * Downloads the file contents.
   * @param file File to download.
   * @return The file content.l
   * @throws IOException
   */
public String downloadFile(File file) throws IOException {
    HttpResponse res = mDriveService.getRequestFactory().buildGetRequest(new GenericUrl(file.getDownloadUrl())).execute();
    return Utils.fromInputStreamtoString(res.getContent());
}

84. GcsUtilTest#googleJsonResponseException()

Project: DataflowJavaSDK
Source File: GcsUtilTest.java
View license
/**
   * Builds a fake GoogleJsonResponseException for testing API error handling.
   */
private static GoogleJsonResponseException googleJsonResponseException(final int status, final String reason, final String message) throws IOException {
    final JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport transport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.setReason(reason);
            errorInfo.setMessage(message);
            errorInfo.setFactory(jsonFactory);
            GenericJson error = new GenericJson();
            error.set("code", status);
            error.set("errors", Arrays.asList(errorInfo));
            error.setFactory(jsonFactory);
            GenericJson errorResponse = new GenericJson();
            errorResponse.set("error", error);
            errorResponse.setFactory(jsonFactory);
            return new MockLowLevelHttpRequest().setResponse(new MockLowLevelHttpResponse().setContent(errorResponse.toPrettyString()).setContentType(Json.MEDIA_TYPE).setStatusCode(status));
        }
    };
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    return GoogleJsonResponseException.from(jsonFactory, response);
}

85. PackageUtilTest#googleJsonResponseException()

View license
/**
   * Builds a fake GoogleJsonResponseException for testing API error handling.
   */
private static GoogleJsonResponseException googleJsonResponseException(final int status, final String reason, final String message) throws IOException {
    final JsonFactory jsonFactory = new JacksonFactory();
    HttpTransport transport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            ErrorInfo errorInfo = new ErrorInfo();
            errorInfo.setReason(reason);
            errorInfo.setMessage(message);
            errorInfo.setFactory(jsonFactory);
            GenericJson error = new GenericJson();
            error.set("code", status);
            error.set("errors", Arrays.asList(errorInfo));
            error.setFactory(jsonFactory);
            GenericJson errorResponse = new GenericJson();
            errorResponse.set("error", error);
            errorResponse.setFactory(jsonFactory);
            return new MockLowLevelHttpRequest().setResponse(new MockLowLevelHttpResponse().setContent(errorResponse.toPrettyString()).setContentType(Json.MEDIA_TYPE).setStatusCode(status));
        }
    };
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    return GoogleJsonResponseException.from(jsonFactory, response);
}

86. BatchUnparsedResponse#parseNextResponse()

View license
/**
   * Parses the next response in the queue if a data class and a {@link BatchCallback} is specified.
   *
   * <p>
   * This method closes the input stream if there are no more individual responses left.
   * </p>
   */
void parseNextResponse() throws IOException {
    contentId++;
    // Extract the outer headers.
    String line;
    while ((line = readLine()) != null && !line.equals("")) {
    // Do nothing.
    }
    // Extract the status code.
    String statusLine = readLine();
    String[] statusParts = statusLine.split(" ");
    int statusCode = Integer.parseInt(statusParts[1]);
    // Extract and store the inner headers.
    // TODO(rmistry): Handle inner headers that span multiple lines. More details here:
    // http://tools.ietf.org/html/rfc2616#section-2.2
    List<String> headerNames = new ArrayList<String>();
    List<String> headerValues = new ArrayList<String>();
    long contentLength = -1L;
    while ((line = readLine()) != null && !line.equals("")) {
        String[] headerParts = line.split(": ", 2);
        String headerName = headerParts[0];
        String headerValue = headerParts[1];
        headerNames.add(headerName);
        headerValues.add(headerValue);
        if ("Content-Length".equalsIgnoreCase(headerName.trim())) {
            contentLength = Long.parseLong(headerValue);
        }
    }
    InputStream body;
    if (contentLength == -1) {
        // This isn't very efficient, but most respectable servers should set the Content-Length
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        while ((line = readRawLine()) != null && !line.startsWith(boundary)) {
            // Convert characters back to bytes:
            buffer.write(line.getBytes("ISO-8859-1"));
        }
        // Remove CRLF that separates body from boundary token
        body = trimCrlf(buffer.toByteArray());
        // Remove CRLF from the boundary token (to match readLine)
        line = trimCrlf(line);
    } else {
        body = new FilterInputStream(ByteStreams.limit(inputStream, contentLength)) {

            @Override
            public void close() {
            // Don't allow the parser to close the underlying stream
            }
        };
    }
    HttpResponse response = getFakeResponse(statusCode, body, headerNames, headerValues);
    parseAndCallback(requestInfos.get(contentId - 1), statusCode, response);
    // Consume any bytes that were not consumed by the parser
    while (body.skip(contentLength) > 0 || body.read() != -1) {
    }
    if (contentLength != -1) {
        line = readLine();
    } else {
    // The line was already read
    }
    // Consume any blank lines that follow the response (not included in Content-Length)
    while ((line != null) && (line.length() == 0)) {
        line = readLine();
    }
    checkForFinalBoundary(line);
}

87. MediaHttpDownloader#executeCurrentRequest()

View license
/**
   * Executes the current request.
   *
   * @param currentRequestLastBytePos last byte position for current request
   * @param requestUrl request URL where the download requests will be sent
   * @param requestHeaders request headers or {@code null} to ignore
   * @param outputStream destination output stream
   * @return HTTP response
   */
private HttpResponse executeCurrentRequest(long currentRequestLastBytePos, GenericUrl requestUrl, HttpHeaders requestHeaders, OutputStream outputStream) throws IOException {
    // prepare the GET request
    HttpRequest request = requestFactory.buildGetRequest(requestUrl);
    // add request headers
    if (requestHeaders != null) {
        request.getHeaders().putAll(requestHeaders);
    }
    // set Range header (if necessary)
    if (bytesDownloaded != 0 || currentRequestLastBytePos != -1) {
        StringBuilder rangeHeader = new StringBuilder();
        rangeHeader.append("bytes=").append(bytesDownloaded).append("-");
        if (currentRequestLastBytePos != -1) {
            rangeHeader.append(currentRequestLastBytePos);
        }
        request.getHeaders().setRange(rangeHeader.toString());
    }
    // execute the request and copy into the output stream
    HttpResponse response = request.execute();
    try {
        IOUtils.copy(response.getContent(), outputStream);
    } finally {
        response.disconnect();
    }
    return response;
}

88. MediaHttpUploader#directUpload()

View license
/**
   * Direct Uploads the media.
   *
   * @param initiationRequestUrl The request URL where the initiation request will be sent
   * @return HTTP response
   */
private HttpResponse directUpload(GenericUrl initiationRequestUrl) throws IOException {
    updateStateAndNotifyListener(UploadState.MEDIA_IN_PROGRESS);
    HttpContent content = mediaContent;
    if (metadata != null) {
        content = new MultipartContent().setContentParts(Arrays.asList(metadata, mediaContent));
        initiationRequestUrl.put("uploadType", "multipart");
    } else {
        initiationRequestUrl.put("uploadType", "media");
    }
    HttpRequest request = requestFactory.buildRequest(initiationRequestMethod, initiationRequestUrl, content);
    request.getHeaders().putAll(initiationHeaders);
    // We do not have to do anything special here if media content length is unspecified because
    // direct media upload works even when the media content length == -1.
    HttpResponse response = executeCurrentRequest(request);
    boolean responseProcessed = false;
    try {
        if (isMediaLengthKnown()) {
            totalBytesServerReceived = getMediaContentLength();
        }
        updateStateAndNotifyListener(UploadState.MEDIA_COMPLETE);
        responseProcessed = true;
    } finally {
        if (!responseProcessed) {
            response.disconnect();
        }
    }
    return response;
}

89. MediaHttpUploader#executeCurrentRequestWithoutGZip()

View license
/**
   * Executes the current request with some minimal common code.
   *
   * @param request current request
   * @return HTTP response
   */
private HttpResponse executeCurrentRequestWithoutGZip(HttpRequest request) throws IOException {
    // method override for non-POST verbs
    new MethodOverride().intercept(request);
    // don't throw an exception so we can let a custom Google exception be thrown
    request.setThrowExceptionOnExecuteError(false);
    // execute the request
    HttpResponse response = request.execute();
    return response;
}

90. MediaHttpUploader#executeCurrentRequest()

View license
/**
   * Executes the current request with some common code that includes exponential backoff and GZip
   * encoding.
   *
   * @param request current request
   * @return HTTP response
   */
private HttpResponse executeCurrentRequest(HttpRequest request) throws IOException {
    // enable GZip encoding if necessary
    if (!disableGZipContent && !(request.getContent() instanceof EmptyContent)) {
        request.setEncoding(new GZipEncoding());
    }
    // execute request
    HttpResponse response = executeCurrentRequestWithoutGZip(request);
    return response;
}

91. AbstractGoogleClientRequest#executeUnparsed()

View license
/**
   * Sends the metadata request using the given request method to the server and returns the raw
   * metadata {@link HttpResponse}.
   */
private HttpResponse executeUnparsed(boolean usingHead) throws IOException {
    HttpResponse response;
    if (uploader == null) {
        // normal request (not upload)
        response = buildHttpRequest(usingHead).execute();
    } else {
        // upload request
        GenericUrl httpRequestUrl = buildHttpRequestUrl();
        HttpRequest httpRequest = getAbstractGoogleClient().getRequestFactory().buildRequest(requestMethod, httpRequestUrl, httpContent);
        boolean throwExceptionOnExecuteError = httpRequest.getThrowExceptionOnExecuteError();
        response = uploader.setInitiationHeaders(requestHeaders).setDisableGZipContent(disableGZipContent).upload(httpRequestUrl);
        response.getRequest().setParser(getAbstractGoogleClient().getObjectParser());
        // process any error
        if (throwExceptionOnExecuteError && !response.isSuccessStatusCode()) {
            throw newExceptionOnError(response);
        }
    }
    // process response
    lastResponseHeaders = response.getHeaders();
    lastStatusCode = response.getStatusCode();
    lastStatusMessage = response.getStatusMessage();
    return response;
}

92. GoogleJsonErrorTest#testParse()

View license
public void testParse() throws Exception {
    HttpTransport transport = new ErrorTransport();
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonError errorResponse = GoogleJsonError.parse(FACTORY, response);
    assertEquals(ERROR, FACTORY.toString(errorResponse));
}

93. GoogleJsonResponseExceptionTest#testFrom_noDetails()

View license
public void testFrom_noDetails() throws Exception {
    HttpTransport transport = new MockHttpTransport();
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge = GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertEquals("200", ge.getMessage());
}

94. GoogleJsonResponseExceptionTest#testFrom_detailsMissingContent()

View license
public void testFrom_detailsMissingContent() throws Exception {
    HttpTransport transport = new ErrorTransport(null, Json.MEDIA_TYPE);
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge = GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertEquals("403", ge.getMessage());
}

95. GoogleJsonResponseExceptionTest#testFrom_detailsArbitraryJsonContent()

View license
public void testFrom_detailsArbitraryJsonContent() throws Exception {
    HttpTransport transport = new ErrorTransport("{\"foo\":\"bar\"}", Json.MEDIA_TYPE);
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge = GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertEquals("403", ge.getMessage());
}

96. GoogleJsonResponseExceptionTest#testFrom_errorNoContentButWithJsonContentType()

View license
public void testFrom_errorNoContentButWithJsonContentType() throws Exception {
    HttpTransport transport = new ErrorTransport("", Json.MEDIA_TYPE);
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge = GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertEquals("403", ge.getMessage());
}

97. GoogleJsonResponseExceptionTest#testFrom_errorEmptyContentButWithJsonContentType()

View license
public void testFrom_errorEmptyContentButWithJsonContentType() throws Exception {
    HttpTransport transport = new ErrorTransport(null, Json.MEDIA_TYPE);
    HttpRequest request = transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    HttpResponse response = request.execute();
    GoogleJsonResponseException ge = GoogleJsonResponseException.from(GoogleJsonErrorTest.FACTORY, response);
    assertNull(ge.getDetails());
    assertEquals("403", ge.getMessage());
}

98. MediaHttpUploaderTest#subtestUpload_ResumableWithError()

View license
public void subtestUpload_ResumableWithError(ErrorType error, int contentLength, boolean contentLengthKnown, int maxByteIndexUploadedOnError, int chunks, boolean force308OnRangeQueryResponse) throws Exception {
    MediaTransport fakeTransport = new MediaTransport(contentLength, true);
    if (error == ErrorType.IO_EXCEPTION) {
        fakeTransport.testIOException = true;
    } else if (error == ErrorType.SERVER_UNAVAILABLE) {
        fakeTransport.testServerError = true;
    }
    fakeTransport.contentLengthNotSpecified = !contentLengthKnown;
    fakeTransport.maxByteIndexUploadedOnError = maxByteIndexUploadedOnError;
    fakeTransport.force308OnRangeQueryResponse = force308OnRangeQueryResponse;
    byte[] testedData = new byte[contentLength];
    new Random().nextBytes(testedData);
    InputStream is = new ByteArrayInputStream(testedData);
    InputStreamContent mediaContent = new InputStreamContent(TEST_CONTENT_TYPE, is);
    if (contentLengthKnown) {
        mediaContent.setLength(contentLength);
    }
    MediaHttpUploader uploader = new MediaHttpUploader(mediaContent, fakeTransport, new ZeroBackOffRequestInitializer());
    // disable GZip - so we would be able to test byte received by server.
    uploader.setDisableGZipContent(true);
    HttpResponse response = uploader.upload(new GenericUrl(TEST_RESUMABLE_REQUEST_URL));
    assertEquals(200, response.getStatusCode());
    // There should be the following number of calls made:
    // 1 initiation request + 1 call to query the range + chunks
    int calls = 2 + chunks;
    assertEquals(calls, fakeTransport.lowLevelExecCalls);
    assertTrue(Arrays.equals(testedData, fakeTransport.bytesReceived));
}

99. 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;
}

100. ServiceAccountCredentials#refreshAccessToken()

View license
/**
   * Refreshes the OAuth2 access token by getting a new access token using a JSON Web Token (JWT).
   */
@Override
public AccessToken refreshAccessToken() throws IOException {
    if (createScopedRequired()) {
        throw new IOException("Scopes not configured for service account. Scoped should be specifed" + " by calling createScoped or passing scopes to constructor.");
    }
    JsonWebSignature.Header header = new JsonWebSignature.Header();
    header.setAlgorithm("RS256");
    header.setType("JWT");
    header.setKeyId(privateKeyId);
    JsonWebToken.Payload payload = new JsonWebToken.Payload();
    long currentTime = clock.currentTimeMillis();
    payload.setIssuer(clientEmail);
    payload.setAudience(OAuth2Utils.TOKEN_SERVER_URI.toString());
    payload.setIssuedAtTimeSeconds(currentTime / 1000);
    payload.setExpirationTimeSeconds(currentTime / 1000 + 3600);
    payload.setSubject(null);
    payload.put("scope", Joiner.on(' ').join(scopes));
    JsonFactory jsonFactory = OAuth2Utils.JSON_FACTORY;
    String assertion = null;
    try {
        assertion = JsonWebSignature.signUsingRsaSha256(privateKey, jsonFactory, header, payload);
    } catch (GeneralSecurityException e) {
        throw OAuth2Utils.exceptionWithCause(new IOException("Error signing service account access token request with private key."), e);
    }
    GenericData tokenRequest = new GenericData();
    tokenRequest.set("grant_type", GRANT_TYPE);
    tokenRequest.set("assertion", assertion);
    UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), content);
    request.setParser(new JsonObjectParser(jsonFactory));
    HttpResponse response;
    try {
        response = request.execute();
    } catch (IOException e) {
        throw OAuth2Utils.exceptionWithCause(new IOException("Error getting access token for service account: "), e);
    }
    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;
}