下面列出了io.reactivex.rxjavafx.observables.JavaFxObservable#com.google.protobuf.Empty 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void deleteStateTest() {
String etag = "ETag1";
String key = "key1";
StateOptions options = buildStateOptions(StateOptions.Consistency.STRONG, StateOptions.Concurrency.FIRST_WRITE,
Duration.ofDays(100), 1, StateOptions.RetryPolicy.Pattern.LINEAR);
SettableFuture<Empty> settableFuture = SettableFuture.create();
MockCallback<Empty> callback = new MockCallback<>(Empty.newBuilder().build());
addCallback(settableFuture, callback, directExecutor());
when(client.deleteState(any(io.dapr.v1.DaprProtos.DeleteStateRequest.class)))
.thenReturn(settableFuture);
State<String> stateKey = buildStateKey(null, key, etag, options);
Mono<Void> result = adapter.deleteState(STATE_STORE_NAME, stateKey.getKey(), stateKey.getEtag(),
stateKey.getOptions());
settableFuture.set(Empty.newBuilder().build());
result.block();
assertTrue(callback.wasCalled);
}
/**
* Test successful call with broken setup.
*/
@Test
@DirtiesContext
public void testSuccessfulCallWithBrokenSetup() {
log.info("--- Starting tests with successful call with broken setup ---");
assertThrowsStatus(UNAVAILABLE,
() -> TestServiceGrpc.newBlockingStub(this.channel).normal(Empty.getDefaultInstance()));
final StreamRecorder<SomeType> streamRecorder = StreamRecorder.create();
this.testServiceStub.normal(Empty.getDefaultInstance(), streamRecorder);
assertFutureThrowsStatus(UNAVAILABLE, streamRecorder.firstValue(), 5, TimeUnit.SECONDS);
assertThrowsStatus(UNAVAILABLE, () -> this.testServiceBlockingStub.normal(Empty.getDefaultInstance()));
assertFutureThrowsStatus(UNAVAILABLE, this.testServiceFutureStub.normal(Empty.getDefaultInstance()),
5, TimeUnit.SECONDS);
log.info("--- Test completed ---");
}
@Test
public void saveStateNoConsistencyTest() {
String key = "key1";
String etag = "ETag1";
String value = "State value";
SettableFuture<Empty> settableFuture = SettableFuture.create();
MockCallback<Empty> callback = new MockCallback<>(Empty.newBuilder().build());
addCallback(settableFuture, callback, directExecutor());
when(client.saveState(any(io.dapr.v1.DaprProtos.SaveStateRequest.class))).thenReturn(settableFuture);
StateOptions options = buildStateOptions(null, StateOptions.Concurrency.FIRST_WRITE,
Duration.ofDays(100), 1, StateOptions.RetryPolicy.Pattern.LINEAR);
Mono<Void> result = adapter.saveState(STATE_STORE_NAME, key, etag, value, options);
settableFuture.set(Empty.newBuilder().build());
result.block();
assertTrue(callback.wasCalled);
}
@Test
public void saveStateRetryPolicyNoDurationTest() {
String key = "key1";
String etag = "ETag1";
String value = "State value";
SettableFuture<Empty> settableFuture = SettableFuture.create();
MockCallback<Empty> callback = new MockCallback<>(Empty.newBuilder().build());
addCallback(settableFuture, callback, directExecutor());
when(client.saveState(any(io.dapr.v1.DaprProtos.SaveStateRequest.class))).thenReturn(settableFuture);
StateOptions options = buildStateOptions(StateOptions.Consistency.STRONG, StateOptions.Concurrency.FIRST_WRITE,
null, 1, StateOptions.RetryPolicy.Pattern.LINEAR);
Mono<Void> result = adapter.saveState(STATE_STORE_NAME, key, etag, value, options);
settableFuture.set(Empty.newBuilder().build());
result.block();
assertTrue(callback.wasCalled);
}
@Test
public void saveStateRetryPolicyNoThresholdTest() {
String key = "key1";
String etag = "ETag1";
String value = "State value";
SettableFuture<Empty> settableFuture = SettableFuture.create();
MockCallback<Empty> callback = new MockCallback<>(Empty.newBuilder().build());
addCallback(settableFuture, callback, directExecutor());
when(client.saveState(any(io.dapr.v1.DaprProtos.SaveStateRequest.class))).thenReturn(settableFuture);
StateOptions options = buildStateOptions(StateOptions.Consistency.STRONG, StateOptions.Concurrency.FIRST_WRITE,
Duration.ofDays(100), null, StateOptions.RetryPolicy.Pattern.LINEAR);
Mono<Void> result = adapter.saveState(STATE_STORE_NAME, key, etag, value, options);
settableFuture.set(Empty.newBuilder().build());
result.block();
assertTrue(callback.wasCalled);
}
@Test
public void stateOptionsConsistencyValuesHaveValidGrpcEnumMappings() {
String key = "key1";
String etag = "ETag1";
String value = "State value";
SettableFuture<Empty> settableFuture = SettableFuture.create();
MockCallback<Empty> callback = new MockCallback<>(Empty.newBuilder().build());
addCallback(settableFuture, callback, directExecutor());
when(client.saveState(any(io.dapr.v1.DaprProtos.SaveStateRequest.class))).thenReturn(settableFuture);
settableFuture.set(Empty.newBuilder().build());
for (StateOptions.Consistency consistency : StateOptions.Consistency.values()) {
StateOptions options = buildStateOptions(consistency, StateOptions.Concurrency.FIRST_WRITE,
Duration.ofDays(100), null, StateOptions.RetryPolicy.Pattern.LINEAR);
Mono<Void> result = adapter.saveState(STATE_STORE_NAME, key, etag, value, options);
result.block();
}
assertTrue(callback.wasCalled);
}
private void sendAllProfiles() {
final List<ListenableFuture<Empty>> futures = Lists.newArrayList();
for (ManagedForeman managedForeman : externalIdToForeman.values()) {
try {
Optional<ListenableFuture<Empty>> future =
managedForeman.foreman.sendPlanningProfile();
future.ifPresent(futures::add);
} catch (final Exception e) {
// Exception ignored. Profile sender thread should not die due to a random
// exception
}
}
// we'll wait to complete so we don't back up if the cluster is moving slowly.
try {
Futures.successfulAsList(futures).get();
} catch (final Exception ex) {
logger.info("Failure while sending profile to JobTelemetryService", ex);
}
}
@After
public void teardown() throws IOException, InterruptedException, ExecutionException {
blob.delete();
bucket.delete();
ClusterControllerSettings clusterControllerSettings =
ClusterControllerSettings.newBuilder().setEndpoint(ENDPOINT).build();
try (ClusterControllerClient clusterControllerClient =
ClusterControllerClient.create(clusterControllerSettings)) {
for (Cluster element :
clusterControllerClient.listClusters(PROJECT_ID, REGION).iterateAll()) {
if (element.getClusterName() == CLUSTER_NAME) {
OperationFuture<Empty, ClusterOperationMetadata> deleteClusterAsyncRequest =
clusterControllerClient.deleteClusterAsync(PROJECT_ID, REGION, CLUSTER_NAME);
deleteClusterAsyncRequest.get();
break;
}
}
}
}
/**
* Tests that when ackMessages() succeeds and the subsequent call to poll() has no messages, that
* the subscriber does not invoke ackMessages because there should be no acks.
*/
@Test
public void testPollInRegularCase() throws Exception {
task.start(props);
ReceivedMessage rm1 = createReceivedMessage(ACK_ID1, CPS_MESSAGE, new HashMap<String, String>());
PullResponse stubbedPullResponse = PullResponse.newBuilder().addReceivedMessages(rm1).build();
when(subscriber.pull(any(PullRequest.class)).get()).thenReturn(stubbedPullResponse);
List<SourceRecord> result = task.poll();
assertEquals(1, result.size());
task.commitRecord(result.get(0));
stubbedPullResponse = PullResponse.newBuilder().build();
SettableApiFuture<Empty> goodFuture = SettableApiFuture.create();
goodFuture.set(Empty.getDefaultInstance());
when(subscriber.ackMessages(any(AcknowledgeRequest.class))).thenReturn(goodFuture);
when(subscriber.pull(any(PullRequest.class)).get()).thenReturn(stubbedPullResponse);
result = task.poll();
assertEquals(0, result.size());
result = task.poll();
assertEquals(0, result.size());
verify(subscriber, times(1)).ackMessages(any(AcknowledgeRequest.class));
}
@Override
public void offerStream(Empty request, StreamObserver<SimulatedOfferEvent> responseObserver) {
Subscription subscription = cloud.offers().subscribe(
offerEvent -> {
logger.info("Sending new offer event: offerId={}, rescinded={}", offerEvent.getOffer().getId().getValue(), offerEvent.isRescind());
responseObserver.onNext(toSimulatedOfferEvent(offerEvent));
},
e -> {
logger.info("Offer subscription stream terminated with an error: {}", e.getMessage(), e);
responseObserver.onError(e);
},
() -> {
logger.info("Offer subscription stream completed");
responseObserver.onCompleted();
}
);
GrpcUtil.attachCancellingCallback(responseObserver, subscription);
}
/**
* Test failing call.
*/
@Test
@DirtiesContext
public void testFailingCall() {
log.info("--- Starting tests with failing call ---");
assertThrowsStatus(UNIMPLEMENTED,
() -> TestServiceGrpc.newBlockingStub(this.channel).unimplemented(Empty.getDefaultInstance()));
final StreamRecorder<SomeType> streamRecorder = StreamRecorder.create();
this.testServiceStub.unimplemented(Empty.getDefaultInstance(), streamRecorder);
assertFutureThrowsStatus(UNIMPLEMENTED, streamRecorder.firstValue(), 5, TimeUnit.SECONDS);
assertThrowsStatus(UNIMPLEMENTED, () -> this.testServiceBlockingStub.unimplemented(Empty.getDefaultInstance()));
assertFutureThrowsStatus(UNIMPLEMENTED, this.testServiceFutureStub.unimplemented(Empty.getDefaultInstance()),
5, TimeUnit.SECONDS);
log.info("--- Test completed ---");
}
static void undeployModel(String projectId, String modelId)
throws IOException, ExecutionException, InterruptedException {
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (AutoMlClient client = AutoMlClient.create()) {
// Get the full path of the model.
ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
UndeployModelRequest request =
UndeployModelRequest.newBuilder().setName(modelFullId.toString()).build();
OperationFuture<Empty, OperationMetadata> future = client.undeployModelAsync(request);
future.get();
System.out.println("Model undeployment finished");
}
}
@Override
public Completable updateTaskAttributes(TaskAttributesUpdate attributesUpdate, CallMetadata callMetadata) {
Observable<Empty> result = findTaskInAllCells(attributesUpdate.getTaskId(), callMetadata)
.flatMap(response -> singleCellCall(response.getCell(),
(client, streamObserver) -> client.updateTaskAttributes(attributesUpdate, streamObserver),
callMetadata));
return result.toCompletable();
}
public ActiveThreadCountStreamObserver(PinpointGrpcServer pinpointGrpcServer, StreamObserver<Empty> connectionObserver) {
this.pinpointGrpcServer = Objects.requireNonNull(pinpointGrpcServer, "pinpointGrpcServer");
if (connectionObserver instanceof ServerCallStreamObserver) {
this.connectionObserver = (ServerCallStreamObserver<Empty>) connectionObserver;
} else {
throw new IllegalArgumentException("streamConnectionManagerObserver can not cast to ServerCallStreamObserver");
}
}
@Override
public Completable updateJobProcesses(JobProcessesUpdate jobProcessesUpdate, CallMetadata callMetadata) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = GrpcUtil.createEmptyClientResponseObserver(emitter);
createWrappedStub(client, callMetadata, configuration.getRequestTimeoutMs()).updateJobProcesses(jobProcessesUpdate, streamObserver);
}, configuration.getRequestTimeoutMs());
}
static void classificationDeployModel(String projectId, String modelId)
throws IOException, ExecutionException, InterruptedException {
// String projectId = "YOUR_PROJECT_ID";
// String modelId = "YOUR_MODEL_ID";
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (AutoMlClient client = AutoMlClient.create()) {
// Get the full path of the model.
ModelName modelFullId = ModelName.of(projectId, "us-central1", modelId);
// Build deploy model request.
DeployModelRequest deployModelRequest =
DeployModelRequest.newBuilder().setName(modelFullId.toString()).build();
// Deploy a model with the deploy model request.
OperationFuture<Empty, OperationMetadata> future =
client.deployModelAsync(deployModelRequest);
future.get();
// Display the deployment details of model.
System.out.println("Model deployment finished");
}
}
/**
* Tests behaviour with TLSv1.1 and shared protocols. Test should fail, as the server does not support TLSv1.1.
*/
@Test
public void testTlsV11Stub() {
Exception exception = assertThrows(StatusRuntimeException.class, () -> {
tlsV11Stub.normal(Empty.getDefaultInstance()).getVersion();
});
assertTrue(exception.getCause() instanceof SSLHandshakeException);
}
@Override
public Completable updateJobCapacity(JobCapacityUpdate request, CallMetadata callMetadata) {
Observable<Empty> result = jobManagementServiceHelper.findJobInAllCells(request.getJobId(), callMetadata)
.flatMap(response -> singleCellCall(response.getCell(),
(client, streamObserver) -> client.updateJobCapacity(request, streamObserver),
callMetadata)
);
return result.toCompletable();
}
@Test
@SuppressWarnings("all")
public void runOfflineUserDataJobTest() throws Exception {
Empty expectedResponse = Empty.newBuilder().build();
Operation resultOperation =
Operation.newBuilder()
.setName("runOfflineUserDataJobTest")
.setDone(true)
.setResponse(Any.pack(expectedResponse))
.build();
mockOfflineUserDataJobService.addResponse(resultOperation);
String formattedResourceName =
OfflineUserDataJobServiceClient.formatOfflineUserDataJobName(
"[CUSTOMER]", "[OFFLINE_USER_DATA_JOB]");
Empty actualResponse = client.runOfflineUserDataJobAsync(formattedResourceName).get();
Assert.assertEquals(expectedResponse, actualResponse);
List<AbstractMessage> actualRequests = mockOfflineUserDataJobService.getRequests();
Assert.assertEquals(1, actualRequests.size());
RunOfflineUserDataJobRequest actualRequest =
(RunOfflineUserDataJobRequest) actualRequests.get(0);
Assert.assertEquals(formattedResourceName, actualRequest.getResourceName());
Assert.assertTrue(
channelProvider.isHeaderSent(
ApiClientHeaderProvider.getDefaultApiClientHeaderKey(),
GaxGrpcProperties.getDefaultApiClientHeaderPattern()));
}
/**
* Tests behaviour with TLSv1.3 and shared protocols. Test should succeed, as the server supports TLSv1.3.
*/
@Test
public void testTlsV13Stub() {
assertEquals("1.2.3",
tlsV13Stub.normal(Empty.getDefaultInstance()).getVersion());
}
/**
* Tests behaviour with no shared ciphers. Test should fail with a {@link SSLHandshakeException}
*/
@Test
public void testNoSharedCiphersClientStub() {
Exception exception = assertThrows(StatusRuntimeException.class, () -> {
tlsNoSharedCiphersStub.normal(Empty.getDefaultInstance()).getVersion();
});
assertTrue(exception.getCause() instanceof SSLHandshakeException);
}
/** Returns the builder for the settings used for calls to runOfflineUserDataJob. */
@BetaApi(
"The surface for long-running operations is not stable yet and may change in the future.")
public OperationCallSettings.Builder<RunOfflineUserDataJobRequest, Empty, Empty>
runOfflineUserDataJobOperationSettings() {
return getStubSettingsBuilder().runOfflineUserDataJobOperationSettings();
}
@Override
public Flux<NumberProto.Number> responsePressure(Mono<Empty> request) {
return Flux
.fromIterable(IntStream.range(0, NUMBER_OF_STREAM_ELEMENTS)::iterator)
.doOnNext(i -> System.out.println(" <-- " + i))
.doOnNext(i -> updateNumberOfWaits(lastValueTime, numberOfWaits))
.map(BackpressureIntegrationTest::protoNum)
.hide();
}
@Override
public Completable deleteSystemSelector(String id) {
return createRequestCompletable(emitter -> {
StreamObserver<Empty> streamObserver = createEmptyClientResponseObserver(emitter);
GrpcUtil.createWrappedStubWithResolver(client, callMetadataResolver, configuration.getRequestTimeout()).deleteSystemSelector(SystemSelectorId.newBuilder().setId(id).build(), streamObserver);
}, configuration.getRequestTimeout());
}
private void send(final Message<? extends GeneratedMessageV3> message, StreamObserver<Empty> responseObserver) {
try {
ServerRequest<?> request = serverRequestFactory.newServerRequest(message);
this.dispatchHandler.dispatchSendMessage(request);
} catch (Exception e) {
logger.warn("Failed to request. message={}", message, e);
if (e instanceof StatusException || e instanceof StatusRuntimeException) {
responseObserver.onError(e);
} else {
// Avoid detailed exception
responseObserver.onError(Status.INTERNAL.withDescription("Bad Request").asException());
}
}
}
@Override
public void updateJobProcesses(JobProcessesUpdate request, StreamObserver<Empty> responseObserver) {
if (!jobIds.contains(request.getJobId())) {
responseObserver.onError(NOT_FOUND.asRuntimeException());
return;
}
processUpdatesTracking.add(request.getJobId());
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
}
@Test
public void testEmpty() throws IOException {
Marshaller<Empty> marshaller = ProtoLiteUtils.marshaller(Empty.getDefaultInstance());
InputStream is = marshaller.stream(Empty.getDefaultInstance());
assertEquals(0, is.available());
byte[] b = new byte[10];
assertEquals(-1, is.read(b));
assertArrayEquals(new byte[10], b);
// Do the same thing again, because the internal state may be different
assertEquals(-1, is.read(b));
assertArrayEquals(new byte[10], b);
assertEquals(-1, is.read());
assertEquals(0, is.available());
}
@Override
public Flux<NumberProto.Number> responsePressure(Mono<Empty> request) {
return Flux
.fromIterable(IntStream.range(0, NUMBER_OF_STREAM_ELEMENTS)::iterator)
.doOnNext(i -> System.out.println(" <-- " + i))
.doOnNext(i -> updateNumberOfWaits(lastValueTime, numberOfWaits))
.map(BackpressureIntegrationTest::protoNum);
}
private static void streamCompletableResponse(Completable completable, StreamObserver<Empty> responseObserver) {
Subscription subscription = completable.subscribe(
() -> {
responseObserver.onNext(Empty.getDefaultInstance());
responseObserver.onCompleted();
},
e -> safeOnError(logger, e, responseObserver)
);
attachCancellingCallback(responseObserver, subscription);
}
@Override
public void updateInstanceGroupTier(TierUpdate request, StreamObserver<Empty> responseObserver) {
Disposable subscription = agentManagementService.updateInstanceGroupTier(request).subscribe(
next -> {
// Never
},
e -> safeOnError(logger, e, responseObserver),
() -> emitEmptyReply(responseObserver)
);
attachCancellingCallback(responseObserver, subscription);
}