com.google.api.client.http.HttpRequest

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

1. BatchRequestTest#subTestExecuteWithVoidCallback()

View license
public void subTestExecuteWithVoidCallback(boolean testServerError) throws Exception {
    MockTransport transport = new MockTransport(testServerError, false, false, false, false, false);
    MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH, null, null).setApplicationName("Test Application").build();
    MockGoogleClientRequest<String> jsonHttpRequest1 = new MockGoogleClientRequest<String>(client, METHOD1, URI_TEMPLATE1, null, String.class);
    MockGoogleClientRequest<String> jsonHttpRequest2 = new MockGoogleClientRequest<String>(client, METHOD2, URI_TEMPLATE2, null, String.class);
    ObjectParser parser = new JsonObjectParser(new JacksonFactory());
    BatchRequest batchRequest = new BatchRequest(transport, null).setBatchUrl(new GenericUrl(TEST_BATCH_URL));
    HttpRequest request1 = jsonHttpRequest1.buildHttpRequest();
    request1.setParser(parser);
    HttpRequest request2 = jsonHttpRequest2.buildHttpRequest();
    request2.setParser(parser);
    batchRequest.queue(request1, MockDataClass1.class, GoogleJsonErrorContainer.class, callback1);
    batchRequest.queue(request2, Void.class, Void.class, callback3);
    batchRequest.execute();
    // Assert transport called expected number of times.
    assertEquals(1, transport.actualCalls);
}

2. CredentialTest#subtestRefreshToken_request()

View license
private void subtestRefreshToken_request(AccessTokenTransport transport, int expectedCalls) throws Exception {
    Credential credential = new Credential.Builder(BearerToken.queryParameterAccessMethod()).setTransport(transport).setJsonFactory(JSON_FACTORY).setTokenServerUrl(TOKEN_SERVER_URL).setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)).build().setRefreshToken(REFRESH_TOKEN).setAccessToken(ACCESS_TOKEN);
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.setThrowExceptionOnExecuteError(false);
    request.execute();
    assertEquals(expectedCalls, transport.calls);
}

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

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

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

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

7. 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 + "{"));
}

8. 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 + "<"));
}

9. 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!");
}

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

11. StubsPortalTest#should_FindPostContentsNotEqual_WhenJsonParseExceptionThrown()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_FindPostContentsNotEqual_WhenJsonParseExceptionThrown() throws Exception {
    final String requestUrl = String.format("%s%s", STUBS_URL, "/complex/json/tree");
    final String content = "{this is an : invalid JSON string]";
    final HttpRequest request = HttpUtils.constructHttpRequest(HttpMethods.POST, requestUrl, content);
    final HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.setContentType(Common.HEADER_APPLICATION_JSON);
    request.setHeaders(httpHeaders);
    assertThat(request.execute().getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND_404);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

27. AbstractGoogleClientRequestTest#subtestBuildHttpRequest_emptyContent()

View license
private void subtestBuildHttpRequest_emptyContent(String method, boolean expectEmptyContent) throws Exception {
    HttpTransport transport = new MockHttpTransport();
    MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).setApplicationName("Test Application").build();
    MockGoogleClientRequest<String> request = new MockGoogleClientRequest<String>(client, method, URI_TEMPLATE, null, String.class);
    HttpRequest httpRequest = request.buildHttpRequest();
    if (expectEmptyContent) {
        assertTrue(httpRequest.getContent() instanceof EmptyContent);
    } else {
        assertNull(httpRequest.getContent());
    }
}

28. AppIdentityCredentialTest#testUsesAppIdentityService()

View license
public void testUsesAppIdentityService() throws IOException {
    final String expectedAccessToken = "ExpectedAccessToken";
    MockAppIdentityService appIdentity = new MockAppIdentityService();
    appIdentity.setAccessTokenText(expectedAccessToken);
    AppIdentityCredential.Builder builder = new AppIdentityCredential.Builder(SCOPES);
    builder.setAppIdentityService(appIdentity);
    AppIdentityCredential appCredential = builder.build();
    HttpTransport transport = new MockHttpTransport();
    HttpRequest request = transport.createRequestFactory().buildRequest("get", null, null);
    appCredential.intercept(request);
    assertEquals(appIdentity.getGetAccessTokenCallCount(), 1);
    HttpHeaders headers = request.getHeaders();
    String authHeader = headers.getAuthorization();
    Boolean headerContainsToken = authHeader.contains(expectedAccessToken);
    assertTrue(headerContainsToken);
}

29. HttpCredentialsAdapterTest#initialize_populatesOAuth2Credentials()

View license
@Test
public void initialize_populatesOAuth2Credentials() throws IOException {
    final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
    final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken;
    MockTokenServerTransport transport = new MockTokenServerTransport();
    transport.addClient(CLIENT_ID, CLIENT_SECRET);
    transport.addRefreshToken(REFRESH_TOKEN, accessToken);
    OAuth2Credentials credentials = new UserCredentials(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, transport, null);
    HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("http://foo"));
    adapter.initialize(request);
    HttpHeaders requestHeaders = request.getHeaders();
    String authorizationHeader = requestHeaders.getAuthorization();
    assertEquals(authorizationHeader, expectedAuthorization);
}

30. HttpCredentialsAdapterTest#initialize_noURI()

View license
@Test
public void initialize_noURI() throws IOException {
    final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
    final String expectedAuthorization = InternalAuthHttpConstants.BEARER_PREFIX + accessToken;
    MockTokenServerTransport transport = new MockTokenServerTransport();
    transport.addClient(CLIENT_ID, CLIENT_SECRET);
    transport.addRefreshToken(REFRESH_TOKEN, accessToken);
    OAuth2Credentials credentials = new UserCredentials(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, transport, null);
    HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request = requestFactory.buildGetRequest(null);
    adapter.initialize(request);
    HttpHeaders requestHeaders = request.getHeaders();
    String authorizationHeader = requestHeaders.getAuthorization();
    assertEquals(authorizationHeader, expectedAuthorization);
}

31. GooglePlusSample#run()

View license
private static void run() throws IOException {
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
    });
    PlusUrl url = PlusUrl.listPublicActivities(USER_ID).setMaxResults(MAX_RESULTS);
    url.put("fields", "items(id,url,object(content,plusoners/totalItems))");
    HttpRequest request = requestFactory.buildGetRequest(url);
    parseResponse(request.execute());
}

32. ClientParametersAuthenticationTest#test()

View license
public void test() throws Exception {
    HttpRequest request = new MockHttpTransport().createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    ClientParametersAuthentication auth = new ClientParametersAuthentication(CLIENT_ID, CLIENT_SECRET);
    assertEquals(CLIENT_ID, auth.getClientId());
    assertEquals(CLIENT_SECRET, auth.getClientSecret());
    auth.intercept(request);
    UrlEncodedContent content = (UrlEncodedContent) request.getContent();
    @SuppressWarnings("unchecked") Map<String, ?> data = (Map<String, ?>) content.getData();
    assertEquals(CLIENT_ID, data.get("client_id"));
    assertEquals(CLIENT_SECRET, data.get("client_secret"));
}

33. ClientParametersAuthenticationTest#test_noSecret()

View license
public void test_noSecret() throws Exception {
    HttpRequest request = new MockHttpTransport().createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
    ClientParametersAuthentication auth = new ClientParametersAuthentication(CLIENT_ID, null);
    assertEquals(CLIENT_ID, auth.getClientId());
    assertNull(auth.getClientSecret());
    auth.intercept(request);
    UrlEncodedContent content = (UrlEncodedContent) request.getContent();
    @SuppressWarnings("unchecked") Map<String, ?> data = (Map<String, ?>) content.getData();
    assertEquals(CLIENT_ID, data.get("client_id"));
    assertNull(data.get("client_secret"));
}

34. CredentialTest#testConstructor_expiredBody()

View license
public void testConstructor_expiredBody() throws Exception {
    HttpRequest request = subtestConstructor_expired(BearerToken.formEncodedBodyAccessMethod(), new CheckAuth() {

        public boolean checkAuth(MockLowLevelHttpRequest req) {
            return NEW_ACCESS_TOKEN.equals(((Map<?, ?>) ((UrlEncodedContent) req.getStreamingContent()).getData()).get("access_token"));
        }
    });
    assertEquals(NEW_ACCESS_TOKEN, ((Map<?, ?>) ((UrlEncodedContent) request.getContent()).getData()).get("access_token"));
}

35. DailyMotionSample#run()

View license
private static void run(HttpRequestFactory requestFactory) throws IOException {
    DailyMotionUrl url = new DailyMotionUrl("https://api.dailymotion.com/videos/favorites");
    url.setFields("id,tags,title,url");
    HttpRequest request = requestFactory.buildGetRequest(url);
    VideoFeed videoFeed = request.execute().parseAs(VideoFeed.class);
    if (videoFeed.list.isEmpty()) {
        System.out.println("No favorite videos found.");
    } else {
        if (videoFeed.hasMore) {
            System.out.print("First ");
        }
        System.out.println(videoFeed.list.size() + " favorite videos found:");
        for (Video video : videoFeed.list) {
            System.out.println();
            System.out.println("-----------------------------------------------");
            System.out.println("ID: " + video.id);
            System.out.println("Title: " + video.title);
            System.out.println("Tags: " + video.tags);
            System.out.println("URL: " + video.url);
        }
    }
}

36. 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 /");
}

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

38. 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 /");
}

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

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

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

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

43. 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 /");
}

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

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

46. 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 /");
}

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

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

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

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

51. 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!");
}

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

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

54. 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'");
}

55. 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'");
}

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

57. BatchUnparsedResponse#getFakeResponse()

View license
/** Create a fake HTTP response object populated with the partContent and the statusCode. */
private HttpResponse getFakeResponse(final int statusCode, final InputStream partContent, List<String> headerNames, List<String> headerValues) throws IOException {
    HttpRequest request = new FakeResponseHttpTransport(statusCode, partContent, headerNames, headerValues).createRequestFactory().buildPostRequest(new GenericUrl("http://google.com/"), null);
    request.setLoggingEnabled(false);
    request.setThrowExceptionOnExecuteError(false);
    return request.execute();
}

58. BatchRequestTest#getBatchPopulatedWithRequests()

View license
private BatchRequest getBatchPopulatedWithRequests(boolean testServerError, boolean testAuthenticationError, boolean returnSuccessAuthenticatedContent, boolean testExponentialBackOff, boolean testRedirect, boolean testBinary, boolean testMissingLength) throws Exception {
    transport = new MockTransport(testServerError, testAuthenticationError, testExponentialBackOff, testRedirect, testBinary, testMissingLength);
    MockGoogleClient client = new MockGoogleClient.Builder(transport, ROOT_URL, SERVICE_PATH, null, null).setApplicationName("Test Application").build();
    MockGoogleClientRequest<String> jsonHttpRequest1 = new MockGoogleClientRequest<String>(client, METHOD1, URI_TEMPLATE1, null, String.class);
    MockGoogleClientRequest<String> jsonHttpRequest2 = new MockGoogleClientRequest<String>(client, METHOD2, URI_TEMPLATE2, null, String.class);
    credential = new MockCredential();
    ObjectParser parser = testBinary ? new ProtoObjectParser() : new JsonObjectParser(new JacksonFactory());
    BatchRequest batchRequest = new BatchRequest(transport, credential).setBatchUrl(new GenericUrl(TEST_BATCH_URL));
    HttpRequest request1 = jsonHttpRequest1.buildHttpRequest();
    request1.setParser(parser);
    HttpRequest request2 = jsonHttpRequest2.buildHttpRequest();
    request2.setParser(parser);
    if (testAuthenticationError) {
        request2.setUnsuccessfulResponseHandler(new MockUnsuccessfulResponseHandler(transport, returnSuccessAuthenticatedContent));
    }
    if (testExponentialBackOff) {
        request2.setBackOffPolicy(new MockExponentialBackOffPolicy());
    }
    if (testBinary) {
        batchRequest.queue(request1, MockData.Class1.class, ErrorOutput.ErrorBody.class, new TestCallback1Adapter(callback1));
        batchRequest.queue(request2, MockData.Class2.class, ErrorOutput.ErrorBody.class, new TestCallback2Adapter(callback2));
    } else {
        batchRequest.queue(request1, MockDataClass1.class, GoogleJsonErrorContainer.class, callback1);
        batchRequest.queue(request2, MockDataClass2.class, GoogleJsonErrorContainer.class, callback2);
    }
    return batchRequest;
}

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

60. AbstractGoogleClientRequest#buildHttpRequest()

View license
/** Create a request suitable for use against this service. */
private HttpRequest buildHttpRequest(boolean usingHead) throws IOException {
    Preconditions.checkArgument(uploader == null);
    Preconditions.checkArgument(!usingHead || requestMethod.equals(HttpMethods.GET));
    String requestMethodToUse = usingHead ? HttpMethods.HEAD : requestMethod;
    final HttpRequest httpRequest = getAbstractGoogleClient().getRequestFactory().buildRequest(requestMethodToUse, buildHttpRequestUrl(), httpContent);
    new MethodOverride().intercept(httpRequest);
    httpRequest.setParser(getAbstractGoogleClient().getObjectParser());
    // custom methods may use POST with no content but require a Content-Length header
    if (httpContent == null && (requestMethod.equals(HttpMethods.POST) || requestMethod.equals(HttpMethods.PUT) || requestMethod.equals(HttpMethods.PATCH))) {
        httpRequest.setContent(new EmptyContent());
    }
    httpRequest.getHeaders().putAll(requestHeaders);
    if (!disableGZipContent) {
        httpRequest.setEncoding(new GZipEncoding());
    }
    final HttpResponseInterceptor responseInterceptor = httpRequest.getResponseInterceptor();
    httpRequest.setResponseInterceptor(new HttpResponseInterceptor() {

        public void interceptResponse(HttpResponse response) throws IOException {
            if (responseInterceptor != null) {
                responseInterceptor.interceptResponse(response);
            }
            if (!response.isSuccessStatusCode() && httpRequest.getThrowExceptionOnExecuteError()) {
                throw newExceptionOnError(response);
            }
        }
    });
    return httpRequest;
}

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

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

63. CredentialTest#subtestConstructor_expired()

View license
private HttpRequest subtestConstructor_expired(Credential.AccessMethod method, final CheckAuth checkAuth) throws Exception {
    final Credential credential = new Credential.Builder(method).setTransport(new AccessTokenTransport()).setJsonFactory(JSON_FACTORY).setTokenServerUrl(TOKEN_SERVER_URL).setClientAuthentication(new BasicAuthentication(CLIENT_ID, CLIENT_SECRET)).build().setAccessToken(ACCESS_TOKEN).setRefreshToken(REFRESH_TOKEN);
    class MyTransport extends MockHttpTransport {

        boolean resetAccessToken;

        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
            return new MockLowLevelHttpRequest(url) {

                @Override
                public LowLevelHttpResponse execute() {
                    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                    if (!checkAuth.checkAuth(this)) {
                        response.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
                        if (resetAccessToken) {
                            credential.setAccessToken(NEW_ACCESS_TOKEN);
                        }
                    }
                    return response;
                }
            };
        }
    }
    MyTransport transport = new MyTransport();
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.execute();
    credential.setAccessToken(ACCESS_TOKEN);
    transport.resetAccessToken = true;
    request.execute();
    return request;
}

64. 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\"}");
}

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

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

67. BatchRequest#execute()

View license
/**
   * Executes all queued HTTP requests in a single call, parses the responses and invokes callbacks.
   *
   * <p>
   * Calling {@link #execute()} executes and clears the queued requests. This means that the
   * {@link BatchRequest} object can be reused to {@link #queue} and {@link #execute()} requests
   * again.
   * </p>
   */
public void execute() throws IOException {
    boolean retryAllowed;
    Preconditions.checkState(!requestInfos.isEmpty());
    HttpRequest batchRequest = requestFactory.buildPostRequest(this.batchUrl, null);
    // NOTE: batch does not support gzip encoding
    HttpExecuteInterceptor originalInterceptor = batchRequest.getInterceptor();
    batchRequest.setInterceptor(new BatchInterceptor(originalInterceptor));
    int retriesRemaining = batchRequest.getNumberOfRetries();
    BackOffPolicy backOffPolicy = batchRequest.getBackOffPolicy();
    if (backOffPolicy != null) {
        // Reset the BackOffPolicy at the start of each execute.
        backOffPolicy.reset();
    }
    do {
        retryAllowed = retriesRemaining > 0;
        MultipartContent batchContent = new MultipartContent();
        batchContent.getMediaType().setSubType("mixed");
        int contentId = 1;
        for (RequestInfo<?, ?> requestInfo : requestInfos) {
            batchContent.addPart(new MultipartContent.Part(new HttpHeaders().setAcceptEncoding(null).set("Content-ID", contentId++), new HttpRequestContent(requestInfo.request)));
        }
        batchRequest.setContent(batchContent);
        HttpResponse response = batchRequest.execute();
        BatchUnparsedResponse batchResponse;
        try {
            // Find the boundary from the Content-Type header.
            String boundary = "--" + response.getMediaType().getParameter("boundary");
            // Parse the content stream.
            InputStream contentStream = response.getContent();
            batchResponse = new BatchUnparsedResponse(contentStream, boundary, requestInfos, retryAllowed);
            while (batchResponse.hasNext) {
                batchResponse.parseNextResponse();
            }
        } finally {
            response.disconnect();
        }
        List<RequestInfo<?, ?>> unsuccessfulRequestInfos = batchResponse.unsuccessfulRequestInfos;
        if (!unsuccessfulRequestInfos.isEmpty()) {
            requestInfos = unsuccessfulRequestInfos;
            // backOff if required.
            if (batchResponse.backOffRequired && backOffPolicy != null) {
                long backOffTime = backOffPolicy.getNextBackOffMillis();
                if (backOffTime != BackOffPolicy.STOP) {
                    try {
                        sleeper.sleep(backOffTime);
                    } catch (InterruptedException exception) {
                    }
                }
            }
        } else {
            break;
        }
        retriesRemaining--;
    } while (retryAllowed);
    requestInfos.clear();
}

68. ComputeCredential#executeRefreshToken()

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

69. BatchRequestTest#testExecute_checkWriteTo()

View license
public void testExecute_checkWriteTo() throws Exception {
    String request1Method = HttpMethods.POST;
    String request1Url = "http://test/dummy/url1";
    String request1ContentType = "application/json";
    String request1Content = "{\"data\":{\"foo\":{\"v1\":{}}}}";
    String request2Method = HttpMethods.GET;
    String request2Url = "http://test/dummy/url2";
    final StringBuilder expectedOutput = new StringBuilder();
    expectedOutput.append("--__END_OF_PART__\r\n");
    expectedOutput.append("Content-Length: 109\r\n");
    expectedOutput.append("Content-Type: application/http\r\n");
    expectedOutput.append("content-id: 1\r\n");
    expectedOutput.append("content-transfer-encoding: binary\r\n");
    expectedOutput.append("\r\n");
    expectedOutput.append("POST http://test/dummy/url1\r\n");
    expectedOutput.append("Content-Length: 26\r\n");
    expectedOutput.append("Content-Type: " + request1ContentType + "\r\n");
    expectedOutput.append("\r\n");
    expectedOutput.append(request1Content + "\r\n");
    expectedOutput.append("--__END_OF_PART__\r\n");
    expectedOutput.append("Content-Length: 30\r\n");
    expectedOutput.append("Content-Type: application/http\r\n");
    expectedOutput.append("content-id: 2\r\n");
    expectedOutput.append("content-transfer-encoding: binary\r\n");
    expectedOutput.append("\r\n");
    expectedOutput.append("GET http://test/dummy/url2\r\n");
    expectedOutput.append("\r\n");
    expectedOutput.append("\r\n");
    expectedOutput.append("--__END_OF_PART__--\r\n");
    MockHttpTransport transport = new MockHttpTransport();
    HttpRequest request1 = transport.createRequestFactory().buildRequest(request1Method, new GenericUrl(request1Url), new ByteArrayContent(request1ContentType, request1Content.getBytes()));
    HttpRequest request2 = transport.createRequestFactory().buildRequest(request2Method, new GenericUrl(request2Url), null);
    subtestExecute_checkWriteTo(expectedOutput.toString(), request1, request2);
}

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

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

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

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

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

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

76. MethodOverrideTest#testInterceptMaxLength()

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

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

78. UserAuthorizer#getCredentialsFromCode()

View license
/**
   * Returns a UserCredentials instance by exchanging an OAuth2 authorization code for tokens.
   *
   * @param code Code returned from OAuth2 consent prompt.
   * @param baseUri The URI to resolve the OAuth2 callback URI relative to.
   * @return the UserCredentials instance created from the authorization code.
   * @throws IOException An error from the server API call to get the tokens.
   */
public UserCredentials getCredentialsFromCode(String code, URI baseUri) throws IOException {
    Preconditions.checkNotNull(code);
    URI resolvedCallbackUri = getCallbackUri(baseUri);
    GenericData tokenData = new GenericData();
    tokenData.put("code", code);
    tokenData.put("client_id", clientId.getClientId());
    tokenData.put("client_secret", clientId.getClientSecret());
    tokenData.put("redirect_uri", resolvedCallbackUri);
    tokenData.put("grant_type", "authorization_code");
    UrlEncodedContent tokenContent = new UrlEncodedContent(tokenData);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest tokenRequest = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), tokenContent);
    tokenRequest.setParser(new JsonObjectParser(OAuth2Utils.JSON_FACTORY));
    HttpResponse tokenResponse = tokenRequest.execute();
    GenericJson parsedTokens = tokenResponse.parseAs(GenericJson.class);
    String accessTokenValue = OAuth2Utils.validateString(parsedTokens, "access_token", FETCH_TOKEN_ERROR);
    int expiresInSecs = OAuth2Utils.validateInt32(parsedTokens, "expires_in", FETCH_TOKEN_ERROR);
    Date expirationTime = new Date(new Date().getTime() + expiresInSecs * 1000);
    AccessToken accessToken = new AccessToken(accessTokenValue, expirationTime);
    String refreshToken = OAuth2Utils.validateOptionalString(parsedTokens, "refresh_token", FETCH_TOKEN_ERROR);
    UserCredentials credentials = new UserCredentials(clientId.getClientId(), clientId.getClientSecret(), refreshToken, accessToken, transport, tokenServerUri);
    return credentials;
}

79. UserAuthorizer#revokeAuthorization()

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

80. UserCredentials#refreshAccessToken()

View license
/**
   * Refreshes the OAuth2 access token by getting a new access token from the refresh token
   */
@Override
public AccessToken refreshAccessToken() throws IOException {
    if (refreshToken == null) {
        throw new IllegalStateException("UserCredentials instance cannot refresh because there is no" + " refresh token.");
    }
    GenericData tokenRequest = new GenericData();
    tokenRequest.set("client_id", clientId);
    tokenRequest.set("client_secret", clientSecret);
    tokenRequest.set("refresh_token", refreshToken);
    tokenRequest.set("grant_type", GRANT_TYPE);
    UrlEncodedContent content = new UrlEncodedContent(tokenRequest);
    HttpRequestFactory requestFactory = transport.createRequestFactory();
    HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(tokenServerUri), content);
    request.setParser(new JsonObjectParser(OAuth2Utils.JSON_FACTORY));
    HttpResponse response = request.execute();
    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;
}

81. CredentialTest#subtestConstructor()

View license
private HttpRequest subtestConstructor(Credential credential) throws Exception {
    MockHttpTransport transport = new MockHttpTransport();
    HttpRequestFactory requestFactory = transport.createRequestFactory(credential);
    HttpRequest request = requestFactory.buildDeleteRequest(HttpTesting.SIMPLE_GENERIC_URL);
    request.execute();
    return request;
}

82. PackageUtilTest#googleJsonResponseException()

Project: incubator-beam
Source File: PackageUtilTest.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);
}

83. GcsUtilTest#googleJsonResponseException()

Project: incubator-beam
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);
}

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

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

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

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

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

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

90. StubsPortalTest#should_ReturnExpectedRecordedResponse_OnSubsequentCallToValidUrl()

Project: stubby4j
Source File: StubsPortalTest.java
View license
@Test
public void should_ReturnExpectedRecordedResponse_OnSubsequentCallToValidUrl() throws Exception {
    ANSITerminal.muteConsole(false);
    final ByteArrayOutputStream consoleCaptor = new ByteArrayOutputStream();
    final boolean NO_AUTO_FLUSH = false;
    final PrintStream oldPrintStream = System.out;
    System.setOut(new PrintStream(consoleCaptor, NO_AUTO_FLUSH, StringUtils.UTF_8));
    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 int LIMIT = 5;
    for (int idx = 1; idx <= LIMIT; idx++) {
        final HttpResponse actualResponse = request.execute();
        final String actualConsoleOutput = consoleCaptor.toString(StringUtils.UTF_8).trim();
        String firstCallResponseContent = actualResponse.parseAsString().trim();
        assertThat(firstCallResponseContent).contains("<payment><invoiceTypeLookupCode>STANDARD</invoiceTypeLookupCode></payment>");
        // Make sure we only hitting recordabe source once
        assertThat(actualConsoleOutput).containsOnlyOnce("Recording HTTP response using");
        if (idx == LIMIT) {
            System.setOut(oldPrintStream);
            System.out.println(actualConsoleOutput);
        }
    }
}

91. RetryHttpInitializerWrapperTests#testRetryWaitTooLong()

View license
public void testRetryWaitTooLong() throws Exception {
    TimeValue maxWaitTime = TimeValue.timeValueMillis(10);
    int maxRetryTimes = 50;
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, maxRetryTimes);
    JsonFactory jsonFactory = new JacksonFactory();
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper oneTimeSleeper = new MockSleeper() {

        @Override
        public void sleep(long millis) throws InterruptedException {
            Thread.sleep(maxWaitTime.getMillis());
            // important number, use this to get count
            super.sleep(0);
        }
    };
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, oneTimeSleeper, maxWaitTime);
    Compute client = new Compute.Builder(fakeTransport, jsonFactory, null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
    HttpRequest request1 = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    try {
        request1.execute();
        fail("Request should fail if wait too long");
    } catch (HttpResponseException e) {
        assertThat(e.getStatusCode(), equalTo(HttpStatusCodes.STATUS_CODE_SERVER_ERROR));
        assertThat(oneTimeSleeper.getCount(), lessThan(maxRetryTimes));
    }
}

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

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

94. BatchRequestTest#subtestExecute_checkWriteTo()

View license
private void subtestExecute_checkWriteTo(final String expectedOutput, HttpRequest... requests) throws IOException {
    MockHttpTransport transport = new MockHttpTransport() {

        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
            return new MockLowLevelHttpRequest(url) {

                @Override
                public LowLevelHttpResponse execute() throws IOException {
                    assertEquals("multipart/mixed; boundary=__END_OF_PART__", getContentType());
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    getStreamingContent().writeTo(out);
                    assertEquals(expectedOutput, out.toString("UTF-8"));
                    MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                    response.setStatusCode(200);
                    response.addHeader("Content-Type", "multipart/mixed; boundary=" + RESPONSE_BOUNDARY);
                    String content2 = "{\"name\": \"" + TEST_NAME + "\", \"number\": \"" + TEST_NUM + "\"}";
                    StringBuilder responseContent = new StringBuilder();
                    responseContent.append("--" + RESPONSE_BOUNDARY + "\n").append("Content-Type: application/http\n").append("Content-Transfer-Encoding: binary\n").append("Content-ID: response-1\n\n").append("HTTP/1.1 200 OK\n").append("Content-Type: application/json; charset=UTF-8\n").append("Content-Length: " + content2.length() + "\n\n").append(content2 + "\n\n").append("--" + RESPONSE_BOUNDARY + "--\n\n");
                    response.setContent(responseContent.toString());
                    return response;
                }
            };
        }
    };
    BatchRequest batchRequest = new BatchRequest(transport, null);
    BatchCallback<Void, Void> callback = new BatchCallback<Void, Void>() {

        @Override
        public void onSuccess(Void t, HttpHeaders responseHeaders) {
        }

        @Override
        public void onFailure(Void e, HttpHeaders responseHeaders) {
        }
    };
    for (HttpRequest request : requests) {
        batchRequest.queue(request, Void.class, Void.class, callback);
    }
    batchRequest.execute();
}

95. BatchRequestTest#testExecute_checkWriteToNoHeaders()

View license
public void testExecute_checkWriteToNoHeaders() throws Exception {
    MockHttpTransport transport = new MockHttpTransport();
    HttpRequest request1 = transport.createRequestFactory().buildPostRequest(HttpTesting.SIMPLE_GENERIC_URL, new HttpContent() {

        @Override
        public long getLength() {
            return -1;
        }

        @Override
        public String getType() {
            return null;
        }

        @Override
        public void writeTo(OutputStream out) {
        }

        @Override
        public boolean retrySupported() {
            return true;
        }
    });
    subtestExecute_checkWriteTo(new StringBuilder().append("--__END_OF_PART__\r\n").append("Content-Length: 27\r\n").append("Content-Type: application/http\r\n").append("content-id: 1\r\n").append("content-transfer-encoding: binary\r\n").append("\r\n").append("POST http://google.com/\r\n").append("\r\n").append("\r\n").append("--__END_OF_PART__--\r\n").toString(), request1);
}

96. MethodOverrideTest#subtestIntercept()

View license
private void subtestIntercept(boolean shouldOverride, HttpTransport transport, MethodOverride interceptor, String requestMethod) throws Exception {
    HttpRequest request = transport.createRequestFactory().buildRequest(requestMethod, HttpTesting.SIMPLE_GENERIC_URL, null);
    interceptor.intercept(request);
    assertEquals(requestMethod, shouldOverride ? HttpMethods.POST : requestMethod, request.getRequestMethod());
    assertEquals(requestMethod, shouldOverride ? requestMethod : null, request.getHeaders().get(MethodOverride.HEADER));
}

97. AppIdentityCredentialTest#testAppEngineCredentialWrapper()

View license
public void testAppEngineCredentialWrapper() throws IOException {
    final String expectedAccessToken = "ExpectedAccessToken";
    final Collection<String> emptyScopes = Collections.emptyList();
    HttpTransport transport = new MockHttpTransport();
    JsonFactory jsonFactory = new JacksonFactory();
    MockAppIdentityService appIdentity = new MockAppIdentityService();
    appIdentity.setAccessTokenText(expectedAccessToken);
    AppIdentityCredential.Builder builder = new AppIdentityCredential.Builder(emptyScopes);
    builder.setAppIdentityService(appIdentity);
    AppIdentityCredential appCredential = builder.build();
    GoogleCredential wrapper = new AppIdentityCredential.AppEngineCredentialWrapper(appCredential, transport, jsonFactory);
    HttpRequest request = transport.createRequestFactory().buildRequest("get", null, null);
    assertTrue(wrapper.createScopedRequired());
    try {
        wrapper.intercept(request);
        fail("Should not be able to use credential without scopes.");
    } catch (Exception expected) {
    }
    assertEquals(appIdentity.getGetAccessTokenCallCount(), 1);
    GoogleCredential scopedWrapper = wrapper.createScoped(SCOPES);
    assertNotSame(wrapper, scopedWrapper);
    scopedWrapper.intercept(request);
    assertEquals(appIdentity.getGetAccessTokenCallCount(), 2);
    HttpHeaders headers = request.getHeaders();
    String authHeader = headers.getAuthorization();
    assertTrue(authHeader.contains(expectedAccessToken));
}

98. HttpCredentialsAdapterTest#initialize_populatesOAuth2Credentials_handle401()

View license
@Test
public void initialize_populatesOAuth2Credentials_handle401() throws IOException {
    final String accessToken = "1/MkSJoj1xsli0AccessToken_NKPY2";
    final String accessToken2 = "2/MkSJoj1xsli0AccessToken_NKPY2";
    final MockTokenServerTransport tokenServerTransport = new MockTokenServerTransport();
    tokenServerTransport.addClient(CLIENT_ID, CLIENT_SECRET);
    tokenServerTransport.addRefreshToken(REFRESH_TOKEN, accessToken);
    OAuth2Credentials credentials = new UserCredentials(CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, null, tokenServerTransport, null);
    credentials.refresh();
    HttpCredentialsAdapter adapter = new HttpCredentialsAdapter(credentials);
    HttpTransport primaryHttpTransport = new MockTokenCheckingTransport(tokenServerTransport, REFRESH_TOKEN);
    HttpRequestFactory requestFactory = primaryHttpTransport.createRequestFactory();
    HttpRequest request = requestFactory.buildGetRequest(new GenericUrl("http://foo"));
    adapter.initialize(request);
    // now switch out the access token so that the original one is invalid,
    //   requiring a refresh of the access token
    tokenServerTransport.addRefreshToken(REFRESH_TOKEN, accessToken2);
    HttpResponse response = request.execute();
    // make sure that the request is successful despite the invalid access token
    assertEquals(200, response.getStatusCode());
    assertEquals(MockTokenCheckingTransport.SUCCESS_CONTENT, response.parseAsString());
}

99. DailyMotionSample#run()

View license
private static void run() throws Exception {
    HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory(new HttpRequestInitializer() {

        @Override
        public void initialize(HttpRequest request) {
            request.setParser(new JsonObjectParser(JSON_FACTORY));
        }
    });
    DailyMotionUrl url = new DailyMotionUrl("https://api.dailymotion.com/videos/");
    url.fields = "id,tags,title,url";
    HttpRequest request = requestFactory.buildGetRequest(url);
    VideoFeed videoFeed = request.execute().parseAs(VideoFeed.class);
    if (videoFeed.list.isEmpty()) {
        System.out.println("No videos found.");
    } else {
        if (videoFeed.hasMore) {
            System.out.print("First ");
        }
        System.out.println(videoFeed.list.size() + " videos found:");
        for (Video video : videoFeed.list) {
            System.out.println();
            System.out.println("-----------------------------------------------");
            System.out.println("ID: " + video.id);
            System.out.println("Title: " + video.title);
            System.out.println("Tags: " + video.tags);
            System.out.println("URL: " + video.url);
        }
    }
}

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