com.google.api.core.ApiFuture Java Examples

The following examples show how to use com.google.api.core.ApiFuture. 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: PubSubTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void publish(Record record) throws StageException {
  ByteArrayOutputStream os = new ByteArrayOutputStream();
  try (DataGenerator generator = generatorFactory.getGenerator(os)) {
    generator.write(record);
  } catch (IOException | DataGeneratorException e) {
    errorRecordHandler.onError(new OnRecordErrorException(record, Errors.PUBSUB_06, e.toString(), e));
    return;
  }

  ByteString data = ByteString.copyFrom(os.toByteArray());

  Map<String, String> attributes = new HashMap<>();
  Record.Header header = record.getHeader();
  header.getAttributeNames().forEach(k -> attributes.put(k, header.getAttribute(k)));

  PubsubMessage message = PubsubMessage.newBuilder().setData(data).putAllAttributes(attributes).build();

  ApiFuture<String> messageIdFuture = publisher.publish(message);
  pendingMessages.add(new PendingMessage(record, messageIdFuture));
}
 
Example #3
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 #4
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 #5
Source File: CampaignExperimentServiceStubSettings.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@Override
public ApiFuture<ListCampaignExperimentAsyncErrorsPagedResponse> getFuturePagedResponse(
    UnaryCallable<
            ListCampaignExperimentAsyncErrorsRequest,
            ListCampaignExperimentAsyncErrorsResponse>
        callable,
    ListCampaignExperimentAsyncErrorsRequest request,
    ApiCallContext context,
    ApiFuture<ListCampaignExperimentAsyncErrorsResponse> futureResponse) {
  PageContext<
          ListCampaignExperimentAsyncErrorsRequest,
          ListCampaignExperimentAsyncErrorsResponse, Status>
      pageContext =
          PageContext.create(
              callable,
              LIST_CAMPAIGN_EXPERIMENT_ASYNC_ERRORS_PAGE_STR_DESC,
              request,
              context);
  return ListCampaignExperimentAsyncErrorsPagedResponse.createAsync(
      pageContext, futureResponse);
}
 
Example #6
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 #7
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 #8
Source File: Quickstart.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
void runAQuery() throws Exception {
  // [START fs_add_query]
  // asynchronously query for all users born before 1900
  ApiFuture<QuerySnapshot> query =
      db.collection("users").whereLessThan("born", 1900).get();
  // ...
  // query.get() blocks on response
  QuerySnapshot querySnapshot = query.get();
  List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
  for (QueryDocumentSnapshot document : documents) {
    System.out.println("User: " + document.getId());
    System.out.println("First: " + document.getString("first"));
    if (document.contains("middle")) {
      System.out.println("Middle: " + document.getString("middle"));
    }
    System.out.println("Last: " + document.getString("last"));
    System.out.println("Born: " + document.getLong("born"));
  }
  // [END fs_add_query]
}
 
Example #9
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 #10
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/** Delete a collection in batches to avoid out-of-memory errors.
 * Batch size may be tuned based on document size (atmost 1MB) and application requirements.
 */
void deleteCollection(CollectionReference collection, int batchSize) {
  try {
    // retrieve a small batch of documents to avoid out-of-memory errors
    ApiFuture<QuerySnapshot> future = collection.limit(batchSize).get();
    int deleted = 0;
    // future.get() blocks on document retrieval
    List<QueryDocumentSnapshot> documents = future.get().getDocuments();
    for (QueryDocumentSnapshot document : documents) {
      document.getReference().delete();
      ++deleted;
    }
    if (deleted >= batchSize) {
      // retrieve and delete another batch
      deleteCollection(collection, batchSize);
    }
  } catch (Exception e) {
    System.err.println("Error deleting collection : " + e.getMessage());
  }
}
 
Example #11
Source File: CampaignExperimentServiceStubSettings.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
@Override
public ApiFuture<ListCampaignExperimentAsyncErrorsPagedResponse> getFuturePagedResponse(
    UnaryCallable<
            ListCampaignExperimentAsyncErrorsRequest,
            ListCampaignExperimentAsyncErrorsResponse>
        callable,
    ListCampaignExperimentAsyncErrorsRequest request,
    ApiCallContext context,
    ApiFuture<ListCampaignExperimentAsyncErrorsResponse> futureResponse) {
  PageContext<
          ListCampaignExperimentAsyncErrorsRequest,
          ListCampaignExperimentAsyncErrorsResponse, Status>
      pageContext =
          PageContext.create(
              callable,
              LIST_CAMPAIGN_EXPERIMENT_ASYNC_ERRORS_PAGE_STR_DESC,
              request,
              context);
  return ListCampaignExperimentAsyncErrorsPagedResponse.createAsync(
      pageContext, futureResponse);
}
 
Example #12
Source File: DatabaseReference.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
private ApiFuture<Void> updateChildrenInternal(
    final Map<String, Object> update, final CompletionListener optListener) {
  if (update == null) {
    throw new NullPointerException("Can't pass null for argument 'update' in updateChildren()");
  }
  final Map<String, Object> bouncedUpdate = CustomClassMapper.convertToPlainJavaTypes(update);
  final Map<Path, Node> parsedUpdate =
      Validation.parseAndValidateUpdate(getPath(), bouncedUpdate);
  final CompoundWrite merge = CompoundWrite.fromPathMerge(parsedUpdate);

  final Pair<ApiFuture<Void>, CompletionListener> wrapped = Utilities.wrapOnComplete(optListener);
  repo.scheduleNow(
      new Runnable() {
        @Override
        public void run() {
          repo.updateChildren(getPath(), merge, wrapped.getSecond(), bouncedUpdate);
        }
      });
  return wrapped.getFirst();
}
 
Example #13
Source File: QueryDataSnippets.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a sample query.
 *
 * @return query
 */
Query createAQueryAlternate() throws Exception {
  // [START fs_create_query_country]
  // Create a reference to the cities collection
  CollectionReference cities = db.collection("cities");
  // Create a query against the collection.
  Query query = cities.whereEqualTo("state", "CA");
  // retrieve  query results asynchronously using query.get()
  ApiFuture<QuerySnapshot> querySnapshot = query.get();

  for (DocumentSnapshot document : querySnapshot.get().getDocuments()) {
    System.out.println(document.getId());
  }
  // [END fs_create_query_country]
  return query;
}
 
Example #14
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 #15
Source File: GoogleAdsServiceClient.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
public static ApiFuture<SearchPagedResponse> createAsync(
    PageContext<SearchGoogleAdsRequest, SearchGoogleAdsResponse, GoogleAdsRow> context,
    ApiFuture<SearchGoogleAdsResponse> futureResponse) {
  ApiFuture<SearchPage> futurePage =
      SearchPage.createEmptyPage().createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<SearchPage, SearchPagedResponse>() {
        @Override
        public SearchPagedResponse apply(SearchPage input) {
          return new SearchPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #16
Source File: ExceptionTransformingCallable.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
@Override
public ApiFuture<ResponseT> futureCall(RequestT request, ApiCallContext inputContext) {
  GrpcCallContext context = GrpcCallContext.createDefault().nullToSelf(inputContext);
  ApiFuture<ResponseT> innerCallFuture = callable.futureCall(request, context);
  ExceptionTransformingFuture transformingFuture =
      new ExceptionTransformingFuture(innerCallFuture);
  ApiFutures.addCallback(innerCallFuture, transformingFuture);
  return transformingFuture;
}
 
Example #17
Source File: RetrieveDataSnippetsIT.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
private static void deleteAllDocuments() throws Exception {
  ApiFuture<QuerySnapshot> future = db.collection("cities").get();
  QuerySnapshot querySnapshot = future.get();
  for (DocumentSnapshot doc : querySnapshot.getDocuments()) {
    // block on delete operation
    db.collection("cities").document(doc.getId()).delete().get();
  }
}
 
Example #18
Source File: OnDisconnect.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private ApiFuture<Void> updateChildrenInternal(
    final Map<String, Object> update, final CompletionListener optListener) {
  final Map<Path, Node> parsedUpdate = Validation.parseAndValidateUpdate(path, update);
  final Pair<ApiFuture<Void>, CompletionListener> wrapped = Utilities.wrapOnComplete(optListener);
  repo.scheduleNow(
      new Runnable() {
        @Override
        public void run() {
          repo.onDisconnectUpdate(path, parsedUpdate, wrapped.getSecond(), update);
        }
      });
  return wrapped.getFirst();
}
 
Example #19
Source File: GoogleAdsFieldServiceStubSettings.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
@Override
public ApiFuture<SearchGoogleAdsFieldsPagedResponse> getFuturePagedResponse(
    UnaryCallable<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse> callable,
    SearchGoogleAdsFieldsRequest request,
    ApiCallContext context,
    ApiFuture<SearchGoogleAdsFieldsResponse> futureResponse) {
  PageContext<
          SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse, GoogleAdsField>
      pageContext =
          PageContext.create(
              callable, SEARCH_GOOGLE_ADS_FIELDS_PAGE_STR_DESC, request, context);
  return SearchGoogleAdsFieldsPagedResponse.createAsync(pageContext, futureResponse);
}
 
Example #20
Source File: TranslateSnippetsBeta.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
/**
 * Lists all the supported language codes.
 *
 * @param projectId - Id of the project.
 * @param location - location name.
 */
// [START translate_list_codes_beta]
static SupportedLanguages listSupportedLanguages(String projectId, String location) {
  try (TranslationServiceClient translationServiceClient = TranslationServiceClient.create()) {

    LocationName locationName =
        LocationName.newBuilder().setProject(projectId).setLocation(location).build();
    GetSupportedLanguagesRequest getSupportedLanguagesRequest =
        GetSupportedLanguagesRequest.newBuilder().setParent(locationName.toString()).build();

    // Call the API
    ApiFuture<SupportedLanguages> future =
        translationServiceClient
            .getSupportedLanguagesCallable()
            .futureCall(getSupportedLanguagesRequest);

    SupportedLanguages response = future.get();
    List<SupportedLanguage> languages = response.getLanguagesList();
    for (SupportedLanguage language : languages) {
      System.out.printf("Code: %s\n", language.getLanguageCode());
    }

    return response;

  } catch (Exception e) {
    throw new RuntimeException("Couldn't create client.", e);
  }
}
 
Example #21
Source File: PubSubPusher.java    From daq with Apache License 2.0 5 votes vote down vote up
public String sendMessage(Map<String, String> attributes, String body) {
  try {
    PubsubMessage message = PubsubMessage.newBuilder()
        .setData(ByteString.copyFrom(body, Charset.defaultCharset()))
        .putAllAttributes(attributes)
        .build();
    ApiFuture<String> publish = publisher.publish(message);
    return publish.get();
  } catch (Exception e) {
    throw new RuntimeException("While sending to topic " + registrar_topic, e);
  }
}
 
Example #22
Source File: PubSubSubscriberTemplate.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private ApiFuture<Empty> ack(String subscriptionName, Collection<String> ackIds) {
	AcknowledgeRequest acknowledgeRequest = AcknowledgeRequest.newBuilder()
			.addAllAckIds(ackIds)
			.setSubscription(subscriptionName)
			.build();
	return this.subscriberStub.acknowledgeCallable().futureCall(acknowledgeRequest);
}
 
Example #23
Source File: RetrieveDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Return multiple documents from a collection based on a query.
 *
 * @return list of documents of capital cities.
 */
public List<QueryDocumentSnapshot> getQueryResults() throws Exception {
  // [START fs_get_multiple_docs]
  //asynchronously retrieve multiple documents
  ApiFuture<QuerySnapshot> future =
      db.collection("cities").whereEqualTo("capital", true).get();
  // future.get() blocks on response
  List<QueryDocumentSnapshot> documents = future.get().getDocuments();
  for (DocumentSnapshot document : documents) {
    System.out.println(document.getId() + " => " + document.toObject(City.class));
  }
  // [END fs_get_multiple_docs]
  return documents;
}
 
Example #24
Source File: MutateJobServiceStubSettings.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
@Override
public ApiFuture<ListMutateJobResultsPagedResponse> getFuturePagedResponse(
    UnaryCallable<ListMutateJobResultsRequest, ListMutateJobResultsResponse> callable,
    ListMutateJobResultsRequest request,
    ApiCallContext context,
    ApiFuture<ListMutateJobResultsResponse> futureResponse) {
  PageContext<
          ListMutateJobResultsRequest, ListMutateJobResultsResponse, MutateJobResult>
      pageContext =
          PageContext.create(
              callable, LIST_MUTATE_JOB_RESULTS_PAGE_STR_DESC, request, context);
  return ListMutateJobResultsPagedResponse.createAsync(pageContext, futureResponse);
}
 
Example #25
Source File: InternalPhotosLibraryClient.java    From java-photoslibrary with Apache License 2.0 5 votes vote down vote up
public static ApiFuture<ListSharedAlbumsPagedResponse> createAsync(
    PageContext<ListSharedAlbumsRequest, ListSharedAlbumsResponse, Album> context,
    ApiFuture<ListSharedAlbumsResponse> futureResponse) {
  ApiFuture<ListSharedAlbumsPage> futurePage =
      ListSharedAlbumsPage.createEmptyPage().createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<ListSharedAlbumsPage, ListSharedAlbumsPagedResponse>() {
        @Override
        public ListSharedAlbumsPagedResponse apply(ListSharedAlbumsPage input) {
          return new ListSharedAlbumsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #26
Source File: ManageDataSnippets.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
/** Update document with server timestamp. */
void updateServerTimestamp() throws Exception {
  db.collection("objects").document("some-id").set(new HashMap<String, Object>()).get();

  // [START fs_update_server_timestamp]
  DocumentReference docRef = db.collection("objects").document("some-id");
  // Update the timestamp field with the value from the server
  ApiFuture<WriteResult> writeResult = docRef.update("timestamp", FieldValue.serverTimestamp());
  System.out.println("Update time : " + writeResult.get());
  // [END fs_update_server_timestamp]
}
 
Example #27
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 5 votes vote down vote up
public ApiFuture<WriteResult> setProtoDocumentAsync(String path, Message proto) {
  try {
    return setDocumentAsync(path, encodeProto(proto));
  } catch (InvalidProtocolBufferException e) {
    throw new IllegalStateException(e);
  }
}
 
Example #28
Source File: FirebaseProjectManagementServiceImpl.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an {@link ApiFuture} that will eventually contain the App ID of the new created App,
 * or an exception if an error occurred during polling.
 */
@Override
public ApiFuture<String> apply(String operationName) {
  SettableApiFuture<String> settableFuture = SettableApiFuture.create();
  scheduler.schedule(
      new WaitOperationRunnable(
          /* numberOfPreviousPolls= */ 0,
          operationName,
          projectId,
          settableFuture),
      /* delayMillis= */ POLL_BASE_WAIT_TIME_MILLIS);
  return settableFuture;
}
 
Example #29
Source File: ApiFutureUtils.java    From future-converter with Apache License 2.0 5 votes vote down vote up
public static <T> ValueSourceFuture<T> createValueSourceFuture(ApiFuture<T> apiFuture) {
    if (apiFuture instanceof ValueSourceFutureBackedApiFuture) {
        return ((ValueSourceFutureBackedApiFuture<T>) apiFuture).getWrappedFuture();
    } else {
        return new ApiFutureBackedValueSourceFuture<>(apiFuture);
    }
}
 
Example #30
Source File: GoogleAdsFieldServiceClient.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
@Override
public ApiFuture<SearchGoogleAdsFieldsPage> createPageAsync(
    PageContext<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse, GoogleAdsField>
        context,
    ApiFuture<SearchGoogleAdsFieldsResponse> futureResponse) {
  return super.createPageAsync(context, futureResponse);
}