下面列出了com.google.common.util.concurrent.SettableFuture#set ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void invokeServiceByteRequestObjectTest() throws Exception {
MyObject resultObj = new MyObject(1, "Value");
SettableFuture<CommonProtos.InvokeResponse> settableFuture = SettableFuture.create();
MockCallback<CommonProtos.InvokeResponse> callback =
new MockCallback<CommonProtos.InvokeResponse>(CommonProtos.InvokeResponse.newBuilder()
.setData(getAny(resultObj)).build());
addCallback(settableFuture, callback, directExecutor());
settableFuture.set(CommonProtos.InvokeResponse.newBuilder().setData(getAny(resultObj)).build());
when(client.invokeService(any(DaprProtos.InvokeServiceRequest.class)))
.thenReturn(settableFuture);
String request = "Request";
byte[] byteRequest = serializer.serialize(request);
Mono<byte[]> result = adapter.invokeService(Verb.GET, "appId", "method", byteRequest, byte[].class);
byte[] byteOutput = result.block();
assertEquals(resultObj, serializer.deserialize(byteOutput, MyObject.class));
}
@Test
public void traverse_previousDeleteQueueItems_done() throws Exception {
// Start of traversal checking delete queue operation.
Operation deleteQueueItemsOperation = new Operation().setDone(true);
when(indexingServiceMock.getOperation("nonempty")).thenReturn(deleteQueueItemsOperation);
when(checkpointHandlerMock.readCheckpoint(FullTraversalConnector.CHECKPOINT_QUEUE))
.thenReturn(new QueueCheckpoint.QueueData().setOperationName("nonempty").get());
// End of traversal running delete queue operation.
SettableFuture<Operation> deleteQueueFuture = SettableFuture.create();
deleteQueueFuture.set(new Operation().setDone(false).setName("deleteQueueItemsName"));
when(indexingServiceMock.deleteQueueItems(any())).thenReturn(deleteQueueFuture);
FullTraversalConnector connector = createConnector(/* useQueues */ true);
List<ApiOperation> docs = createRepositoryDocsAndResponses(3);
connector.traverse();
verify(repositoryMock).getAllDocs(null);
verifyQueueValue(docs, QUEUE_B);
verifyQueueCheckpointHandler(2, 3, QUEUE_B_CHECKPOINT_BYTES);
verify(indexingServiceMock).deleteQueueItems(QUEUE_A);
}
@Override
protected void setUp() throws Exception {
super.setUp();
LocalWaveletContainer.Factory localFactory = mock(LocalWaveletContainer.Factory.class);
WaveletNotificationSubscriber notifiee = mock(WaveletNotificationSubscriber.class);
SettableFuture<ImmutableSet<WaveletId>> lookedupWavelets = SettableFuture.create();
lookedupWavelets.set(ImmutableSet.of(WAVELET_NAME.waveletId));
Wave wave =
new Wave(WAVELET_NAME.waveId, lookedupWavelets, notifiee, localFactory, null,
WAVELET_NAME.waveId.getDomain());
Map<WaveId, Wave> waves = Maps.newHashMap();
waves.put(WAVELET_NAME.waveId, wave);
when(waveMap.getWaves()).thenReturn(waves);
ImmutableSet<WaveletId> wavelets = ImmutableSet.of(WAVELET_NAME.waveletId);
when(waveMap.lookupWavelets(WAVELET_NAME.waveId)).thenReturn(wavelets);
LocalWaveletContainer c = mock(LocalWaveletContainer.class);
when(c.hasParticipant(PARTICIPANT)).thenReturn(true);
when(waveMap.getLocalWavelet(WAVELET_NAME)).thenReturn(c);
}
@Test
public void testRequestListener() throws Exception {
final SettableFuture<String> future = SettableFuture.<String>create();
Listener<ClientRequest> listener = new Listener<ClientRequest>() {
@Override
public void onEvent(ClientRequest event) {
future.set(event.toString());
}
};
ListenerRegistration listenerRegistration = IrisClientFactory.getClient().addRequestListener(listener);
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put(Capability.ATTR_ID, sessionInfo.getPlaces().get(0).getPlaceId());
attributes.put(Capability.ATTR_TYPE, Place.NAMESPACE);
attributes.put(Capability.ATTR_ADDRESS, "SERV:place:" + sessionInfo.getPlaces().get(0).getPlaceId());
PlaceModel m = (PlaceModel) IrisClientFactory.getModelCache().addOrUpdate(attributes);
ClientFuture<Place.ListDevicesResponse> actual = m.listDevices();
actual.get();
listenerRegistration.remove();
assertNotNull(future.get());
assertFalse(listenerRegistration.isRegistered());
}
@Override
public ListenableFuture<Void> onParticipantAdded(WaveletName waveletName, ParticipantId user) {
Multimap<WaveId, WaveletId> perUserView = explicitPerUserWaveViews.getIfPresent(user);
if (perUserView != null) {
if (!perUserView.containsEntry(waveletName.waveId, waveletName.waveletId)) {
perUserView.put(waveletName.waveId, waveletName.waveletId);
if(LOG.isFineLoggable()) {
LOG.fine("Added wavelet: " + waveletName + " to the view of user: " + user.getAddress());
LOG.fine("View size is now: " + perUserView.size());
}
}
}
SettableFuture<Void> task = SettableFuture.create();
task.set(null);
return task;
}
@Test
public void getStateStringValueNoOptionsTest() throws IOException {
String etag = "ETag1";
String key = "key1";
String expectedValue = "Expected state";
State<String> expectedState = buildStateKey(expectedValue, key, etag, null);
DaprProtos.GetStateResponse responseEnvelope = buildGetStateResponse(expectedValue, etag);
SettableFuture<DaprProtos.GetStateResponse> settableFuture = SettableFuture.create();
MockCallback<DaprProtos.GetStateResponse> callback = new MockCallback<>(responseEnvelope);
addCallback(settableFuture, callback, directExecutor());
when(client.getState(any(io.dapr.v1.DaprProtos.GetStateRequest.class)))
.thenReturn(settableFuture);
State<String> keyRequest = buildStateKey(null, key, etag, null);
Mono<State<String>> result = adapter.getState(STATE_STORE_NAME, keyRequest, String.class);
settableFuture.set(responseEnvelope);
assertEquals(expectedState, result.block());
}
@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);
}
@Before
public void setUp() throws Exception {
Config config = ConfigFactory.load().getConfig("xio.testApplication.settings.requestMuxer");
LocalConnector connector =
new LocalConnector("test-muxer") {
@Override
public ListenableFuture<Channel> connect() {
SettableFuture<Channel> result = SettableFuture.create();
EmbeddedChannel channel = new EmbeddedChannel();
channel.pipeline().addLast(new ClientCodec());
channels.add(channel);
result.set(channel);
return result;
}
};
// TODO(CK): Override connection pool request node instead of connector.connect
connectionPool = new ConnectionPool(connector);
group =
new NioEventLoopGroup(
5,
new ThreadFactoryBuilder().setNameFormat("chicagoClient-nioEventLoopGroup-%d").build());
requestMuxer = new RequestMuxer(config, group, connectionPool);
requestMuxer.start();
}
@Override
protected void processMessage(Message m) throws Exception {
if (m instanceof Ping) {
SettableFuture<Void> future = mapPingFutures.get(((Ping) m).getNonce());
if (future != null) {
future.set(null);
return;
}
}
if (m instanceof BloomFilter) {
lastReceivedFilter = (BloomFilter) m;
}
inboundMessages.offer(m);
}
@Test public void singleArgMethod() throws Exception {
SimpleProducerModule module = new SimpleProducerModule();
SettableFuture<String> strFuture = SettableFuture.create();
Producer<String> strProducer = producerOfFuture(strFuture);
Producer<Integer> producer =
new SimpleProducerModule_LenFactory(module, MoreExecutors.directExecutor(), strProducer);
assertThat(producer.get().isDone()).isFalse();
strFuture.set("abcdef");
assertThat(producer.get().get()).isEqualTo(6);
}
@Override
public ListenableFuture<SocketStats> getStats() {
SettableFuture<SocketStats> ret = SettableFuture.create();
ret.set(
new SocketStats(
/*data=*/ null,
listenAddress,
/*remote=*/ null,
new SocketOptions.Builder().addOption("listen_option", "listen_option_value").build(),
/*security=*/ null));
return ret;
}
private <T> SettableFuture<DaprProtos.GetStateResponse> buildFutureGetStateEnvelop(T value, String etag) throws IOException {
DaprProtos.GetStateResponse envelope = buildGetStateResponse(value, etag);
SettableFuture<DaprProtos.GetStateResponse> settableFuture = SettableFuture.create();
MockCallback<DaprProtos.GetStateResponse> callback = new MockCallback<>(envelope);
addCallback(settableFuture, callback, directExecutor());
settableFuture.set(envelope);
return settableFuture;
}
@Override
public ListenableFuture<SocketStats> getStats() {
final SettableFuture<SocketStats> ret = SettableFuture.create();
if (ch.eventLoop().inEventLoop()) {
// This is necessary, otherwise we will block forever if we get the future from inside
// the event loop.
ret.set(new SocketStats(
/*data=*/ null,
ch.localAddress(),
/*remote=*/ null,
Utils.getSocketOptions(ch),
/*security=*/ null));
return ret;
}
ch.eventLoop()
.submit(
new Runnable() {
@Override
public void run() {
ret.set(new SocketStats(
/*data=*/ null,
ch.localAddress(),
/*remote=*/ null,
Utils.getSocketOptions(ch),
/*security=*/ null));
}
})
.addListener(
new GenericFutureListener<Future<Object>>() {
@Override
public void operationComplete(Future<Object> future) throws Exception {
if (!future.isSuccess()) {
ret.setException(future.cause());
}
}
});
return ret;
}
@Test
public void invokeServiceTest() throws Exception {
String expected = "Value";
SettableFuture<CommonProtos.InvokeResponse> settableFuture = SettableFuture.create();
MockCallback<CommonProtos.InvokeResponse> callback =
new MockCallback<CommonProtos.InvokeResponse>(CommonProtos.InvokeResponse.newBuilder()
.setData(getAny(expected)).build());
addCallback(settableFuture, callback, directExecutor());
settableFuture.set(CommonProtos.InvokeResponse.newBuilder().setData(getAny(expected)).build());
when(client.invokeService(any(DaprProtos.InvokeServiceRequest.class)))
.thenReturn(settableFuture);
Mono<String> result = adapter.invokeService(Verb.GET, "appId", "method", "request", null, String.class);
String strOutput = result.block();
assertEquals(expected, strOutput);
}
/**
* Invoked at the client when the server responds to a message
* @param message a RapidResponse + reqNo received after sending a RapidRequest with a given reqNo
*/
private void receiveResponse(final WrappedRapidResponse message) {
final RapidResponse rapidResponse = message.response;
final SettableFuture<RapidResponse> future = outstandingRequests.getIfPresent(message.count);
if (future != null) {
future.set(rapidResponse);
outstandingRequests.invalidate(message.count);
} else {
// Ignore
LOG.error("Could not find future for req# {}", message.count);
}
}
@Override
public ListenableFuture<ServerStats> getStats() {
ServerStats.Builder builder
= new ServerStats.Builder()
.setListenSockets(transportServer.getListenSockets());
serverCallTracer.updateBuilder(builder);
SettableFuture<ServerStats> ret = SettableFuture.create();
ret.set(builder.build());
return ret;
}
@Test
public void testCloseAwaitsChildCloseCompletion()
{
SettableFuture<Void> engineCloseControllingFuture = SettableFuture.create();
TestCar car = _model.getObjectFactory().create(TestCar.class,
Collections.singletonMap(ConfiguredObject.NAME,
"myCar"), null);
String engineName = "myEngine";
Map<String, Object> engineAttributes = new HashMap<>();
engineAttributes.put(ConfiguredObject.NAME, engineName);
engineAttributes.put(TestEngine.BEFORE_CLOSE_FUTURE, engineCloseControllingFuture);
TestEngine engine = (TestEngine) car.createChild(TestEngine.class, engineAttributes);
ListenableFuture carListenableFuture = car.closeAsync();
assertFalse("car close future has completed before engine closed", carListenableFuture.isDone());
assertSame("engine deregistered from car too early",
engine,
car.getChildById(TestEngine.class, engine.getId()));
engineCloseControllingFuture.set(null);
assertTrue("car close future has not completed", carListenableFuture.isDone());
assertNull("engine not deregistered", car.getChildById(TestEngine.class, engine.getId()));
}
@Override
public BuildEngine.BuildEngineResult build(
BuildEngineBuildContext buildContext, ExecutionContext executionContext, BuildRule rule) {
SettableFuture<BuildResult> future = SettableFuture.create();
future.set(buildResults.get(rule.getBuildTarget()));
return BuildEngineResult.of(future);
}
@Test
public void test_client_takeover_retry_mqtt5() throws Exception {
final SettableFuture<Void> disconnectFuture = SettableFuture.create();
final CountDownLatch disconnectEventLatch = new CountDownLatch(1);
final Waiter disconnectMessageWaiter = new Waiter();
final TestDisconnectHandler testDisconnectHandler = new TestDisconnectHandler(disconnectMessageWaiter, true);
final EmbeddedChannel oldChannel =
new EmbeddedChannel(testDisconnectHandler, new TestDisconnectEventHandler(disconnectEventLatch));
oldChannel.attr(ChannelAttributes.TAKEN_OVER).set(true);
oldChannel.attr(ChannelAttributes.DISCONNECT_FUTURE).set(disconnectFuture);
oldChannel.attr(ChannelAttributes.MQTT_VERSION).set(ProtocolVersion.MQTTv5);
final AtomicReference<Channel> oldChannelRef = new AtomicReference<>(oldChannel);
when(channelPersistence.get(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.get());
when(channelPersistence.remove(eq("sameClientId"))).thenAnswer(invocation -> oldChannelRef.getAndSet(null));
assertTrue(oldChannel.isOpen());
assertTrue(embeddedChannel.isOpen());
final CONNECT connect1 = new CONNECT.Mqtt5Builder().withClientIdentifier("sameClientId").build();
embeddedChannel.writeInbound(connect1);
assertTrue(oldChannel.isOpen());
assertTrue(embeddedChannel.isOpen());
oldChannel.attr(ChannelAttributes.TAKEN_OVER).set(false);
disconnectFuture.set(null);
embeddedChannel.runPendingTasks();
assertTrue(embeddedChannel.isOpen());
assertFalse(oldChannel.isOpen());
assertTrue(oldChannel.attr(ChannelAttributes.TAKEN_OVER).get());
assertTrue(disconnectEventLatch.await(5, TimeUnit.SECONDS));
disconnectMessageWaiter.await();
final DISCONNECT disconnectMessage = testDisconnectHandler.getDisconnectMessage();
assertNotNull(disconnectMessage);
assertEquals(Mqtt5DisconnectReasonCode.SESSION_TAKEN_OVER, disconnectMessage.getReasonCode());
assertEquals(ReasonStrings.DISCONNECT_SESSION_TAKEN_OVER, disconnectMessage.getReasonString());
}
@Test
public void testCancellationDuringExecute() throws Exception {
SettableFuture<Runnable> completer = SettableFuture.create();
clients =
new SimpleRemoteExecutionClients() {
@Override
public ExecutionHandle execute() {
SettableFuture<ExecutionResult> result = SettableFuture.create();
completer.set(
() -> {
try {
result.get();
} catch (InterruptedException | ExecutionException e) {
throw new IllegalStateException();
}
});
return new ExecutionHandle() {
@Override
public ListenableFuture<ExecutionResult> getResult() {
return result;
}
@Override
public ListenableFuture<ExecuteOperationMetadata> getExecutionStarted() {
return SettableFuture.create();
}
@Override
public void cancel() {
result.setException(new IllegalAccessException());
}
};
}
};
StrategyBuildResult strategyBuildResult = beginBuild();
completer.get(2, TimeUnit.SECONDS);
boolean cancelled = strategyBuildResult.cancelIfNotComplete(new Throwable());
assertTrue(cancelled);
// The server should have received indication that the client cancelled the call.
expectedException.expect(IllegalStateException.class);
completer.get().run();
}