下面列出了怎么用com.google.api.client.http.LowLevelHttpRequest的API类实例代码及写法,或者点击链接到github查看源代码。
@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;
}
@Test
public void verifyTokenCertificateError() {
MockHttpTransport failingTransport = new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
throw new IOException("Expected error");
}
};
GooglePublicKeysManager publicKeysManager = newPublicKeysManager(failingTransport);
FirebaseTokenVerifier idTokenVerifier = newTestTokenVerifier(publicKeysManager);
String token = tokenFactory.createToken();
try {
idTokenVerifier.verifyToken(token);
Assert.fail("No exception thrown");
} catch (FirebaseAuthException expected) {
assertTrue(expected.getCause() instanceof IOException);
assertEquals("Expected error", expected.getCause().getMessage());
}
}
@Test
public void testNoServiceAccount() throws Exception {
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(new MockGoogleCredentials("test-token"))
.setProjectId("test-project-id")
.setHttpTransport(new HttpTransport() {
@Override
protected LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
throw new IOException("transport error");
}
})
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
try {
FirebaseAuth.getInstance(app).createCustomTokenAsync("foo").get();
fail("Expected exception.");
} catch (IllegalStateException expected) {
Assert.assertEquals(
"Failed to initialize FirebaseTokenFactory. Make sure to initialize the SDK with "
+ "service account credentials or specify a service account ID with "
+ "iam.serviceAccounts.signBlob permission. Please refer to "
+ "https://firebase.google.com/docs/auth/admin/create-custom-tokens for more details "
+ "on creating custom tokens.",
expected.getMessage());
}
}
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;
}
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);
}
};
}
@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="));
}
private void mockChangeFound(GitRevision currentRev, int changeNum) throws IOException {
when(gitUtil
.httpTransport()
.buildRequest(eq("GET"), startsWith("https://localhost:33333/changes/")))
.then(
(Answer<LowLevelHttpRequest>)
invocation -> {
String change = changeIdFromRequest((String) invocation.getArguments()[1]);
return mockResponse(
String.format(
"[{"
+ "change_id : '%s',"
+ "status : 'NEW',"
+ "_number : '" + changeNum + "',"
+ "current_revision = '%s'}]",
change, currentRev.getSha1()));
});
}
@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);
}
@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);
}
@Test
public void connectionRefused() 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);
when(httpRequest.execute()).thenThrow(ConnectException.class);
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(RetriableException.class, () -> this.task.put(sinkRecords));
}
@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));
}
@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));
}
@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));
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
HttpTransport lowLevelTransport =
new HttpTransport() {
@Override
protected LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
return mockLowLevelRequest;
}
};
// Retry initializer will pass through to credential, since we can have
// only a single HttpRequestInitializer, and we use multiple Credential
// types in the SDK, not all of which allow for retry configuration.
RetryHttpRequestInitializer initializer =
new RetryHttpRequestInitializer(
new MockNanoClock(),
millis -> {},
Arrays.asList(418 /* I'm a teapot */),
mockHttpResponseInterceptor);
storage =
new Storage.Builder(lowLevelTransport, jsonFactory, initializer)
.setApplicationName("test")
.build();
}
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;
}
};
}
/** 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());
}
@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");
}
@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");
}
@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;
}
};
}
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();
}
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++];
}
};
}
};
}
@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;
}
};
}
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();
}
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);
}
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);
}
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);
}
@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();
}
};
}
@Override
public LowLevelHttpRequest buildRequest(final String method, String url) {
// First request should be to the resumable request url
if (method.equals("POST")) {
assertEquals(TEST_RESUMABLE_REQUEST_URL, url);
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() {
assertEquals(TEST_CONTENT_TYPE, getFirstHeaderValue("x-upload-content-type"));
// This is the initiation call.
MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
// Return 200 with the upload URI.
response.setStatusCode(200);
response.addHeader("Location", TEST_UPLOAD_URL);
return response;
}
};
}
// Fake an error when uploading chunks
return new MockLowLevelHttpRequest() {
@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;
}
};
}
public static HttpTransport createFaultyHttpTransport() {
return new HttpTransport() {
@Override
protected LowLevelHttpRequest buildRequest(String s, String s1) throws IOException {
throw new IOException("transport error");
}
};
}