com.google.api.gax.rpc.ApiException Java Examples
The following examples show how to use
com.google.api.gax.rpc.ApiException.
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: GoogleCloudPubSubFlusherTest.java From divolte-collector with Apache License 2.0 | 6 votes |
@Test public void testMessagesAreAbandonedOnNonRetriableFailure() throws IOException { // Simulate a failure on send that indicates a retry isn't allowed. final Publisher publisher = mockPublisher.orElseThrow(IllegalStateException::new); when(publisher.publish(any(PubsubMessage.class))) .thenReturn(failedFuture(new ApiException("simulated permanent failure", new IOException(), GrpcStatusCode.of(Status.Code.NOT_FOUND), false))); // Here we send the message. processSingleMessage(); // Now we check the invocations… verify(publisher).publish(any(PubsubMessage.class)); verifyNoMoreInteractions(publisher); }
Example #2
Source File: GoogleCloudPubSubFlusherTest.java From divolte-collector with Apache License 2.0 | 6 votes |
@Test public void testMessagesAreRetriedOnRetriableFailure() throws IOException { // Simulate a failure on the first send that indicates a retry should succeed. final Publisher publisher = mockPublisher.orElseThrow(IllegalStateException::new); when(publisher.publish(any(PubsubMessage.class))) .thenReturn(failedFuture(new ApiException("simulated transient failure", new IOException(), GrpcStatusCode.of(Status.Code.INTERNAL), true))) .thenAnswer(invocationOnMock -> completedFuture(String.valueOf(messageIdCounter++))); // Here we send the message. processSingleMessage(); // Now we check the invocations… verify(publisher, times(2)).publish(any(PubsubMessage.class)); verifyNoMoreInteractions(publisher); }
Example #3
Source File: DataCatalogSchemaUtils.java From DataflowTemplates with Apache License 2.0 | 6 votes |
static Entry lookupPubSubEntry(DataCatalogClient client, String pubsubTopic, String gcpProject) { String linkedResource = String.format(DATA_CATALOG_PUBSUB_URI_TEMPLATE, gcpProject, pubsubTopic); LOG.info("Looking up LinkedResource {}", linkedResource); LookupEntryRequest request = LookupEntryRequest.newBuilder().setLinkedResource(linkedResource).build(); try { Entry entry = client.lookupEntry(request); return entry; } catch (ApiException e) { System.out.println("CANT LOOKUP ENTRY" + e.toString()); e.printStackTrace(); LOG.error("ApiException thrown by Data Catalog API:", e); return null; } }
Example #4
Source File: IntentManagement.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** Helper method for testing to get intentIds from displayName. */ public static List<String> getIntentIds(String displayName, String projectId) throws ApiException, IOException { List<String> intentIds = new ArrayList<>(); // Instantiates a client try (IntentsClient intentsClient = IntentsClient.create()) { AgentName parent = AgentName.of(projectId); for (Intent intent : intentsClient.listIntents(parent).iterateAll()) { if (intent.getDisplayName().equals(displayName)) { String[] splitName = intent.getName().split("/"); intentIds.add(splitName[splitName.length - 1]); } } } return intentIds; }
Example #5
Source File: BaseGoogleAdsException.java From google-ads-java with Apache License 2.0 | 6 votes |
public Optional<T> createGoogleAdsException(ApiException source) { if (source == null) { return Optional.empty(); } Throwable cause = source.getCause(); if (cause == null) { return Optional.empty(); } Metadata metadata = Status.trailersFromThrowable(cause); if (metadata == null) { return Optional.empty(); } byte[] protoData = metadata.get(getTrailerKey()); if (protoData == null) { return Optional.empty(); } try { return Optional.of(createException(source, protoData, metadata)); } catch (InvalidProtocolBufferException e) { logger.error("Failed to decode GoogleAdsFailure", e); return Optional.empty(); } }
Example #6
Source File: PubSubAdmin.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
/** * Get the configuration of a Google Cloud Pub/Sub subscription. * * @param subscriptionName canonical subscription name, e.g., "subscriptionName", or the fully-qualified * subscription name in the {@code projects/<project_name>/subscriptions/<subscription_name>} format * @return subscription configuration or {@code null} if subscription doesn't exist */ public Subscription getSubscription(String subscriptionName) { Assert.hasText(subscriptionName, "No subscription name was specified"); try { return this.subscriptionAdminClient.getSubscription( PubSubSubscriptionUtils.toProjectSubscriptionName(subscriptionName, this.projectId)); } catch (ApiException aex) { if (aex.getStatusCode().getCode() == StatusCode.Code.NOT_FOUND) { return null; } throw aex; } }
Example #7
Source File: PubSubHealthIndicator.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Override protected void doHealthCheck(Health.Builder builder) throws Exception { try { this.pubSubTemplate.pull("subscription-" + UUID.randomUUID().toString(), 1, true); } catch (ApiException aex) { Code errorCode = aex.getStatusCode().getCode(); if (errorCode == StatusCode.Code.NOT_FOUND || errorCode == Code.PERMISSION_DENIED) { builder.up(); } else { builder.withException(aex).down(); } } catch (Exception e) { builder.withException(e).down(); } }
Example #8
Source File: ApiCatalogTest.java From google-ads-java with Apache License 2.0 | 6 votes |
/** * Ensure that all versions decode a GoogleAdsException when the metadata contains * GoogleAdsFailure. */ @Test public void createGoogleAdsException_fromMetadata() { for (Version version : catalog.getSupportedVersions()) { Message expectedFailure = version.getExceptionFactory().createGoogleAdsFailure(); ApiException exception = getApiExceptionForVersion( version.getExceptionFactory().getTrailerKey(), expectedFailure.toByteArray()); Optional<? extends BaseGoogleAdsException> result = version.getExceptionFactory().createGoogleAdsException(exception); assertTrue("Missing GoogleAdsException from invalid data", result.isPresent()); assertEquals( "Cause not equal to original exception", exception.getCause(), result.get().getCause()); assertEquals( "GoogleAdsFailure present but not equal", expectedFailure, result.get().getGoogleAdsFailure()); } }
Example #9
Source File: GoogleAdsExceptionTransformationTest.java From google-ads-java with Apache License 2.0 | 5 votes |
@Test public void failsGracefullyWithUnparsableFailureProto() { for (Version version : catalog.getSupportedVersions()) { ApiException exception = getApiExceptionForVersion( version.getExceptionFactory().getTrailerKey(), new byte[] {0, 1, 2, 3}); Throwable result = transformation.transform(exception); assertEquals(exception, result); } }
Example #10
Source File: GoogleAdsClientTest.java From google-ads-java with Apache License 2.0 | 5 votes |
/** * Verifies that the exception transformation behaviour is working for a test example. */ @Test public void exceptionTransformedToGoogleAdsException() { GoogleAdsClient client = GoogleAdsClient.newBuilder() .setCredentials(fakeCredentials) .setDeveloperToken(DEVELOPER_TOKEN) .setTransportChannelProvider(localChannelProvider) .setEnableGeneratedCatalog(enabledGeneratedCatalog) .build(); Metadata.Key trailerKey = ApiCatalog .getDefault(enabledGeneratedCatalog) .getLatestVersion() .getExceptionFactory() .getTrailerKey(); Metadata trailers = new Metadata(); GoogleAdsFailure.Builder failure = GoogleAdsFailure.newBuilder(); failure.addErrors(GoogleAdsError.newBuilder().setMessage("Test error message")); trailers.put(trailerKey, failure.build().toByteArray()); StatusException rootCause = new StatusException(Status.UNKNOWN, trailers); mockService.addException(new ApiException(rootCause, GrpcStatusCode.of(Code.UNKNOWN), false)); try (GoogleAdsServiceClient googleAdsServiceClient = client.getLatestVersion().createGoogleAdsServiceClient()) { googleAdsServiceClient.search("123", "select blah"); } catch (GoogleAdsException ex) { // Expected } }
Example #11
Source File: GoogleAdsExceptionTransformationTest.java From google-ads-java with Apache License 2.0 | 5 votes |
private static ApiException getApiExceptionForVersion( Metadata.Key<byte[]> failureKey, byte[] data) { Metadata trailers = new Metadata(); if (data != null) { trailers.put(failureKey, data); } return new ApiException( new StatusException(Status.UNKNOWN, trailers), GrpcStatusCode.of(Code.UNKNOWN), false); }
Example #12
Source File: PhotosLibraryUploadExceptionMappingFn.java From java-photoslibrary with Apache License 2.0 | 5 votes |
@Nullable @Override public UploadMediaItemResponse apply(@Nullable Throwable input) { Optional<String> resumeUrl = Optional.ofNullable(atomicResumeUrl.get()); return UploadMediaItemResponse.newBuilder() .setError( UploadMediaItemResponse.Error.newBuilder() .setResumeUrl(resumeUrl) .setCause( new ApiException( input, getStatusCode(input), resumeUrl.isPresent() /* retryable */)) .build()) .build(); }
Example #13
Source File: StackdriverMeterRegistry.java From micrometer with Apache License 2.0 | 5 votes |
private void createMetricDescriptorIfNecessary(MetricServiceClient client, Meter.Id id, MetricDescriptor.ValueType valueType, @Nullable String statistic) { if (verifiedDescriptors.isEmpty()) { prePopulateVerifiedDescriptors(); } final String metricType = metricType(id, statistic); if (!verifiedDescriptors.contains(metricType)) { MetricDescriptor descriptor = MetricDescriptor.newBuilder() .setType(metricType) .setDescription(id.getDescription() == null ? "" : id.getDescription()) .setMetricKind(MetricDescriptor.MetricKind.GAUGE) .setValueType(valueType) .build(); ProjectName name = ProjectName.of(config.projectId()); CreateMetricDescriptorRequest request = CreateMetricDescriptorRequest.newBuilder() .setName(name.toString()) .setMetricDescriptor(descriptor) .build(); logger.trace("creating metric descriptor:{}{}", System.lineSeparator(), request); try { client.createMetricDescriptor(request); verifiedDescriptors.add(metricType); } catch (ApiException e) { logger.warn("failed to create metric descriptor in Stackdriver for meter " + id, e); } } }
Example #14
Source File: PubSubAdmin.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
/** * Get the configuration of a Google Cloud Pub/Sub topic. * * @param topicName canonical topic name, e.g., "topicName", or the fully-qualified topic name in the * {@code projects/<project_name>/topics/<topic_name>} format * @return topic configuration or {@code null} if topic doesn't exist */ public Topic getTopic(String topicName) { Assert.hasText(topicName, "No topic name was specified."); try { return this.topicAdminClient.getTopic(PubSubTopicUtils.toProjectTopicName(topicName, this.projectId)); } catch (ApiException aex) { if (aex.getStatusCode().getCode() == StatusCode.Code.NOT_FOUND) { return null; } throw aex; } }
Example #15
Source File: PubSubHealthIndicatorTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void healthUpFor404() throws Exception { when(pubSubTemplate.pull(anyString(), anyInt(), anyBoolean())).thenThrow(new ApiException( new IllegalStateException("Illegal State"), GrpcStatusCode.of(io.grpc.Status.Code.NOT_FOUND), false)); PubSubHealthIndicator healthIndicator = new PubSubHealthIndicator(pubSubTemplate); assertThat(healthIndicator.health().getStatus()).isEqualTo(Status.UP); }
Example #16
Source File: PubSubHealthIndicatorTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void healthUpFor403() throws Exception { when(pubSubTemplate.pull(anyString(), anyInt(), anyBoolean())).thenThrow(new ApiException( new IllegalStateException("Illegal State"), GrpcStatusCode.of(Code.PERMISSION_DENIED), false)); PubSubHealthIndicator healthIndicator = new PubSubHealthIndicator(pubSubTemplate); assertThat(healthIndicator.health().getStatus()).isEqualTo(Status.UP); }
Example #17
Source File: PubSubHealthIndicatorTests.java From spring-cloud-gcp with Apache License 2.0 | 5 votes |
@Test public void healthDown() { when(pubSubTemplate.pull(anyString(), anyInt(), anyBoolean())) .thenThrow(new ApiException(new IllegalStateException("Illegal State"), GrpcStatusCode.of(io.grpc.Status.Code.INVALID_ARGUMENT), false)); PubSubHealthIndicator healthIndicator = new PubSubHealthIndicator(pubSubTemplate); assertThat(healthIndicator.health().getStatus()).isEqualTo(Status.DOWN); }
Example #18
Source File: IntentManagement.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** * List intents * * @param projectId Project/Agent Id. * @return Intents found. */ public static List<Intent> listIntents(String projectId) throws ApiException, IOException { List<Intent> intents = Lists.newArrayList(); // Instantiates a client try (IntentsClient intentsClient = IntentsClient.create()) { // Set the project agent name using the projectID (my-project-id) AgentName parent = AgentName.of(projectId); // Performs the list intents request for (Intent intent : intentsClient.listIntents(parent).iterateAll()) { System.out.println("===================="); System.out.format("Intent name: '%s'\n", intent.getName()); System.out.format("Intent display name: '%s'\n", intent.getDisplayName()); System.out.format("Action: '%s'\n", intent.getAction()); System.out.format("Root followup intent: '%s'\n", intent.getRootFollowupIntentName()); System.out.format("Parent followup intent: '%s'\n", intent.getParentFollowupIntentName()); System.out.format("Input contexts:\n"); for (String inputContextName : intent.getInputContextNamesList()) { System.out.format("\tName: %s\n", inputContextName); } System.out.format("Output contexts:\n"); for (Context outputContext : intent.getOutputContextsList()) { System.out.format("\tName: %s\n", outputContext.getName()); } intents.add(intent); } } return intents; }
Example #19
Source File: IntentManagement.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** * Create an intent of the given intent type * * @param displayName The display name of the intent. * @param projectId Project/Agent Id. * @param trainingPhrasesParts Training phrases. * @param messageTexts Message texts for the agent's response when the intent is detected. * @return The created Intent. */ public static Intent createIntent( String displayName, String projectId, List<String> trainingPhrasesParts, List<String> messageTexts) throws ApiException, IOException { // Instantiates a client try (IntentsClient intentsClient = IntentsClient.create()) { // Set the project agent name using the projectID (my-project-id) AgentName parent = AgentName.of(projectId); // Build the trainingPhrases from the trainingPhrasesParts List<TrainingPhrase> trainingPhrases = new ArrayList<>(); for (String trainingPhrase : trainingPhrasesParts) { trainingPhrases.add( TrainingPhrase.newBuilder() .addParts(Part.newBuilder().setText(trainingPhrase).build()) .build()); } // Build the message texts for the agent's response Message message = Message.newBuilder().setText(Text.newBuilder().addAllText(messageTexts).build()).build(); // Build the intent Intent intent = Intent.newBuilder() .setDisplayName(displayName) .addMessages(message) .addAllTrainingPhrases(trainingPhrases) .build(); // Performs the create intent request Intent response = intentsClient.createIntent(parent, intent); System.out.format("Intent created: %s\n", response); return response; } }
Example #20
Source File: IntentManagement.java From java-docs-samples with Apache License 2.0 | 5 votes |
/** * Delete intent with the given intent type and intent value * * @param intentId The id of the intent. * @param projectId Project/Agent Id. */ public static void deleteIntent(String intentId, String projectId) throws ApiException, IOException { // Instantiates a client try (IntentsClient intentsClient = IntentsClient.create()) { IntentName name = IntentName.of(projectId, intentId); // Performs the delete intent request intentsClient.deleteIntent(name); } }
Example #21
Source File: KnowledgeBaseManagement.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static KnowledgeBase createKnowledgeBase(String projectId, String displayName) throws ApiException, IOException { // Instantiates a client try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { KnowledgeBase knowledgeBase = KnowledgeBase.newBuilder().setDisplayName(displayName).build(); ProjectName projectName = ProjectName.of(projectId); KnowledgeBase response = knowledgeBasesClient.createKnowledgeBase(projectName, knowledgeBase); System.out.format("Knowledgebase created:\n"); System.out.format("Display Name: %s \n", response.getDisplayName()); System.out.format("Knowledge ID: %s \n", response.getName()); return response; } }
Example #22
Source File: DetectIntentTexts.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static Map<String, QueryResult> detectIntentTexts( String projectId, List<String> texts, String sessionId, String languageCode) throws IOException, ApiException { Map<String, QueryResult> queryResults = Maps.newHashMap(); // Instantiates a client try (SessionsClient sessionsClient = SessionsClient.create()) { // Set the session name using the sessionId (UUID) and projectID (my-project-id) SessionName session = SessionName.of(projectId, sessionId); System.out.println("Session Path: " + session.toString()); // Detect intents for each text input for (String text : texts) { // Set the text (hello) and language code (en-US) for the query TextInput.Builder textInput = TextInput.newBuilder().setText(text).setLanguageCode(languageCode); // Build the query with the TextInput QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build(); // Performs the detect intent request DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput); // Display the query result QueryResult queryResult = response.getQueryResult(); System.out.println("===================="); System.out.format("Query Text: '%s'\n", queryResult.getQueryText()); System.out.format( "Detected Intent: %s (confidence: %f)\n", queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence()); System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText()); queryResults.put(text, queryResult); } } return queryResults; }
Example #23
Source File: DocumentManagement.java From java-docs-samples with Apache License 2.0 | 5 votes |
public static Document createDocument( String knowledgeBaseName, String displayName, String mimeType, String knowledgeType, String contentUri) throws IOException, ApiException, InterruptedException, ExecutionException, TimeoutException { // Instantiates a client try (DocumentsClient documentsClient = DocumentsClient.create()) { Document document = Document.newBuilder() .setDisplayName(displayName) .setContentUri(contentUri) .setMimeType(mimeType) .addKnowledgeTypes(KnowledgeType.valueOf(knowledgeType)) .build(); CreateDocumentRequest createDocumentRequest = CreateDocumentRequest.newBuilder() .setDocument(document) .setParent(knowledgeBaseName) .build(); OperationFuture<Document, KnowledgeOperationMetadata> response = documentsClient.createDocumentAsync(createDocumentRequest); Document createdDocument = response.get(180, TimeUnit.SECONDS); System.out.format("Created Document:\n"); System.out.format(" - Display Name: %s\n", createdDocument.getDisplayName()); System.out.format(" - Knowledge ID: %s\n", createdDocument.getName()); System.out.format(" - MIME Type: %s\n", createdDocument.getMimeType()); System.out.format(" - Knowledge Types:\n"); for (KnowledgeType knowledgeTypeId : document.getKnowledgeTypesList()) { System.out.format(" - %s \n", knowledgeTypeId.getValueDescriptor()); } System.out.format(" - Source: %s \n", document.getContentUri()); return createdDocument; } }
Example #24
Source File: ApiCatalogTest.java From google-ads-java with Apache License 2.0 | 5 votes |
/** Ensure that all versions return Optional.empty() when the trailing metadata is not present. */ @Test public void createGoogleAdsException_fromNullMetadata() { for (Version version : catalog.getSupportedVersions()) { ApiException exception = new ApiException( new StatusException(Status.UNKNOWN, null), GrpcStatusCode.of(Code.UNKNOWN), false); Optional<? extends BaseGoogleAdsException> result = version.getExceptionFactory().createGoogleAdsException(exception); assertFalse("Null metadata produced result", result.isPresent()); } }
Example #25
Source File: GoogleAdsException.java From google-ads-java with Apache License 2.0 | 5 votes |
@Override protected GoogleAdsException createException( ApiException source, byte[] protoData, Metadata metadata) throws InvalidProtocolBufferException { GoogleAdsFailure failure = createGoogleAdsFailure(protoData); return new GoogleAdsException(source, failure, metadata); }
Example #26
Source File: ExceptionTransformingCallable.java From google-ads-java with Apache License 2.0 | 5 votes |
@Override public void onFailure(Throwable throwable) { if (throwable instanceof CancellationException && cancelled) { // this just circled around, so ignore. } else if (throwable instanceof ApiException) { setException(transformation.transform((ApiException) throwable)); } }
Example #27
Source File: BaseGoogleAdsException.java From google-ads-java with Apache License 2.0 | 5 votes |
/** Create from ApiException, GoogleAdsFailure (as Message) and metadata. */ public <T extends Message> BaseGoogleAdsException( ApiException original, T failure, Metadata metadata) { super( failure.toString(), original.getCause(), original.getStatusCode(), original.isRetryable()); this.metadata = metadata; this.failure = failure; }
Example #28
Source File: GoogleAdsExceptionTransformation.java From google-ads-java with Apache License 2.0 | 5 votes |
@Override public Throwable transform(ApiException apiException) { for (Version version : catalog.getSupportedVersions()) { Optional<? extends BaseGoogleAdsException> result = version.getExceptionFactory().createGoogleAdsException(apiException); if (result.isPresent()) { return result.get(); } } return apiException; }
Example #29
Source File: ApiCatalogTest.java From google-ads-java with Apache License 2.0 | 5 votes |
/** * Ensure that all versions throw a creation exception when the metadata is present but invalid. */ @Test public void createGoogleAdsException_fromInvalidData() { for (Version version : catalog.getSupportedVersions()) { ApiException exception = getApiExceptionForVersion( version.getExceptionFactory().getTrailerKey(), new byte[] {1, 2, 3}); Optional<? extends BaseGoogleAdsException> result = version.getExceptionFactory().createGoogleAdsException(exception); assertFalse("Invalid data produced result", result.isPresent()); } }
Example #30
Source File: ApiCatalogTest.java From google-ads-java with Apache License 2.0 | 5 votes |
/** * Ensure that all versions return Optional.empty() when the ApiException doesn't have a cause. */ @Test public void createGoogleAdsException_fromNullCause() { for (Version version : catalog.getSupportedVersions()) { ApiException exception = new ApiException(null, GrpcStatusCode.of(Code.UNKNOWN), false); Optional<? extends BaseGoogleAdsException> result = version.getExceptionFactory().createGoogleAdsException(exception); assertFalse("Null cause produced result", result.isPresent()); } }