本文整理匯總了Java中com.google.api.client.googleapis.json.GoogleJsonResponseException類的典型用法代碼示例。如果您正苦於以下問題:Java GoogleJsonResponseException類的具體用法?Java GoogleJsonResponseException怎麽用?Java GoogleJsonResponseException使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
GoogleJsonResponseException類屬於com.google.api.client.googleapis.json包,在下文中一共展示了GoogleJsonResponseException類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: registerMetric_fetchesStackdriverDefinition
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
@Test
public void registerMetric_fetchesStackdriverDefinition() throws Exception {
// Stackdriver throws an Exception with the status message "ALREADY_EXISTS" when you try to
// register a metric that's already been registered, so we fake one here.
ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
HttpResponseException.Builder httpResponseExceptionBuilder =
new HttpResponseException.Builder(response);
httpResponseExceptionBuilder.setStatusCode(400);
httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
GoogleJsonResponseException exception =
new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
when(metricDescriptorCreate.execute()).thenThrow(exception);
StackdriverWriter writer =
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
writer.registerMetric(metric);
verify(client.projects().metricDescriptors().get("metric")).execute();
}
示例2: registerMetric_rethrowsException
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
@Test
public void registerMetric_rethrowsException() throws Exception {
ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
HttpResponseException.Builder httpResponseExceptionBuilder =
new HttpResponseException.Builder(response);
httpResponseExceptionBuilder.setStatusCode(404);
GoogleJsonResponseException exception =
new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
when(metricDescriptorCreate.execute()).thenThrow(exception);
StackdriverWriter writer =
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
assertThrows(GoogleJsonResponseException.class, () -> writer.registerMetric(metric));
assertThat(exception.getStatusCode()).isEqualTo(404);
}
示例3: getEncodedTimeSeries_nullLabels_encodes
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
@Test
public void getEncodedTimeSeries_nullLabels_encodes() throws Exception {
ByteArrayInputStream inputStream = new ByteArrayInputStream("".getBytes(UTF_8));
HttpResponse response = GoogleJsonResponseExceptionHelper.createHttpResponse(400, inputStream);
HttpResponseException.Builder httpResponseExceptionBuilder =
new HttpResponseException.Builder(response);
httpResponseExceptionBuilder.setStatusCode(400);
httpResponseExceptionBuilder.setStatusMessage("ALREADY_EXISTS");
GoogleJsonResponseException exception =
new GoogleJsonResponseException(httpResponseExceptionBuilder, null);
when(metricDescriptorCreate.execute()).thenThrow(exception);
when(metricDescriptorGet.execute())
.thenReturn(new MetricDescriptor().setName("foo").setLabels(null));
StackdriverWriter writer =
new StackdriverWriter(client, PROJECT, MONITORED_RESOURCE, MAX_QPS, MAX_POINTS_PER_REQUEST);
writer.registerMetric(metric);
TimeSeries timeSeries =
writer.getEncodedTimeSeries(
MetricPoint.create(metric, ImmutableList.of("foo"), Instant.ofEpochMilli(1337), 10L));
assertThat(timeSeries.getMetric().getLabels()).isEmpty();
}
示例4: convertException
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
private Exception convertException(Exception e) {
logDebug("Exception: " + e.toString());
e.printStackTrace();
if (UserRecoverableAuthIOException.class.isAssignableFrom(e.getClass()))
{
logDebug("clearing account data.");
//this is not really nice because it removes data from the cache which might still be valid but we don't have the account name here...
mAccountData.clear();
}
if (GoogleJsonResponseException.class.isAssignableFrom(e.getClass()) )
{
GoogleJsonResponseException jsonEx = (GoogleJsonResponseException)e;
if (jsonEx.getDetails().getCode() == 404)
return new FileNotFoundException(jsonEx.getMessage());
}
return e;
}
示例5: blobExists
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
/**
* Returns true if the blob exists in the bucket
*
* @param blobName name of the blob
* @return true if the blob exists, false otherwise
*/
boolean blobExists(String blobName) throws IOException {
try {
StorageObject blob = SocketAccess.doPrivilegedIOException(() -> client.objects().get(bucket, blobName).execute());
if (blob != null) {
return Strings.hasText(blob.getId());
}
} catch (GoogleJsonResponseException e) {
GoogleJsonError error = e.getDetails();
if ((e.getStatusCode() == HTTP_NOT_FOUND) || ((error != null) && (error.getCode() == HTTP_NOT_FOUND))) {
return false;
}
throw e;
}
return false;
}
示例6: map
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
@Override
public BackgroundException map(final IOException failure) {
final StringBuilder buffer = new StringBuilder();
if(failure instanceof GoogleJsonResponseException) {
final GoogleJsonResponseException error = (GoogleJsonResponseException) failure;
this.append(buffer, error.getDetails().getMessage());
switch(error.getDetails().getCode()) {
case HttpStatus.SC_FORBIDDEN:
final List<GoogleJsonError.ErrorInfo> errors = error.getDetails().getErrors();
for(GoogleJsonError.ErrorInfo info : errors) {
if("usageLimits".equals(info.getDomain())) {
return new RetriableAccessDeniedException(buffer.toString(), Duration.ofSeconds(5), failure);
}
}
break;
}
}
if(failure instanceof HttpResponseException) {
final HttpResponseException response = (HttpResponseException) failure;
this.append(buffer, response.getStatusMessage());
return new HttpResponseExceptionMappingService().map(new org.apache.http.client
.HttpResponseException(response.getStatusCode(), buffer.toString()));
}
return super.map(failure);
}
示例7: subscribeTopic
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
/**
* Sets up a subscription to projects/<code>appName</code>/subscriptions/<code>subName</code>.
* Ignores error if the subscription already exists.
* <p/>
* See <a href="https://cloud.google.com/pubsub/subscriber">cloud.google.com/pubsub/subscriber</a>
*/
Subscription subscribeTopic(String subscriptionName, String topicName) throws IOException {
String sub = getSubscription(subscriptionName);
Subscription subscription = new Subscription()
.setName(sub)
.setAckDeadlineSeconds(15)
.setTopic(getTopic(topicName));
try {
return pubsub.projects().subscriptions().create(sub, subscription).execute();
} catch (GoogleJsonResponseException e) {
if (e.getStatusCode() == HttpURLConnection.HTTP_CONFLICT) {
return subscription;
} else {
throw e;
}
}
}
示例8: GCSFilesSource
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
/**
* Constructor for GCSFileSource.
* @param bucket The bucket where the configuration files reside.
* @param repository The root directory where the files reside.
* @throws GeneralSecurityException Thrown if there's a permissions error using the GCS API.
* @throws IOException Thrown if there's a IO error using the GCS API.
*/
public GCSFilesSource(String bucket, String repository)
throws GeneralSecurityException, IOException {
this.bucket = bucket;
this.repository = repository;
try {
// test that the bucket actually exists.
getStorageApiStub().buckets().get(bucket).execute();
} catch (GoogleJsonResponseException gjre) {
String msgFormat = new StringBuilder()
.append("Can't access bucket \"gs://%s\".\n\n")
.append("1. Check that your appengine-web.xml has the correct environment variables.\n")
.append("2. Check your project IAM settings: the Compute Engine service account should\n")
.append(" have Editor access (or at least Storage Object Creator) if you're running\n")
.append(" on production. If you are running this locally, your user account or group\n")
.append(" should be granted Storage Object Creator.\n")
.append("3. Try re-authing your application-default credentials with this command:\n\n")
.append(" $ gcloud auth application-default login\n\n")
.append("More details:\n%s").toString();
String message = String.format(msgFormat, bucket, gjre.getContent());
throw new BucketAccessException(message);
}
}
示例9: testProjectWithIamErrorsCreatesSideOutput
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
@Test
public void testProjectWithIamErrorsCreatesSideOutput() throws IOException {
String projectSuffix = "project-with-error";
GCPProject project = getSampleProject(projectSuffix);
List<GCPProject> projects = new ArrayList<>(1);
projects.add(project);
when(this.getIamPolicy.execute()).thenThrow(GoogleJsonResponseException.class);
sideOutputTester.processBatch(projects);
List<GCPResourceErrorInfo> sideOutputs = sideOutputTester.takeSideOutputElements(errorTag);
List<GCPResourceErrorInfo> expected = new ArrayList<>();
expected.add(new GCPResourceErrorInfo(project, "Policy error null"));
Assert.assertEquals(expected, sideOutputs);
}
示例10: setUp
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
@Before
public void setUp() throws IOException, GeneralSecurityException {
when(this.objectList.setPageToken(anyString())).thenReturn(this.objectList);
when(this.objectList.setPageToken(null)).thenReturn(this.objectList);
when(this.objectList.setPrefix(anyString())).thenReturn(this.objectList);
when(this.objects.list(anyString())).thenReturn(this.objectList);
when(this.objects.get(anyString(), anyString())).thenReturn(this.objectGet);
when(this.gcs.objects()).thenReturn(this.objects);
when(this.buckets.get(BUCKET)).thenReturn(this.bucketGet);
when(this.gcs.buckets()).thenReturn(this.buckets);
GCSFilesSource.setStorageApiStub(gcs);
source = new GCSFilesSource(BUCKET, REPOSITORY);
when(this.buckets.get(FORBIDDEN_BUCKET)).thenThrow(GoogleJsonResponseException.class);
}
示例11: shouldHandleTooManyKeysCreated
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
@Test
public void shouldHandleTooManyKeysCreated() throws IOException {
when(serviceAccountKeyManager.serviceAccountExists(anyString())).thenReturn(true);
final GoogleJsonResponseException resourceExhausted = new GoogleJsonResponseException(
new HttpResponseException.Builder(429, "RESOURCE_EXHAUSTED", new HttpHeaders()),
new GoogleJsonError().set("status", "RESOURCE_EXHAUSTED"));
doThrow(resourceExhausted).when(serviceAccountKeyManager).createJsonKey(any());
doThrow(resourceExhausted).when(serviceAccountKeyManager).createP12Key(any());
exception.expect(InvalidExecutionException.class);
exception.expectMessage("Maximum number of keys on service account reached: " + SERVICE_ACCOUNT);
sut.ensureServiceAccountKeySecret(WORKFLOW_ID.toString(), SERVICE_ACCOUNT);
}
示例12: create_adminApiNotEnabled
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
@Test
public void create_adminApiNotEnabled() throws IOException {
ErrorInfo error = new ErrorInfo();
error.setReason(SslSocketFactory.ADMIN_API_NOT_ENABLED_REASON);
GoogleJsonError details = new GoogleJsonError();
details.setErrors(ImmutableList.of(error));
when(adminApiInstancesGet.execute())
.thenThrow(
new GoogleJsonResponseException(
new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()),
details));
SslSocketFactory sslSocketFactory =
new SslSocketFactory(new Clock(), clientKeyPair, credential, adminApi, 3307);
try {
sslSocketFactory.create(INSTANCE_CONNECTION_STRING);
fail("Expected RuntimeException");
} catch (RuntimeException e) {
// TODO(berezv): should we throw something more specific than RuntimeException?
assertThat(e.getMessage()).contains("Cloud SQL API is not enabled");
}
}
示例13: create_notAuthorizedToGetInstance
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
@Test
public void create_notAuthorizedToGetInstance() throws IOException {
ErrorInfo error = new ErrorInfo();
error.setReason(SslSocketFactory.INSTANCE_NOT_AUTHORIZED_REASON);
GoogleJsonError details = new GoogleJsonError();
details.setErrors(ImmutableList.of(error));
when(adminApiInstancesGet.execute())
.thenThrow(
new GoogleJsonResponseException(
new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()),
details));
SslSocketFactory sslSocketFactory =
new SslSocketFactory(new Clock(), clientKeyPair, credential, adminApi, 3307);
try {
sslSocketFactory.create(INSTANCE_CONNECTION_STRING);
fail("Expected RuntimeException");
} catch (RuntimeException e) {
// TODO(berezv): should we throw something more specific than RuntimeException?
assertThat(e.getMessage()).contains("not authorized");
}
}
示例14: create_notAuthorizedToCreateEphemeralCertificate
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
@Test
public void create_notAuthorizedToCreateEphemeralCertificate() throws IOException {
ErrorInfo error = new ErrorInfo();
error.setReason(SslSocketFactory.INSTANCE_NOT_AUTHORIZED_REASON);
GoogleJsonError details = new GoogleJsonError();
details.setErrors(ImmutableList.of(error));
when(adminApiSslCertsCreateEphemeral.execute())
.thenThrow(
new GoogleJsonResponseException(
new HttpResponseException.Builder(403, "Forbidden", new HttpHeaders()),
details));
SslSocketFactory sslSocketFactory =
new SslSocketFactory(new Clock(), clientKeyPair, credential, adminApi, 3307);
try {
sslSocketFactory.create(INSTANCE_CONNECTION_STRING);
fail();
} catch (RuntimeException e) {
// TODO(berezv): should we throw something more specific than RuntimeException?
assertThat(e.getMessage()).contains("Unable to obtain ephemeral certificate");
}
}
示例15: checkFilesNumber
import com.google.api.client.googleapis.json.GoogleJsonResponseException; //導入依賴的package包/類
/**
* Checks the files number on Google Drive
*
* @param drive a Google Drive object
* @throws IOException
*/
public static void checkFilesNumber(Drive drive) throws IOException {
EndToEndTestUtils.instrumentation.waitForIdleSync();
long startTime = System.currentTimeMillis();
int trackNumber = EndToEndTestUtils.SOLO.getCurrentViews(ListView.class).get(0).getCount();
List<File> files = getDriveFiles(EndToEndTestUtils.trackListActivity.getApplicationContext(),
drive);
while (System.currentTimeMillis() - startTime < MAX_TIME_TO_WAIT_SYNC) {
try {
if (files.size() == trackNumber) {
return;
}
trackNumber = EndToEndTestUtils.SOLO.getCurrentViews(ListView.class).get(0).getCount();
files = getDriveFiles(EndToEndTestUtils.trackListActivity.getApplicationContext(), drive);
EndToEndTestUtils.sleep(EndToEndTestUtils.SHORT_WAIT_TIME);
EndToEndTestUtils.findMenuItem(
EndToEndTestUtils.trackListActivity.getString(R.string.menu_sync_now), true);
} catch (GoogleJsonResponseException e) {
Log.e(TAG, e.getMessage(), e);
}
}
Assert.assertEquals(files.size(), trackNumber);
}