Java Code Examples for com.google.api.core.ApiFutures#addCallback()

The following examples show how to use com.google.api.core.ApiFutures#addCallback() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
Source File: ApiFutureUtils.java    From future-converter with Apache License 2.0 5 votes vote down vote up
@Override
public void addCallbacks(Consumer<T> successCallback, Consumer<Throwable> failureCallback) {
    ApiFutures.addCallback(getWrappedFuture(), new ApiFutureCallback<T>() {
        @Override
        public void onSuccess(T result) {
            successCallback.accept(result);
        }

        @Override
        public void onFailure(Throwable t) {
            failureCallback.accept(t);

        }
    }, MoreExecutors.directExecutor());
}
 
Example 14
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 15
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 16
Source File: FirebaseDatabaseAuthTestIT.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
private static void doWrite(
    DatabaseReference ref, final boolean shouldSucceed, final boolean shouldTimeout)
    throws InterruptedException {
  final CountDownLatch lock = new CountDownLatch(1);
  final AtomicBoolean success = new AtomicBoolean(false);
  ApiFutures.addCallback(ref.setValueAsync("wrote something"), new ApiFutureCallback<Void>() {
    @Override
    public void onFailure(Throwable throwable) {
      success.compareAndSet(false, false);
      lock.countDown();
    }

    @Override
    public void onSuccess(Void result) {
      success.compareAndSet(false, true);
      lock.countDown();
    }
  }, MoreExecutors.directExecutor());
  boolean finished = lock.await(TestUtils.TEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
  if (shouldTimeout) {
    assertTrue("Write finished (expected to timeout).", !finished);
  } else if (shouldSucceed) {
    assertTrue("Write timed out (expected to succeed)", finished);
    assertTrue("Write failed (expected to succeed).", success.get());
  } else {
    assertTrue("Write timed out (expected to fail).", finished);
    assertTrue("Write successful (expected to fail).", !success.get());
  }
}
 
Example 17
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 18
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 19
Source File: ApiCommonConvertedFutureTestHelper.java    From future-converter with Apache License 2.0 4 votes vote down vote up
@Override
public void addCallbackTo(ApiFuture<String> convertedFuture) {
    ApiFutures.addCallback(convertedFuture, callback);
    convertedFuture.addListener(this::callbackCalled, MoreExecutors.directExecutor());
}