当前位置: 首页>>代码示例>>Java>>正文


Java GoogleJsonResponseException类代码示例

本文整理汇总了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();
}
 
开发者ID:google,项目名称:java-monitoring-client-library,代码行数:21,代码来源:StackdriverWriterTest.java

示例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);
}
 
开发者ID:google,项目名称:java-monitoring-client-library,代码行数:17,代码来源:StackdriverWriterTest.java

示例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();
}
 
开发者ID:google,项目名称:java-monitoring-client-library,代码行数:24,代码来源:StackdriverWriterTest.java

示例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;
	
}
 
开发者ID:PhilippC,项目名称:keepass2android,代码行数:20,代码来源:GoogleDriveFileStorage.java

示例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;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:22,代码来源:GoogleCloudStorageBlobStore.java

示例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);
}
 
开发者ID:iterate-ch,项目名称:cyberduck,代码行数:26,代码来源:DriveExceptionMappingService.java

示例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;
        }
    }
}
 
开发者ID:spac3lord,项目名称:eip,代码行数:23,代码来源:PubSubWrapper.java

示例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);
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:policyscanner,代码行数:31,代码来源:GCSFilesSource.java

示例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);
}
 
开发者ID:GoogleCloudPlatform,项目名称:policyscanner,代码行数:17,代码来源:ExtractStateTest.java

示例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);
}
 
开发者ID:GoogleCloudPlatform,项目名称:policyscanner,代码行数:19,代码来源:GCSFilesSourceTest.java

示例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);
}
 
开发者ID:spotify,项目名称:styx,代码行数:17,代码来源:KubernetesGCPServiceAccountSecretManagerTest.java

示例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");
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-sql-jdbc-socket-factory,代码行数:23,代码来源:SslSocketFactoryTest.java

示例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");
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-sql-jdbc-socket-factory,代码行数:23,代码来源:SslSocketFactoryTest.java

示例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");
  }
}
 
开发者ID:GoogleCloudPlatform,项目名称:cloud-sql-jdbc-socket-factory,代码行数:23,代码来源:SslSocketFactoryTest.java

示例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);
}
 
开发者ID:Plonk42,项目名称:mytracks,代码行数:29,代码来源:SyncTestUtils.java


注:本文中的com.google.api.client.googleapis.json.GoogleJsonResponseException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。