com.google.api.core.ApiFutures Java Examples

The following examples show how to use com.google.api.core.ApiFutures. 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: GooglePubsub.java    From metastore with Apache License 2.0 7 votes vote down vote up
@Override
public void descriptorsChanged(Report report) {
  try (Scope scope =
      TRACER
          .spanBuilder("GooglePubsub.descriptorsChanged")
          .setRecordEvents(true)
          .startScopedSpan()) {
    PubsubMessage message = PubsubMessage.newBuilder().setData(report.toByteString()).build();
    ApiFuture<String> future = publisherDescriptorChange.publish(message);
    ApiFutures.addCallback(
        future,
        new ApiFutureCallback<String>() {
          @Override
          public void onFailure(Throwable t) {
            LOG.error("Error publishing changes to Pubsub", t);
          }

          @Override
          public void onSuccess(String messageId) {
            LOG.debug("Published changes to Pubsub");
          }
        },
        MoreExecutors.directExecutor());
  }
}
 
Example #2
Source File: FuturesConverter.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
/** Converts an {@see ApiFuture} to a {@see ListenableFuture}. */
public static <T> ListenableFuture<T> apiFutureToListenableFuture(final ApiFuture<T> apiFuture) {
  SettableFuture<T> settableFuture = SettableFuture.create();
  ApiFutures.addCallback(
      apiFuture,
      new ApiFutureCallback<T>() {
        @Override
        public void onFailure(Throwable t) {
          settableFuture.setException(t);
        }

        @Override
        public void onSuccess(T result) {
          settableFuture.set(result);
        }
      });
  return settableFuture;
}
 
Example #3
Source File: PubSubSubscriberTemplate.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
/**
 * Pulls messages asynchronously, on demand, using the pull request in argument.
 *
 * @param pullRequest pull request containing the subscription name
 * @return the ListenableFuture for the asynchronous execution, returning
 * the list of {@link AcknowledgeablePubsubMessage} containing the ack ID, subscription
 * and acknowledger
 */
private ListenableFuture<List<AcknowledgeablePubsubMessage>> pullAsync(PullRequest pullRequest) {
	Assert.notNull(pullRequest, "The pull request can't be null.");

	ApiFuture<PullResponse> pullFuture = this.subscriberStub.pullCallable().futureCall(pullRequest);

	final SettableListenableFuture<List<AcknowledgeablePubsubMessage>> settableFuture = new SettableListenableFuture<>();
	ApiFutures.addCallback(pullFuture, new ApiFutureCallback<PullResponse>() {

		@Override
		public void onFailure(Throwable throwable) {
			settableFuture.setException(throwable);
		}

		@Override
		public void onSuccess(PullResponse pullResponse) {
			List<AcknowledgeablePubsubMessage> result = toAcknowledgeablePubsubMessageList(
					pullResponse.getReceivedMessagesList(), pullRequest.getSubscription());

			settableFuture.set(result);
		}

	}, asyncPullExecutor);

	return settableFuture;
}
 
Example #4
Source File: CPSPublisherTask.java    From pubsub with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Void> publish(
    int clientId, int sequenceNumber, long publishTimestampMillis) {
  SettableFuture<Void> done = SettableFuture.create();
  ApiFutures.addCallback(
      publisher.publish(
          PubsubMessage.newBuilder()
              .setData(payload)
              .putAttributes("sendTime", Long.toString(publishTimestampMillis))
              .putAttributes("clientId", Integer.toString(clientId))
              .putAttributes("sequenceNumber", Integer.toString(sequenceNumber))
              .build()),
      new ApiFutureCallback<String>() {
        @Override
        public void onSuccess(String messageId) {
          done.set(null);
        }

        @Override
        public void onFailure(Throwable t) {
          done.setException(t);
        }
      },
      MoreExecutors.directExecutor());
  return done;
}
 
Example #5
Source File: PubsubPluginSink.java    From ffwd with Apache License 2.0 6 votes vote down vote up
private void publishPubSub(final ByteString bytes) {
  // don't publish "\000" - indicates all the metrics are in the writeCache
  if (bytes.size() <= 1) {
    return;
  }

  final ApiFuture<String> publish =
      publisher.publish(PubsubMessage.newBuilder().setData(bytes).build());


  ApiFutures.addCallback(publish, new ApiFutureCallback<String>() {
    @Override
    public void onFailure(Throwable t) {
      logger.error("Failed sending metrics {}", t.getMessage());
    }

    @Override
    public void onSuccess(String messageId) { }

  }, executorService);
}
 
Example #6
Source File: RetrieveDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Create cities collection and add sample documents. */
void prepareExamples() throws Exception {
  // [START fs_retrieve_create_examples]
  CollectionReference cities = db.collection("cities");
  List<ApiFuture<WriteResult>> futures = new ArrayList<>();
  futures.add(cities.document("SF").set(new City("San Francisco", "CA", "USA", false, 860000L,
      Arrays.asList("west_coast", "norcal"))));
  futures.add(cities.document("LA").set(new City("Los Angeles", "CA", "USA", false, 3900000L,
      Arrays.asList("west_coast", "socal"))));
  futures.add(cities.document("DC").set(new City("Washington D.C.", null, "USA", true, 680000L,
      Arrays.asList("east_coast"))));
  futures.add(cities.document("TOK").set(new City("Tokyo", null, "Japan", true, 9000000L,
      Arrays.asList("kanto", "honshu"))));
  futures.add(cities.document("BJ").set(new City("Beijing", null, "China", true, 21500000L,
      Arrays.asList("jingjinji", "hebei"))));
  // (optional) block on operation
  ApiFutures.allAsList(futures).get();
  // [END fs_retrieve_create_examples]
}
 
Example #7
Source File: ApiCommonConvertedFutureTestHelper.java    From future-converter with Apache License 2.0 6 votes vote down vote up
@Override
public void waitForCalculationToFinish(ApiFuture<String> convertedFuture) throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(1);

    ApiFutures.addCallback(convertedFuture, new ApiFutureCallback<String>() {
        @Override
        public void onSuccess(String result) {
            latch.countDown();
        }

        @Override
        public void onFailure(Throwable t) {
            latch.countDown();
        }
    }, MoreExecutors.directExecutor());

    latch.await(1, TimeUnit.SECONDS);
}
 
Example #8
Source File: MutateJobServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<ListMutateJobResultsPagedResponse> createAsync(
    PageContext<ListMutateJobResultsRequest, ListMutateJobResultsResponse, MutateJobResult>
        context,
    ApiFuture<ListMutateJobResultsResponse> futureResponse) {
  ApiFuture<ListMutateJobResultsPage> futurePage =
      ListMutateJobResultsPage.createEmptyPage().createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<ListMutateJobResultsPage, ListMutateJobResultsPagedResponse>() {
        @Override
        public ListMutateJobResultsPagedResponse apply(ListMutateJobResultsPage input) {
          return new ListMutateJobResultsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #9
Source File: CampaignExperimentServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<ListCampaignExperimentAsyncErrorsPagedResponse> createAsync(
    PageContext<
            ListCampaignExperimentAsyncErrorsRequest, ListCampaignExperimentAsyncErrorsResponse,
            Status>
        context,
    ApiFuture<ListCampaignExperimentAsyncErrorsResponse> futureResponse) {
  ApiFuture<ListCampaignExperimentAsyncErrorsPage> futurePage =
      ListCampaignExperimentAsyncErrorsPage.createEmptyPage()
          .createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<
          ListCampaignExperimentAsyncErrorsPage,
          ListCampaignExperimentAsyncErrorsPagedResponse>() {
        @Override
        public ListCampaignExperimentAsyncErrorsPagedResponse apply(
            ListCampaignExperimentAsyncErrorsPage input) {
          return new ListCampaignExperimentAsyncErrorsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #10
Source File: GoogleAdsFieldServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<SearchGoogleAdsFieldsPagedResponse> createAsync(
    PageContext<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse, GoogleAdsField>
        context,
    ApiFuture<SearchGoogleAdsFieldsResponse> futureResponse) {
  ApiFuture<SearchGoogleAdsFieldsPage> futurePage =
      SearchGoogleAdsFieldsPage.createEmptyPage().createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<SearchGoogleAdsFieldsPage, SearchGoogleAdsFieldsPagedResponse>() {
        @Override
        public SearchGoogleAdsFieldsPagedResponse apply(SearchGoogleAdsFieldsPage input) {
          return new SearchGoogleAdsFieldsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #11
Source File: CampaignDraftServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<ListCampaignDraftAsyncErrorsPagedResponse> createAsync(
    PageContext<
            ListCampaignDraftAsyncErrorsRequest, ListCampaignDraftAsyncErrorsResponse, Status>
        context,
    ApiFuture<ListCampaignDraftAsyncErrorsResponse> futureResponse) {
  ApiFuture<ListCampaignDraftAsyncErrorsPage> futurePage =
      ListCampaignDraftAsyncErrorsPage.createEmptyPage()
          .createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<
          ListCampaignDraftAsyncErrorsPage, ListCampaignDraftAsyncErrorsPagedResponse>() {
        @Override
        public ListCampaignDraftAsyncErrorsPagedResponse apply(
            ListCampaignDraftAsyncErrorsPage input) {
          return new ListCampaignDraftAsyncErrorsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #12
Source File: MutateJobServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<ListMutateJobResultsPagedResponse> createAsync(
    PageContext<ListMutateJobResultsRequest, ListMutateJobResultsResponse, MutateJobResult>
        context,
    ApiFuture<ListMutateJobResultsResponse> futureResponse) {
  ApiFuture<ListMutateJobResultsPage> futurePage =
      ListMutateJobResultsPage.createEmptyPage().createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<ListMutateJobResultsPage, ListMutateJobResultsPagedResponse>() {
        @Override
        public ListMutateJobResultsPagedResponse apply(ListMutateJobResultsPage input) {
          return new ListMutateJobResultsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #13
Source File: CampaignExperimentServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<ListCampaignExperimentAsyncErrorsPagedResponse> createAsync(
    PageContext<
            ListCampaignExperimentAsyncErrorsRequest, ListCampaignExperimentAsyncErrorsResponse,
            Status>
        context,
    ApiFuture<ListCampaignExperimentAsyncErrorsResponse> futureResponse) {
  ApiFuture<ListCampaignExperimentAsyncErrorsPage> futurePage =
      ListCampaignExperimentAsyncErrorsPage.createEmptyPage()
          .createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<
          ListCampaignExperimentAsyncErrorsPage,
          ListCampaignExperimentAsyncErrorsPagedResponse>() {
        @Override
        public ListCampaignExperimentAsyncErrorsPagedResponse apply(
            ListCampaignExperimentAsyncErrorsPage input) {
          return new ListCampaignExperimentAsyncErrorsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #14
Source File: GoogleAdsFieldServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<SearchGoogleAdsFieldsPagedResponse> createAsync(
    PageContext<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse, GoogleAdsField>
        context,
    ApiFuture<SearchGoogleAdsFieldsResponse> futureResponse) {
  ApiFuture<SearchGoogleAdsFieldsPage> futurePage =
      SearchGoogleAdsFieldsPage.createEmptyPage().createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<SearchGoogleAdsFieldsPage, SearchGoogleAdsFieldsPagedResponse>() {
        @Override
        public SearchGoogleAdsFieldsPagedResponse apply(SearchGoogleAdsFieldsPage input) {
          return new SearchGoogleAdsFieldsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #15
Source File: CampaignDraftServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<ListCampaignDraftAsyncErrorsPagedResponse> createAsync(
    PageContext<
            ListCampaignDraftAsyncErrorsRequest, ListCampaignDraftAsyncErrorsResponse, Status>
        context,
    ApiFuture<ListCampaignDraftAsyncErrorsResponse> futureResponse) {
  ApiFuture<ListCampaignDraftAsyncErrorsPage> futurePage =
      ListCampaignDraftAsyncErrorsPage.createEmptyPage()
          .createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<
          ListCampaignDraftAsyncErrorsPage, ListCampaignDraftAsyncErrorsPagedResponse>() {
        @Override
        public ListCampaignDraftAsyncErrorsPagedResponse apply(
            ListCampaignDraftAsyncErrorsPage input) {
          return new ListCampaignDraftAsyncErrorsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #16
Source File: MutateJobServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<ListMutateJobResultsPagedResponse> createAsync(
    PageContext<ListMutateJobResultsRequest, ListMutateJobResultsResponse, MutateJobResult>
        context,
    ApiFuture<ListMutateJobResultsResponse> futureResponse) {
  ApiFuture<ListMutateJobResultsPage> futurePage =
      ListMutateJobResultsPage.createEmptyPage().createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<ListMutateJobResultsPage, ListMutateJobResultsPagedResponse>() {
        @Override
        public ListMutateJobResultsPagedResponse apply(ListMutateJobResultsPage input) {
          return new ListMutateJobResultsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #17
Source File: CampaignExperimentServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<ListCampaignExperimentAsyncErrorsPagedResponse> createAsync(
    PageContext<
            ListCampaignExperimentAsyncErrorsRequest, ListCampaignExperimentAsyncErrorsResponse,
            Status>
        context,
    ApiFuture<ListCampaignExperimentAsyncErrorsResponse> futureResponse) {
  ApiFuture<ListCampaignExperimentAsyncErrorsPage> futurePage =
      ListCampaignExperimentAsyncErrorsPage.createEmptyPage()
          .createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<
          ListCampaignExperimentAsyncErrorsPage,
          ListCampaignExperimentAsyncErrorsPagedResponse>() {
        @Override
        public ListCampaignExperimentAsyncErrorsPagedResponse apply(
            ListCampaignExperimentAsyncErrorsPage input) {
          return new ListCampaignExperimentAsyncErrorsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #18
Source File: Demo.java    From kafka-pubsub-emulator with Apache License 2.0 6 votes vote down vote up
private void publish(String topic) throws IOException, InterruptedException {
  System.out.println("Publishing messages to " + topic + "...Press Ctrl-C to exit");
  Publisher publisher = Publisher.newBuilder(topic)
      .setCredentialsProvider(new NoCredentialsProvider())
      .setChannelProvider(getChannelProvider())
      .build();
  int messageNo = 1;
  while (true) {
    String message = "Message #" + messageNo++;
    ApiFuture<String> publishFuture = publisher.publish(PubsubMessage.newBuilder()
        .setData(ByteString.copyFromUtf8(message))
        .build());
    ApiFutures.addCallback(publishFuture, new ApiFutureCallback<String>() {
      @Override
      public void onFailure(Throwable throwable) {
        System.err.println("Error publishing " + message);
      }

      @Override
      public void onSuccess(String messageId) {
        System.out.println("Published " + message + " with message-id " + messageId);
      }
    });
    Thread.sleep(SLEEP_1S);
  }
}
 
Example #19
Source File: BaseIT.java    From kafka-pubsub-emulator with Apache License 2.0 6 votes vote down vote up
protected void publish(
    Publisher publisher,
    PubsubMessage message,
    java.util.function.Consumer<Throwable> onFailure,
    java.util.function.Consumer<String> onSuccess) {
  ApiFutures.addCallback(
      publisher.publish(message),
      new ApiFutureCallback<String>() {
        @Override
        public void onFailure(Throwable throwable) {
          onFailure.accept(throwable);
        }

        @Override
        public void onSuccess(String result) {
          onSuccess.accept(result);
        }
      });
}
 
Example #20
Source File: GoogleAdsFieldServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<SearchGoogleAdsFieldsPagedResponse> createAsync(
    PageContext<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse, GoogleAdsField>
        context,
    ApiFuture<SearchGoogleAdsFieldsResponse> futureResponse) {
  ApiFuture<SearchGoogleAdsFieldsPage> futurePage =
      SearchGoogleAdsFieldsPage.createEmptyPage().createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<SearchGoogleAdsFieldsPage, SearchGoogleAdsFieldsPagedResponse>() {
        @Override
        public SearchGoogleAdsFieldsPagedResponse apply(SearchGoogleAdsFieldsPage input) {
          return new SearchGoogleAdsFieldsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #21
Source File: CampaignDraftServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<ListCampaignDraftAsyncErrorsPagedResponse> createAsync(
    PageContext<
            ListCampaignDraftAsyncErrorsRequest, ListCampaignDraftAsyncErrorsResponse, Status>
        context,
    ApiFuture<ListCampaignDraftAsyncErrorsResponse> futureResponse) {
  ApiFuture<ListCampaignDraftAsyncErrorsPage> futurePage =
      ListCampaignDraftAsyncErrorsPage.createEmptyPage()
          .createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<
          ListCampaignDraftAsyncErrorsPage, ListCampaignDraftAsyncErrorsPagedResponse>() {
        @Override
        public ListCampaignDraftAsyncErrorsPagedResponse apply(
            ListCampaignDraftAsyncErrorsPage input) {
          return new ListCampaignDraftAsyncErrorsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #22
Source File: Pubsub.java    From gcp-ingestion with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<String> apply(PubsubMessage message) {
  final PubsubMessage compressed = compress.apply(message);
  final ApiFuture<String> future = getPublisher(message).publish(compressed);
  final CompletableFuture<String> result = new CompletableFuture<>();
  ApiFutures.addCallback(future, new ApiFutureCallback<String>() {

    @Override
    public void onFailure(Throwable throwable) {
      result.completeExceptionally(throwable);
    }

    @Override
    public void onSuccess(String messageId) {
      result.complete(messageId);
    }
  }, executor);
  return result;
}
 
Example #23
Source File: PubSubSink.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void invoke(IN message, SinkFunction.Context context) throws Exception {
	PubsubMessage pubsubMessage = PubsubMessage
		.newBuilder()
		.setData(ByteString.copyFrom(serializationSchema.serialize(message)))
		.build();

	ApiFuture<String> future = publisher.publish(pubsubMessage);
	numPendingFutures.incrementAndGet();
	ApiFutures.addCallback(future, failureHandler, directExecutor());
}
 
Example #24
Source File: GooglePubsubPublisher.java    From echo with Apache License 2.0 5 votes vote down vote up
public void publish(String jsonPayload, Map<String, String> attributes) {
  PubsubMessage message =
      PubsubMessage.newBuilder()
          .setData(ByteString.copyFromUtf8(jsonPayload))
          .putAllAttributes(attributes)
          .build();

  log.debug("Publishing message on Google Pubsub topic {}", this.getFullTopicName());

  ApiFuture<String> future = publisher.publish(message);
  ApiFutures.addCallback(future, new PublishCallback(this.getFullTopicName()));
}
 
Example #25
Source File: FirebaseAuthorizer.java    From curiostack with MIT License 5 votes vote down vote up
@Override
public CompletionStage<Boolean> authorize(ServiceRequestContext ctx, OAuth2Token data) {
  CompletableFuture<Boolean> result = new CompletableFuture<>();
  ApiFutures.addCallback(
      firebaseAuth.verifyIdTokenAsync(data.accessToken()),
      new ApiFutureCallback<FirebaseToken>() {
        @Override
        public void onFailure(Throwable t) {
          result.complete(false);
        }

        @Override
        public void onSuccess(FirebaseToken token) {
          if (!token.isEmailVerified() && !config.isAllowUnverifiedEmail()) {
            result.complete(false);
            return;
          }
          if (!config.getAllowedGoogleDomains().isEmpty()) {
            @SuppressWarnings("unchecked")
            Map<String, Object> firebaseClaims =
                (Map<String, Object>) token.getClaims().get("firebase");
            if (!firebaseClaims.get("sign_in_provider").equals("google.com")
                || !config.getAllowedGoogleDomains().contains(getEmailDomain(token.getEmail()))) {
              result.complete(false);
              return;
            }
          }
          ctx.setAttr(FIREBASE_TOKEN, token);
          ctx.setAttr(RAW_FIREBASE_TOKEN, data.accessToken());
          result.complete(true);
        }
      },
      MoreExecutors.directExecutor());
  return result;
}
 
Example #26
Source File: PubSubPublisherTemplate.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<String> publish(final String topic, PubsubMessage pubsubMessage) {
	Assert.hasText(topic, "The topic can't be null or empty.");
	Assert.notNull(pubsubMessage, "The pubsubMessage can't be null.");

	ApiFuture<String> publishFuture =
			this.publisherFactory.createPublisher(topic).publish(pubsubMessage);

	final SettableListenableFuture<String> settableFuture = new SettableListenableFuture<>();
	ApiFutures.addCallback(publishFuture, new ApiFutureCallback<String>() {

		@Override
		public void onFailure(Throwable throwable) {
			String errorMessage = "Publishing to " + topic + " topic failed.";
			LOGGER.warn(errorMessage, throwable);
			PubSubDeliveryException pubSubDeliveryException = new PubSubDeliveryException(pubsubMessage, errorMessage, throwable);
			settableFuture.setException(pubSubDeliveryException);
		}

		@Override
		public void onSuccess(String result) {
			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug(
						"Publishing to " + topic + " was successful. Message ID: " + result);
			}
			settableFuture.set(result);
		}

	});

	return settableFuture;
}
 
Example #27
Source File: DocumentOcrTemplate.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private ListenableFuture<DocumentOcrResultSet> extractOcrResultFuture(
		OperationFuture<AsyncBatchAnnotateFilesResponse, OperationMetadata> grpcFuture) {

	SettableListenableFuture<DocumentOcrResultSet> result = new SettableListenableFuture<>();

	ApiFutures.addCallback(grpcFuture, new ApiFutureCallback<AsyncBatchAnnotateFilesResponse>() {
		@Override
		public void onFailure(Throwable throwable) {
			result.setException(throwable);
		}

		@Override
		public void onSuccess(
				AsyncBatchAnnotateFilesResponse asyncBatchAnnotateFilesResponse) {

			String outputLocationUri = asyncBatchAnnotateFilesResponse.getResponsesList().get(0)
					.getOutputConfig()
					.getGcsDestination()
					.getUri();

			GoogleStorageLocation outputFolderLocation = new GoogleStorageLocation(outputLocationUri);
			result.set(readOcrOutputFileSet(outputFolderLocation));
		}
	}, this.executor);

	return result;
}
 
Example #28
Source File: CloudPubSubSinkTask.java    From pubsub with Apache License 2.0 5 votes vote down vote up
@Override
public void flush(Map<TopicPartition, OffsetAndMetadata> partitionOffsets) {
  log.debug("Flushing...");
  // Process results of all the outstanding futures specified by each TopicPartition.
  for (Map.Entry<TopicPartition, OffsetAndMetadata> partitionOffset :
      partitionOffsets.entrySet()) {
    log.trace("Received flush for partition " + partitionOffset.getKey().toString());
    Map<Integer, OutstandingFuturesForPartition> outstandingFuturesForTopic =
        allOutstandingFutures.get(partitionOffset.getKey().topic());
    if (outstandingFuturesForTopic == null) {
      continue;
    }
    OutstandingFuturesForPartition outstandingFutures =
        outstandingFuturesForTopic.get(partitionOffset.getKey().partition());
    if (outstandingFutures == null) {
      continue;
    }
    try {
      ApiFutures.allAsList(outstandingFutures.futures).get();
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      outstandingFutures.futures.clear();
    }
  }
  allOutstandingFutures.clear();
}
 
Example #29
Source File: PubsubPluginSinkTest.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendMetricCache() {
    sink.writeCache = metric -> true;
    when(publisher.publish(Mockito.any())).thenReturn(ApiFutures.immediateFuture("Sent"));
    sink.sendMetric(metric);
    verifyZeroInteractions(publisher);
}
 
Example #30
Source File: ApiCommonOriginalFutureTestHelper.java    From future-converter with Apache License 2.0 5 votes vote down vote up
@Override
public ApiFuture<String> createRunningFuture() {
    return ApiFutures.transform(
        ApiFutures.immediateFuture(""),
        input -> {
            try {
                waitForSignal();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return AbstractConverterTest.VALUE;
        },
        executorService);
}