com.google.api.client.http.LowLevelHttpResponse Java Examples

The following examples show how to use com.google.api.client.http.LowLevelHttpResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UrlFetchRequest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpResponse execute() throws IOException {
  // write content
  if (getStreamingContent() != null) {
    String contentType = getContentType();
    if (contentType != null) {
      addHeader("Content-Type", contentType);
    }
    String contentEncoding = getContentEncoding();
    if (contentEncoding != null) {
      addHeader("Content-Encoding", contentEncoding);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    getStreamingContent().writeTo(out);
    byte[] payload = out.toByteArray();
    if (payload.length != 0) {
      request.setPayload(payload);
    }
  }
  // connect
  URLFetchService service = URLFetchServiceFactory.getURLFetchService();
  HTTPResponse response = service.fetch(request);
  return new UrlFetchResponse(response);
}
 
Example #2
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void normal() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(200);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  this.task.put(sinkRecords);
}
 
Example #3
Source File: GithubArchiveTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void repoExceptionOnDownloadFailure() throws Exception {
  httpTransport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
           MockLowLevelHttpRequest request = new MockLowLevelHttpRequest() {
              public LowLevelHttpResponse execute() throws IOException {
                throw new IOException("OH NOES!");
              }
           };
          return request;
        }
      };
  RemoteFileOptions options = new RemoteFileOptions();
  options.transport = () -> new GclientHttpStreamFactory(httpTransport, Duration.ofSeconds(20));
  Console console = new TestingConsole();
  OptionsBuilder optionsBuilder = new OptionsBuilder().setConsole(console);
  optionsBuilder.remoteFile = options;
  skylark = new SkylarkTestExecutor(optionsBuilder);
  ValidationException e = assertThrows(ValidationException.class, () -> skylark.eval("sha256",
      "sha256 = remotefiles.github_archive("
          + "project = 'google/copybara',"
          + "revision='674ac754f91e64a0efb8087e59a176484bd534d1').sha256()"));
  assertThat(e).hasCauseThat().hasCauseThat().hasCauseThat().isInstanceOf(RepoException.class);
}
 
Example #4
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void contentLengthTooLarge() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(417);
  when(httpResponse.getContentType()).thenReturn("text/html");
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
Example #5
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidIndex() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(400);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
Example #6
Source File: GoogleAuthTest.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
private HttpRequest constructHttpRequest(final String content, final int statusCode) throws IOException {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
          result.setContentType("application/json");
          result.setContent(content);
          result.setStatusCode(statusCode);
          return result;
        }
      };
    }
  };
  HttpRequest httpRequest = transport.createRequestFactory().buildGetRequest(new GenericUrl("https://google.com")).setParser(new JsonObjectParser(new JacksonFactory()));
  GoogleAuth.configureErrorHandling(httpRequest);
  return httpRequest;
}
 
Example #7
Source File: GitHubApiTransportImplTest.java    From copybara with Apache License 2.0 6 votes vote down vote up
@Test
public void testPasswordHeaderSet() throws Exception {
  Map<String, List<String>> headers = new HashMap<>();
  httpTransport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          headers.putAll(this.getHeaders());
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setContent("foo");
          return response;
        }
      };
    }
  };
  transport = new GitHubApiTransportImpl(repo, httpTransport, "store", new TestingConsole());
  transport.get("foo/bar", String.class);
  assertThat(headers).containsEntry("authorization", ImmutableList.of("Basic dXNlcjpTRUNSRVQ="));
}
 
Example #8
Source File: GitTestUtil.java    From copybara with Apache License 2.0 6 votes vote down vote up
public static LowLevelHttpRequest mockResponseWithStatus(
    String responseContent, int status, MockRequestAssertion requestValidator) {
  return new MockLowLevelHttpRequest() {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      assertWithMessage(
              String.format(
                  "Request <%s> did not match predicate: '%s'",
                  this.getContentAsString(), requestValidator))
          .that(requestValidator.test(this.getContentAsString()))
          .isTrue();
      // Responses contain a IntputStream for content. Cannot be reused between for two
      // consecutive calls. We create new ones per call here.
      return new MockLowLevelHttpResponse()
          .setContentType(Json.MEDIA_TYPE)
          .setContent(responseContent)
          .setStatusCode(status);
    }
  };
}
 
Example #9
Source File: SplunkHttpSinkTaskTest.java    From kafka-connect-splunk with Apache License 2.0 6 votes vote down vote up
@Test
public void invalidToken() throws IOException {
  Collection<SinkRecord> sinkRecords = new ArrayList<>();
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp"));
  SinkRecordContentTest.addRecord(sinkRecords, ImmutableMap.of("host", "hostname.example.com", "time", new Date(1472256858924L), "source", "testapp", "sourcetype", "txt", "index", "main"));

  final LowLevelHttpRequest httpRequest = mock(LowLevelHttpRequest.class, CALLS_REAL_METHODS);
  LowLevelHttpResponse httpResponse = getResponse(403);
  when(httpRequest.execute()).thenReturn(httpResponse);

  this.task.transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
      return httpRequest;
    }
  };

  this.task.httpRequestFactory = this.task.transport.createRequestFactory(this.task.httpRequestInitializer);
  assertThrows(org.apache.kafka.connect.errors.ConnectException.class, () -> this.task.put(sinkRecords));
}
 
Example #10
Source File: BigQueryServicesImplTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  // Set up the MockHttpRequest for future inspection
  request =
      new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          return response;
        }
      };

  // A mock transport that lets us mock the API responses.
  MockHttpTransport transport =
      new MockHttpTransport.Builder().setLowLevelHttpRequest(request).build();

  // A sample BigQuery API client that uses default JsonFactory and RetryHttpInitializer.
  bigquery =
      new Bigquery.Builder(
              transport, Transport.getJsonFactory(), new RetryHttpRequestInitializer())
          .build();
}
 
Example #11
Source File: IcannHttpReporterTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private MockHttpTransport createMockTransport (final ByteSource iirdeaResponse) {
  return new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      mockRequest = new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() throws IOException {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(200);
          response.setContentType(PLAIN_TEXT_UTF_8.toString());
          response.setContent(iirdeaResponse.read());
          return response;
        }
      };
      mockRequest.setUrl(url);
      return mockRequest;
    }
  };
}
 
Example #12
Source File: DirectoryGroupsConnectionTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/** Returns a valid GoogleJsonResponseException for the given status code and error message.  */
private GoogleJsonResponseException makeResponseException(
    final int statusCode,
    final String message) throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
          response.setStatusCode(statusCode);
          response.setContentType(Json.MEDIA_TYPE);
          response.setContent(String.format(
              "{\"error\":{\"code\":%d,\"message\":\"%s\",\"domain\":\"global\","
              + "\"reason\":\"duplicate\"}}",
              statusCode,
              message));
          return response;
        }};
    }};
  HttpRequest request = transport.createRequestFactory()
      .buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL)
      .setThrowExceptionOnExecuteError(false);
  return GoogleJsonResponseException.from(new JacksonFactory(), request.execute());
}
 
Example #13
Source File: FirebaseChannelTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void firebaseGet() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  firebaseChannel.firebaseGet(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("GET", FIREBASE_DB_URL + "/my/path");
}
 
Example #14
Source File: FirebaseChannelTest.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void firebaseDelete() throws Exception {
  // Mock out the firebase response. See
  // http://g.co/dv/api-client-library/java/google-http-java-client/unit-testing
  MockHttpTransport mockHttpTransport =
      spy(
          new MockHttpTransport() {
            @Override
            public LowLevelHttpRequest buildRequest(String method, String url)
                throws IOException {
              return new MockLowLevelHttpRequest() {
                @Override
                public LowLevelHttpResponse execute() throws IOException {
                  MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
                  response.setStatusCode(200);
                  return response;
                }
              };
            }
          });
  FirebaseChannel.getInstance().httpTransport = mockHttpTransport;

  firebaseChannel.firebaseDelete(FIREBASE_DB_URL + "/my/path");

  verify(mockHttpTransport, times(1)).buildRequest("DELETE", FIREBASE_DB_URL + "/my/path");
}
 
Example #15
Source File: OAuth2CredentialsTest.java    From rides-java-sdk with MIT License 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, final String url) throws IOException {
    return new MockLowLevelHttpRequest() {

        @Override
        public String getUrl() {
            return url;
        }

        @Override
        public LowLevelHttpResponse execute() throws IOException {
            lastRequestUrl = getUrl();
            lastRequestContent = getContentAsString();

            MockLowLevelHttpResponse mock = new MockLowLevelHttpResponse();
            mock.setStatusCode(httpStatusCode);
            mock.setContent(httpResponseContent);

            return mock;
        }
    };
}
 
Example #16
Source File: FakeWebServer.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  MockLowLevelHttpRequest request = new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      if (responses.isEmpty()) {
        throw new IOException(
            "Unexpected call to execute(), no injected responses left to return.");
      }
      return responses.remove();
    }
  };
  requests.add(new Request(method, request));
  return request;
}
 
Example #17
Source File: ApacheHttpRequest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpResponse execute() throws IOException {
  if (getStreamingContent() != null) {
    Preconditions.checkState(
        request instanceof HttpEntityEnclosingRequest,
        "Apache HTTP client does not support %s requests with content.",
        request.getRequestLine().getMethod());
    ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent());
    entity.setContentEncoding(getContentEncoding());
    entity.setContentType(getContentType());
    if (getContentLength() == -1) {
      entity.setChunked(true);
    }
    ((HttpEntityEnclosingRequest) request).setEntity(entity);
  }
  return new ApacheHttpResponse(request, httpClient.execute(request));
}
 
Example #18
Source File: NetHttpRequestTest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testInterruptedWriteWithResponse() throws Exception {
  MockHttpURLConnection connection =
      new MockHttpURLConnection(new URL(HttpTesting.SIMPLE_URL)) {
        @Override
        public OutputStream getOutputStream() throws IOException {
          return new OutputStream() {
            @Override
            public void write(int b) throws IOException {
              throw new IOException("Error writing request body to server");
            }
          };
        }
      };
  connection.setResponseCode(401);
  connection.setRequestMethod("POST");
  NetHttpRequest request = new NetHttpRequest(connection);
  InputStream is = NetHttpRequestTest.class.getClassLoader().getResourceAsStream("file.txt");
  HttpContent content = new InputStreamContent("text/plain", is);
  request.setStreamingContent(content);

  LowLevelHttpResponse response = request.execute();
  assertEquals(401, response.getStatusCode());
}
 
Example #19
Source File: ApacheHttpRequest.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpResponse execute() throws IOException {
  if (getStreamingContent() != null) {
    Preconditions.checkState(
        request instanceof HttpEntityEnclosingRequest,
        "Apache HTTP client does not support %s requests with content.",
        request.getRequestLine().getMethod());
    ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent());
    entity.setContentEncoding(getContentEncoding());
    entity.setContentType(getContentType());
    if (getContentLength() == -1) {
      entity.setChunked(true);
    }
    ((HttpEntityEnclosingRequest) request).setEntity(entity);
  }
  request.setConfig(requestConfig.build());
  return new ApacheHttpResponse(request, httpClient.execute(request));
}
 
Example #20
Source File: MockHttpTransportHelper.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
public static HttpResponse fakeResponse(Map<String, Object> headers, InputStream content)
    throws IOException {
  HttpTransport transport =
      new MockHttpTransport() {
        @Override
        public LowLevelHttpRequest buildRequest(String method, String url) {
          return new MockLowLevelHttpRequest() {
            @Override
            public LowLevelHttpResponse execute() {
              MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
              headers.forEach((h, hv) -> response.addHeader(h, String.valueOf(hv)));
              return response.setContent(content);
            }
          };
        }
      };
  HttpRequest request =
      transport.createRequestFactory().buildGetRequest(HttpTesting.SIMPLE_GENERIC_URL);
  return request.execute();
}
 
Example #21
Source File: MockHttpTransportHelper.java    From hadoop-connectors with Apache License 2.0 6 votes vote down vote up
public static MockHttpTransport mockTransport(LowLevelHttpResponse... responsesIn) {
  return new MockHttpTransport() {
    int responsesIndex = 0;
    final LowLevelHttpResponse[] responses = responsesIn;

    @Override
    public LowLevelHttpRequest buildRequest(String method, String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return responses[responsesIndex++];
        }
      };
    }
  };
}
 
Example #22
Source File: GooglePublicKeysManagerTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String name, String url) {
  return new MockLowLevelHttpRequest() {
      @Override
    public LowLevelHttpResponse execute() {
      MockLowLevelHttpResponse r = new MockLowLevelHttpResponse();
      r.setStatusCode(200);
      r.addHeader("Cache-Control", "max-age=" + MAX_AGE);
      if (useAgeHeader) {
        r.addHeader("Age", String.valueOf(AGE));
      }
      r.setContentType(Json.MEDIA_TYPE);
      r.setContent(TEST_CERTIFICATES);
      return r;
    }
  };
}
 
Example #23
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testExecuteUsingHead() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          assertEquals("HEAD", method);
          assertEquals("https://www.googleapis.com/test/path/v1/tests/foo", url);
          return new MockLowLevelHttpResponse();
        }
      };
    }
  };
  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, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  request.put("testId", "foo");
  request.executeUsingHead();
}
 
Example #24
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testExecute_void() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContent("{\"a\":\"ignored\"}")
              .setContentType(Json.MEDIA_TYPE);
        }
      };
    }
  };
  MockGoogleClient client = new MockGoogleClient.Builder(
      transport, ROOT_URL, SERVICE_PATH, JSON_OBJECT_PARSER, null).setApplicationName(
      "Test Application").build();
  MockGoogleClientRequest<Void> request =
      new MockGoogleClientRequest<Void>(client, HttpMethods.GET, URI_TEMPLATE, null, Void.class);
  Void v = request.execute();
  assertNull(v);
}
 
Example #25
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testReturnRawInputStream_defaultFalse() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContentEncoding("gzip").setContent(new ByteArrayInputStream(
              BaseEncoding.base64()
                  .decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=")));
        }
      };
    }
  };
  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, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  InputStream inputStream = request.executeAsInputStream();
  // The response will be wrapped because of gzip encoding
  assertFalse(inputStream instanceof ByteArrayInputStream);
}
 
Example #26
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
public void testReturnRawInputStream_True() throws Exception {
  HttpTransport transport = new MockHttpTransport() {
    @Override
    public LowLevelHttpRequest buildRequest(final String method, final String url) {
      return new MockLowLevelHttpRequest() {
        @Override
        public LowLevelHttpResponse execute() {
          return new MockLowLevelHttpResponse().setContentEncoding("gzip").setContent(new ByteArrayInputStream(
              BaseEncoding.base64()
                  .decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=")));
        }
      };
    }
  };
  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, HttpMethods.GET, URI_TEMPLATE, null, String.class);
  request.setReturnRawInputStream(true);
  InputStream inputStream = request.executeAsInputStream();
  // The response will not be wrapped due to setReturnRawInputStream(true)
  assertTrue(inputStream instanceof ByteArrayInputStream);
}
 
Example #27
Source File: AbstractGoogleClientRequestTest.java    From google-api-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
  return new MockLowLevelHttpRequest() {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      String firstHeader = getFirstHeaderValue(expectedHeader);
      assertTrue(
          String.format(
              "Expected header value to match %s, instead got %s.",
              expectedHeaderValue,
              firstHeader
          ),
          firstHeader.matches(expectedHeaderValue)
      );
      return new MockLowLevelHttpResponse();
    }
  };
}
 
Example #28
Source File: CustomTokenRequestTest.java    From google-oauth-java-client with Apache License 2.0 6 votes vote down vote up
@Override
public LowLevelHttpRequest buildRequest(String method, String url) {
  return new MockLowLevelHttpRequest(url) {
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
      response.setContentType(Json.MEDIA_TYPE);
      IdTokenResponse json = new IdTokenResponse();
      json.setAccessToken("abc");
      json.setRefreshToken("def");
      json.setExpiresInSeconds(3600L);
      json.setIdToken(JWT_ENCODED_CONTENT);
      response.setContent(JSON_FACTORY.toString(json));
      return response;
    }
  };
}
 
Example #29
Source File: BatchJobUploaderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that IOExceptions from executing an upload request are propagated properly.
 */
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_ioException_fails() throws Exception {
  final IOException ioException = new IOException("mock IO exception");
  MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      throw ioException;
    }
  };
  when(uploadBodyProvider.getHttpContent(request, true, true))
      .thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(lowLevelHttpRequest).build();
  uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
  BatchJobUploadStatus uploadStatus =
      new BatchJobUploadStatus(0, URI.create("http://www.example.com"));
  thrown.expect(BatchJobException.class);
  thrown.expectCause(Matchers.sameInstance(ioException));
  uploader.uploadIncrementalBatchJobOperations(request, true, uploadStatus);
}
 
Example #30
Source File: BatchJobUploaderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that IOExceptions from initiating an upload are propagated properly.
 */
@SuppressWarnings("rawtypes")
@Test
public void testUploadBatchJobOperations_initiateFails_fails() throws Exception {
  final IOException ioException = new IOException("mock IO exception");
  MockLowLevelHttpRequest lowLevelHttpRequest = new MockLowLevelHttpRequest(){
    @Override
    public LowLevelHttpResponse execute() throws IOException {
      throw ioException;
    }
  };
  when(uploadBodyProvider.getHttpContent(request, true, true))
      .thenReturn(new ByteArrayContent(null, "foo".getBytes(UTF_8)));
  MockHttpTransport transport = new MockHttpTransport.Builder()
      .setLowLevelHttpRequest(lowLevelHttpRequest).build();
  uploader = new BatchJobUploader(adWordsSession, transport, batchJobLogger);
  thrown.expect(BatchJobException.class);
  thrown.expectCause(Matchers.sameInstance(ioException));
  thrown.expectMessage("initiate upload");
  uploader.uploadIncrementalBatchJobOperations(request, true, new BatchJobUploadStatus(
      0, URI.create("http://www.example.com")));
}