下面列出了怎么用com.google.api.client.http.HttpStatusCodes的API类实例代码及写法,或者点击链接到github查看源代码。
public void testDefaultCredentialComputeErrorNotFound() throws IOException {
MockMetadataServerTransport transport = new MockMetadataServerTransport(ACCESS_TOKEN);
transport.setTokenRequestStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND);
TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider();
Credential defaultCredential = testProvider.getDefaultCredential(transport, JSON_FACTORY);
assertNotNull(defaultCredential);
try {
defaultCredential.refreshToken();
fail("Expected error refreshing token.");
} catch (IOException expected) {
String message = expected.getMessage();
assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_NOT_FOUND)));
assertTrue(message.contains("scope"));
}
}
@Test
public void testNonExistentObjectReturnsEmptyResult() throws IOException {
GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
GcsUtil gcsUtil = pipelineOptions.getGcsUtil();
Storage mockStorage = Mockito.mock(Storage.class);
gcsUtil.setStorageClient(mockStorage);
Storage.Objects mockStorageObjects = Mockito.mock(Storage.Objects.class);
Storage.Objects.Get mockStorageGet = Mockito.mock(Storage.Objects.Get.class);
GcsPath pattern = GcsPath.fromUri("gs://testbucket/testdirectory/nonexistentfile");
GoogleJsonResponseException expectedException =
googleJsonResponseException(
HttpStatusCodes.STATUS_CODE_NOT_FOUND, "It don't exist", "Nothing here to see");
when(mockStorage.objects()).thenReturn(mockStorageObjects);
when(mockStorageObjects.get(pattern.getBucket(), pattern.getObject()))
.thenReturn(mockStorageGet);
when(mockStorageGet.execute()).thenThrow(expectedException);
assertEquals(Collections.emptyList(), gcsUtil.expand(pattern));
}
@Test
public void testFileSizeWhenFileNotFoundNonBatch() throws Exception {
MockLowLevelHttpResponse notFoundResponse = new MockLowLevelHttpResponse();
notFoundResponse.setContent("");
notFoundResponse.setStatusCode(HttpStatusCodes.STATUS_CODE_NOT_FOUND);
MockHttpTransport mockTransport =
new MockHttpTransport.Builder().setLowLevelHttpResponse(notFoundResponse).build();
GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
GcsUtil gcsUtil = pipelineOptions.getGcsUtil();
gcsUtil.setStorageClient(new Storage(mockTransport, Transport.getJsonFactory(), null));
thrown.expect(FileNotFoundException.class);
gcsUtil.fileSize(GcsPath.fromComponents("testbucket", "testobject"));
}
@Test
public void testBucketDoesNotExist() throws IOException {
GcsOptions pipelineOptions = gcsOptionsWithTestCredential();
GcsUtil gcsUtil = pipelineOptions.getGcsUtil();
Storage mockStorage = Mockito.mock(Storage.class);
gcsUtil.setStorageClient(mockStorage);
Storage.Buckets mockStorageObjects = Mockito.mock(Storage.Buckets.class);
Storage.Buckets.Get mockStorageGet = Mockito.mock(Storage.Buckets.Get.class);
BackOff mockBackOff = BackOffAdapter.toGcpBackOff(FluentBackoff.DEFAULT.backoff());
when(mockStorage.buckets()).thenReturn(mockStorageObjects);
when(mockStorageObjects.get("testbucket")).thenReturn(mockStorageGet);
when(mockStorageGet.execute())
.thenThrow(
googleJsonResponseException(
HttpStatusCodes.STATUS_CODE_NOT_FOUND, "It don't exist", "Nothing here to see"));
assertFalse(
gcsUtil.bucketAccessible(
GcsPath.fromComponents("testbucket", "testobject"),
mockBackOff,
new FastNanoClockAndSleeper()));
}
/**
* Logs the specified request and response information.
*
* <p>Note that in order to avoid any temptation to consume the contents of the response, this
* does <em>not</em> take an {@link com.google.api.client.http.HttpResponse} object, but instead
* accepts the status code and message from the response.
*/
public void logRequest(
@Nullable HttpRequest request, int statusCode, @Nullable String statusMessage) {
boolean isSuccess = HttpStatusCodes.isSuccess(statusCode);
if (!loggerDelegate.isSummaryLoggable(isSuccess)
&& !loggerDelegate.isDetailsLoggable(isSuccess)) {
return;
}
// Populate the RequestInfo builder from the request.
RequestInfo requestInfo = buildRequestInfo(request);
// Populate the ResponseInfo builder from the response.
ResponseInfo responseInfo = buildResponseInfo(request, statusCode, statusMessage);
RemoteCallReturn.Builder remoteCallReturnBuilder =
new RemoteCallReturn.Builder().withRequestInfo(requestInfo).withResponseInfo(responseInfo);
if (!isSuccess) {
remoteCallReturnBuilder.withException(
new ReportException(String.format("%s: %s", statusCode, statusMessage)));
}
RemoteCallReturn remoteCallReturn = remoteCallReturnBuilder.build();
loggerDelegate.logRequestSummary(remoteCallReturn);
loggerDelegate.logRequestDetails(remoteCallReturn);
}
/** Test successful operation of GoogleCloudStorage.delete(2) with generationId. */
@Test
public void testDeleteObjectWithGenerationId() throws IOException {
int generationId = 65;
MockHttpTransport transport =
mockTransport(emptyResponse(HttpStatusCodes.STATUS_CODE_NO_CONTENT));
GoogleCloudStorage gcs = mockedGcs(transport);
gcs.deleteObjects(
ImmutableList.of(new StorageResourceId(BUCKET_NAME, OBJECT_NAME, generationId)));
assertThat(trackingHttpRequestInitializer.getAllRequestStrings())
.containsExactly(
deleteRequestString(
BUCKET_NAME, OBJECT_NAME, generationId, /* replaceGenerationId= */ false))
.inOrder();
}
@Override
public void service(HttpRequest request, HttpResponse response) throws Exception {
var writer = new PrintWriter(response.getWriter());
try {
DatabaseClient client = getClient();
try (ResultSet rs =
client
.singleUse()
.executeQuery(Statement.of("SELECT SingerId, AlbumId, AlbumTitle FROM Albums"))) {
writer.printf("Albums:%n");
while (rs.next()) {
writer.printf(
"%d %d %s%n",
rs.getLong("SingerId"), rs.getLong("AlbumId"), rs.getString("AlbumTitle"));
}
} catch (SpannerException e) {
writer.printf("Error querying database: %s%n", e.getMessage());
response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, e.getMessage());
}
} catch (Throwable t) {
logger.log(Level.SEVERE, "Spanner example failed", t);
writer.printf("Error setting up Spanner: %s%n", t.getMessage());
response.setStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, t.getMessage());
}
}
void createDataset(String projectId, Dataset dataset)
throws IOException
{
try {
client.datasets().insert(projectId, dataset)
.execute();
}
catch (GoogleJsonResponseException e) {
if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_CONFLICT) {
logger.debug("Dataset already exists: {}:{}", dataset.getDatasetReference());
}
else {
throw e;
}
}
}
void createTable(String projectId, Table table)
throws IOException
{
String datasetId = table.getTableReference().getDatasetId();
try {
client.tables().insert(projectId, datasetId, table)
.execute();
}
catch (GoogleJsonResponseException e) {
if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_CONFLICT) {
logger.debug("Table already exists: {}:{}.{}", projectId, datasetId, table.getTableReference().getTableId());
}
else {
throw e;
}
}
}
/**
* Creates a Cloud Pub/Sub topic if it doesn't exist.
*
* @param client Pubsub client object.
* @throws IOException when API calls to Cloud Pub/Sub fails.
*/
private void setupTopic(final Pubsub client) throws IOException {
String fullName = String.format("projects/%s/topics/%s",
PubsubUtils.getProjectId(),
PubsubUtils.getAppTopicName());
try {
client.projects().topics().get(fullName).execute();
} catch (GoogleJsonResponseException e) {
if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_NOT_FOUND) {
// Create the topic if it doesn't exist
client.projects().topics()
.create(fullName, new Topic())
.execute();
} else {
throw e;
}
}
}
/**
* Triggers the authentication process for the associated {@code username}.
*/
public void getUserAuthenticated() throws IOException {
// assume user is authenticated before
service = new GmailServiceMaker(username).makeGmailService();
while (true) {
try {
// touch one API endpoint to check authentication
getListOfUnreadEmailOfUser();
break;
} catch (HttpResponseException e) {
if (e.getStatusCode() == HttpStatusCodes.STATUS_CODE_FORBIDDEN
|| e.getStatusCode() == HttpStatusCodes.STATUS_CODE_UNAUTHORIZED
|| e.getStatusCode() == HttpStatusCodes.STATUS_CODE_BAD_REQUEST) {
System.out.println(e.getMessage());
// existing credential missing or not working, should do authentication for the account again
service = new GmailServiceMaker(username, true).makeGmailService();
} else {
throw new IOException(e);
}
}
}
}
@Before
public void setUp() throws Exception {
accessDenied =
googleJsonResponseException(
HttpStatusCodes.STATUS_CODE_FORBIDDEN, "Forbidden", "Forbidden");
statusOk = googleJsonResponseException(HttpStatusCodes.STATUS_CODE_OK, "A reason", "ok");
notFound =
googleJsonResponseException(
HttpStatusCodes.STATUS_CODE_NOT_FOUND, "Not found", "Not found");
badRange =
googleJsonResponseException(
ApiErrorExtractor.STATUS_CODE_RANGE_NOT_SATISFIABLE, "Bad range", "Bad range");
alreadyExists = googleJsonResponseException(409, "409", "409");
resourceNotReady =
googleJsonResponseException(
400, ApiErrorExtractor.RESOURCE_NOT_READY_REASON, "Resource not ready");
// This works because googleJsonResponseException takes final ErrorInfo
ErrorInfo errorInfo = new ErrorInfo();
errorInfo.setReason(ApiErrorExtractor.RATE_LIMITED_REASON);
notRateLimited = googleJsonResponseException(POSSIBLE_RATE_LIMIT, errorInfo, "");
errorInfo.setDomain(ApiErrorExtractor.USAGE_LIMITS_DOMAIN);
rateLimited = googleJsonResponseException(POSSIBLE_RATE_LIMIT, errorInfo, "");
errorInfo.setDomain(ApiErrorExtractor.GLOBAL_DOMAIN);
bigqueryRateLimited = googleJsonResponseException(POSSIBLE_RATE_LIMIT, errorInfo, "");
}
public void testDefaultCredentialComputeErrorUnexpected() throws IOException {
MockMetadataServerTransport transport = new MockMetadataServerTransport(ACCESS_TOKEN);
transport.setTokenRequestStatusCode(HttpStatusCodes.STATUS_CODE_SERVER_ERROR);
TestDefaultCredentialProvider testProvider = new TestDefaultCredentialProvider();
Credential defaultCredential = testProvider.getDefaultCredential(transport, JSON_FACTORY);
assertNotNull(defaultCredential);
try {
defaultCredential.refreshToken();
fail("Expected error refreshing token.");
} catch (IOException expected) {
String message = expected.getMessage();
assertTrue(message.contains(Integer.toString(HttpStatusCodes.STATUS_CODE_SERVER_ERROR)));
assertTrue(message.contains("Unexpected"));
}
}
@Test
public void testCStoreService_success() throws Exception {
basicCStoreServiceTest(
false,
HttpStatusCodes.STATUS_CODE_OK,
Status.Success);
}
@Test
public void testCStoreService_connectionError() throws Exception {
basicCStoreServiceTest(
true,
HttpStatusCodes.STATUS_CODE_OK, // won't be returned due to connectionError
Status.ProcessingFailure);
}
@Test
public void testCStoreService_unauthorized() throws Exception {
basicCStoreServiceTest(
false,
HttpStatusCodes.STATUS_CODE_UNAUTHORIZED,
Status.NotAuthorized);
}
@Test
public void testCStoreService_serviceUnavailable() throws Exception {
basicCStoreServiceTest(
false,
HttpStatusCodes.STATUS_CODE_SERVICE_UNAVAILABLE,
Status.OutOfResources);
}
@Test
public void testCStoreService_noSopInstanceUid() throws Exception {
basicCStoreServiceTest(
true, // no stow-rs request will be made
HttpStatusCodes.STATUS_CODE_OK,
Status.CannotUnderstand,
null,
UID.MRImageStorage,
null,
TestUtils.TEST_MR_FILE,
null);
}
@Test
public void testCStoreService_map_success() throws Exception {
basicCStoreServiceTest(
true,
HttpStatusCodes.STATUS_CODE_SERVER_ERROR,
Status.Success,
new MockDestinationConfig[] {
new MockDestinationConfig("StudyDate=19921012&SOPInstanceUID=1.0.0.0",
false, HttpStatusCodes.STATUS_CODE_OK)
});
}
@Test
public void testCStoreService_map_byAet() throws Exception {
basicCStoreServiceTest(
true,
HttpStatusCodes.STATUS_CODE_SERVER_ERROR,
Status.Success,
new MockDestinationConfig[] {
new MockDestinationConfig("StudyDate=19921012&AETitle=CSTORECLIENT",
false, HttpStatusCodes.STATUS_CODE_OK)
});
}
@Test
public void testCStoreService_map_connectionError() throws Exception {
basicCStoreServiceTest(
false,
HttpStatusCodes.STATUS_CODE_OK,
Status.ProcessingFailure,
new MockDestinationConfig[] {
new MockDestinationConfig("StudyDate=19921012&SOPInstanceUID=1.0.0.0",
true, HttpStatusCodes.STATUS_CODE_OK)
});
}
@Test
public void testCStoreService_map_filterOrder_failFirst() throws Exception {
basicCStoreServiceTest(
false,
HttpStatusCodes.STATUS_CODE_OK,
Status.ProcessingFailure,
new MockDestinationConfig[] {
new MockDestinationConfig("StudyDate=19921012&SOPInstanceUID=1.0.0.0",
true, HttpStatusCodes.STATUS_CODE_SERVER_ERROR),
new MockDestinationConfig("StudyDate=19921012",
false, HttpStatusCodes.STATUS_CODE_OK),
});
}
@Test
public void testCStoreService_map_emptyFilterMatches() throws Exception {
basicCStoreServiceTest(
true,
HttpStatusCodes.STATUS_CODE_SERVER_ERROR,
Status.Success,
new MockDestinationConfig[] {
new MockDestinationConfig("", false, HttpStatusCodes.STATUS_CODE_OK)
});
}
@Test
public void testCStoreService_map_defaultClientOnNoMatch() throws Exception {
basicCStoreServiceTest(
false,
HttpStatusCodes.STATUS_CODE_OK,
Status.Success,
new MockDestinationConfig[] {
new MockDestinationConfig("StudyDate=NoSuchValue",
true, HttpStatusCodes.STATUS_CODE_SERVER_ERROR),
new MockDestinationConfig("SOPInstanceUID=NoSuchValue",
true, HttpStatusCodes.STATUS_CODE_SERVER_ERROR),
});
}
@Test(expected = IllegalArgumentException.class)
public void testCStoreService_map_invalidFilter_noSuchTag() throws Exception {
basicCStoreServiceTest(
false,
HttpStatusCodes.STATUS_CODE_OK,
Status.Success,
new MockDestinationConfig[] {
new MockDestinationConfig("NoSuchTag=NoSuchValue",
true, HttpStatusCodes.STATUS_CODE_SERVER_ERROR),
});
}
public void testExecuteUnparsed_error() throws Exception {
HttpTransport transport = new MockHttpTransport() {
@Override
public LowLevelHttpRequest buildRequest(final String method, final String url) {
return new MockLowLevelHttpRequest() {
@Override
public LowLevelHttpResponse execute() {
assertEquals("GET", method);
assertEquals("https://www.googleapis.com/test/path/v1/tests/foo", url);
MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
result.setStatusCode(HttpStatusCodes.STATUS_CODE_UNAUTHORIZED);
result.setContentType(Json.MEDIA_TYPE);
result.setContent(ERROR_CONTENT);
return result;
}
};
}
};
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);
try {
request.put("testId", "foo");
request.executeUnparsed();
fail("expected " + HttpResponseException.class);
} catch (HttpResponseException e) {
// expected
assertEquals("401" + StringUtils.LINE_SEPARATOR + ERROR_CONTENT, e.getMessage());
}
}
@Test
public void testCStoreService_map_tagByHex() throws Exception {
basicCStoreServiceTest(
true,
HttpStatusCodes.STATUS_CODE_SERVER_ERROR,
Status.Success,
new MockDestinationConfig[] {
new MockDestinationConfig(TagUtils.toHexString(Tag.StudyDate) + "=19921012",
false, HttpStatusCodes.STATUS_CODE_OK)
});
}
@Test
public void testCStoreService_transcodeToJpeg2k() throws Exception {
basicCStoreServiceTest(
false,
HttpStatusCodes.STATUS_CODE_OK,
Status.Success,
null,
UID.SecondaryCaptureImageStorage,
"1.2.276.0.7230010.3.1.4.1784944219.230771.1519337370.699151",
TestUtils.TEST_IMG_FILE,
UID.JPEG2000);
}
@Override
public void stowRs(InputStream in) throws DicomWebException {
if (connectError) {
throw new DicomWebException("connect error");
}
if (httpResponseCode != HttpStatusCodes.STATUS_CODE_OK) {
throw new DicomWebException("mock error", httpResponseCode, Status.ProcessingFailure);
}
try {
in.readAllBytes();
} catch (IOException e) {
throw new DicomWebException(e);
}
}
private int httpStatusToDicomStatus(int httpStatus, int defaultStatus) {
switch (httpStatus) {
case HttpStatusCodes.STATUS_CODE_SERVICE_UNAVAILABLE:
return Status.OutOfResources;
case HttpStatusCodes.STATUS_CODE_UNAUTHORIZED:
return Status.NotAuthorized;
default:
return defaultStatus;
}
}