下面列出了com.google.common.util.concurrent.SettableFuture#setException ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void dispatchExpectedResponse(PlatformMessage message) {
String correlationId = message.getCorrelationId();
if(StringUtils.isBlank(correlationId)) {
return;
}
SettableFuture<PlatformMessage> future = futures.get(message.getCorrelationId());
if(future == null) {
return;
}
if(message.isError()) {
MessageBody body = message.getValue();
future.setException(new ErrorEventException((String) body.getAttributes().get("code"), (String) body.getAttributes().get("message")));
} else {
future.set(message);
}
}
protected <T extends BaseRecurlyModel> ListenableFuture<T> doGET(String resourcePath, final Class<T> clazz, @Nullable String apiVersion) {
final SettableFuture<T> future = SettableFuture.create();
try {
get(baseURL + resourcePath, apiVersion)
.execute(new AsyncCompletionHandler<Void>() {
@Override
public Void onCompleted(Response response) throws Exception {
setResponse(response, future, clazz);
return null;
}
});
} catch (Exception ex) {
future.setException(ex);
}
return future;
}
@Override
protected ListenableFuture<Void> onDelete()
{
if (!_nodeLeft)
{
SettableFuture<Void> future = SettableFuture.create();
String nodeName = getName();
try
{
_replicatedEnvironmentFacade.removeNodeFromGroup(nodeName);
getEventLogger().message(_virtualHostNodeLogSubject, HighAvailabilityMessages.DELETED());
future.set(null);
}
catch (RuntimeException e)
{
future.setException(e);
}
return future;
}
else
{
return super.onDelete();
}
}
private void executeUpsertRequest(final UpsertByIdNode.Item item, final SettableFuture<TaskResult> futureResult) {
ShardId shardId;
try {
shardId = clusterService.operationRouting().indexShards(
clusterService.state(),
item.index(),
Constants.DEFAULT_MAPPING_TYPE,
item.id(),
item.routing()
).shardId();
} catch (IndexNotFoundException e) {
if (PartitionName.isPartition(item.index())) {
futureResult.set(TaskResult.ZERO);
return;
}
throw e;
}
ShardUpsertRequest upsertRequest = new ShardUpsertRequest(
shardId, node.updateColumns(), node.insertColumns(), item.routing(), jobId());
upsertRequest.continueOnError(false);
ShardUpsertRequest.Item requestItem = new ShardUpsertRequest.Item(
item.id(), item.updateAssignments(), item.insertValues(), item.version());
upsertRequest.add(0, requestItem);
UpsertByIdContext upsertByIdContext = new UpsertByIdContext(
node.executionPhaseId(), upsertRequest, item, futureResult, transportShardUpsertActionDelegate);
createJobExecutionContext(upsertByIdContext);
try {
jobExecutionContext.start();
} catch (Throwable throwable) {
futureResult.setException(throwable);
}
}
@Test(expected = ExecutionException.class)
public void test_void_future_from_any_future_failure() throws Exception {
final SettableFuture<Object> future = SettableFuture.create();
final ListenableFuture<Void> voidFuture = FutureUtils.voidFutureFromAnyFuture(future);
assertEquals(false, voidFuture.isDone());
future.setException(new RuntimeException());
assertEquals(true, voidFuture.isDone());
voidFuture.get();
}
/**
* Create a Runnable that runs a task which produces a value, then sets the passed-in Future
* with the produced value.
*/
private <T> Runnable createFutureSettingTaskRunner(CheckedSupplier<T, Exception> task,
SettableFuture<T> setWhenFinished) {
return () -> {
try {
setWhenFinished.set(task.get());
} catch (Throwable t) {
LOG.error("Error executing task", t);
setWhenFinished.setException(t);
}
};
}
@Test
public void testCreateAwaitsAttainState_StateChangeAsyncErrors() throws Exception
{
SettableFuture stateChangeFuture = SettableFuture.create();
RuntimeException stateChangeException = new RuntimeException("state change error");
TestCar car = _model.getObjectFactory().create(TestCar.class, Collections.<String, Object>singletonMap(ConfiguredObject.NAME, "myCar"), null);
Map<String, Object> engineAttributes = new HashMap<>();
engineAttributes.put(ConfiguredObject.NAME, "myEngine");
engineAttributes.put(TestEngine.STATE_CHANGE_FUTURE, stateChangeFuture);
ListenableFuture engine = car.createChildAsync(TestEngine.class, engineAttributes);
assertFalse("create child has completed before state change completes", engine.isDone());
stateChangeFuture.setException(stateChangeException);
assertTrue("create child has not completed", engine.isDone());
try
{
engine.get();
fail("Exception not thrown");
}
catch (ExecutionException ee)
{
assertSame(stateChangeException, ee.getCause());
}
assertEquals("Failed engine should not be registered with parent",
(long) 0,
(long) car.getChildren(TestEngine.class).size());
}
@Test(expected = RuntimeException.class)
public void invokeServiceNoRequestNoClassCallbackExceptionThrownTest() {
SettableFuture<CommonProtos.InvokeResponse> settableFuture = SettableFuture.create();
RuntimeException ex = new RuntimeException("An Exception");
MockCallback<CommonProtos.InvokeResponse> callback =
new MockCallback<CommonProtos.InvokeResponse>(ex);
addCallback(settableFuture, callback, directExecutor());
when(client.invokeService(any(DaprProtos.InvokeServiceRequest.class)))
.thenReturn(settableFuture);
Mono<Void> result = adapter.invokeService(Verb.GET, "appId", "method", null);
settableFuture.setException(ex);
result.block();
}
/**
* Invokes a custom API
*
* @param apiName The API name
* @param content The byte array to send as the request body
* @param httpMethod The HTTP Method used to invoke the API
* @param requestHeaders The extra headers to send in the request
* @param parameters The query string parameters sent in the request
* @param features The SDK features used in the request
*/
private ListenableFuture<ServiceFilterResponse> invokeApiInternal(String apiName, byte[] content, String httpMethod,
List<Pair<String, String>> requestHeaders, List<Pair<String, String>> parameters, EnumSet<MobileServiceFeatures> features) {
final SettableFuture<ServiceFilterResponse> future = SettableFuture.create();
if (apiName == null || apiName.trim().equals("")) {
future.setException(new IllegalArgumentException("apiName cannot be null"));
return future;
}
MobileServiceHttpClient httpClient = new MobileServiceHttpClient(this);
return httpClient.request(CUSTOM_API_URL + apiName, content, httpMethod, requestHeaders, parameters, features);
}
@Test
public void test2() throws InterruptedException, ExecutionException, TimeoutException {
SettableFuture<Object> future = SettableFuture.create();
boolean done = future.isDone();
logger.debug("future done:{}", future.isDone());
SettableFuture<Object> future2 = SettableFuture.create();
future2.setFuture(future);
logger.debug("future2 done:{}", future2.isDone());
boolean timeout = future2.setException(new RuntimeException("timeout"));
logger.debug("timeout:{}", timeout);
}
@Override
public ListenableFuture<Optional<CommitTimestamp>> getCommitTimestamp(long startTimestamp) {
startTimestamp = removeCheckpointBits(startTimestamp);
SettableFuture<Optional<CommitTimestamp>> f = SettableFuture.create();
try(Table table = hbaseConnection.getTable(TableName.valueOf(tableName))) {
Get get = new Get(startTimestampToKey(startTimestamp));
get.addColumn(commitTableFamily, COMMIT_TABLE_QUALIFIER);
get.addColumn(commitTableFamily, INVALID_TX_QUALIFIER);
Result result = table.get(get);
if (containsInvalidTransaction(result)) {
CommitTimestamp invalidCT =
new CommitTimestamp(Location.COMMIT_TABLE, INVALID_TRANSACTION_MARKER, false);
f.set(Optional.of(invalidCT));
return f;
}
if (containsATimestamp(result)) {
long commitTSValue =
decodeCommitTimestamp(startTimestamp, result.getValue(commitTableFamily, COMMIT_TABLE_QUALIFIER));
CommitTimestamp validCT = new CommitTimestamp(Location.COMMIT_TABLE, commitTSValue, true);
f.set(Optional.of(validCT));
} else {
f.set(Optional.<CommitTimestamp>absent());
}
} catch (IOException e) {
LOG.error("Error getting commit timestamp for TX {}", startTimestamp, e);
f.setException(e);
}
return f;
}
/**
* Registers the client for template notifications with tags
*
* @param pnsHandle PNS specific identifier
* @param templateName The template name
* @param templateBody The template body
* @return Future with TemplateRegistration Information
*/
public ListenableFuture<Void> registerTemplate(String pnsHandle, String templateName, String templateBody) {
final SettableFuture<Void> resultFuture = SettableFuture.create();
if (isNullOrWhiteSpace(pnsHandle)) {
resultFuture.setException(new IllegalArgumentException("pnsHandle"));
return resultFuture;
}
if (isNullOrWhiteSpace(templateName)) {
resultFuture.setException(new IllegalArgumentException("templateName"));
return resultFuture;
}
if (isNullOrWhiteSpace(templateBody)) {
resultFuture.setException(new IllegalArgumentException("body"));
return resultFuture;
}
JsonObject templateObject = GetTemplateObject(templateName, templateBody);
ListenableFuture<Void> registerInternalFuture = createOrUpdateInstallation(pnsHandle, templateObject);
Futures.addCallback(registerInternalFuture, new FutureCallback<Void>() {
@Override
public void onFailure(Throwable exception) {
resultFuture.setException(exception);
}
@Override
public void onSuccess(Void v) {
resultFuture.set(v);
}
}, MoreExecutors.directExecutor());
return resultFuture;
}
private ChannelFutureListener newWriteListener(SettableFuture<UUID> promise, Request request) {
return new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
promise.set(request.getId());
} else {
promise.setException(future.cause());
}
}
};
}
@Test(expected = RuntimeException.class)
public void invokeServiceCallbackExceptionThrownTest() {
SettableFuture<CommonProtos.InvokeResponse> settableFuture = SettableFuture.create();
RuntimeException ex = new RuntimeException("An Exception");
MockCallback<CommonProtos.InvokeResponse> callback =
new MockCallback<CommonProtos.InvokeResponse>(ex);
addCallback(settableFuture, callback, directExecutor());
when(client.invokeService(any(DaprProtos.InvokeServiceRequest.class)))
.thenReturn(settableFuture);
Mono<String> result = adapter.invokeService(Verb.GET, "appId", "method", "request", null, String.class);
settableFuture.setException(ex);
result.block();
}
public static void main(String[] args) {
WebSocketClient client = null;
final SettableFuture<Integer> future = SettableFuture.create();
final CountDownLatch latch = new CountDownLatch(1);
try {
client = new WebSocketClient(new URI("ws://100.80.128.181:9881/ws")) {
@Override
public void onOpen(ServerHandshake handshakedata) {
System.out.println("web socket open");
//System.out.println(this);
this.send("{\"0\":\"Hk/Ue+DxkKe8FhLktTbfIwh6m9gjC0NJieyZCW8Zleau/37qmrfkinjX4zpEEcklb1p8JpoliDbDuTegvjdUjdcIhaRu/2qWeh+ebG/ufmi+fCqzSYbxl3hdrdkNekR5Akc+YtqbPhBUj5qdnPsrk6l4Qfh4H0BiaddpOxbHv6Y=\",\"1\":\"HX9LpFWgrTUt7yBqS6+Gjc4ftPHi1+kj/W+XqTq0vdCp1SmKGGLTdHFzMLgeJyiaJl2bCyCoDeSsfvpWEWxi8Nk/sUCkaaid164zR80mAc+uvg55Cc/KkdHsMF2UJwIPHJghucJgUg+MqYt04j8na+n7ZWEYxFuz6jZhVQOspZueZvkvyEH2Cb5EoU5yt2gcOWciX+K7T/iG1j0z5Oc5ovaejuBurwwL/ompvD0vI4plPdTXqqfuQAPy3pQ6pwhq53cGBVk56U0=\"}");
future.set(0);
}
@Override
public void onMessage(String message) {
//proxy netty返回的是二进制数据,不走这个逻辑
}
@Override
public void onMessage(ByteBuffer bytes) {
handleResult(bytes, latch);
}
@Override
public void onClose(int code, String reason, boolean remote) {
System.out.println("close");
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
future.setException(ex);
}
};
client.connect();
while (!client.getReadyState().equals(ReadyState.OPEN)) {
System.out.println("正在连接");
}
latch.await();
} catch (Exception e) {
} finally {
if (client != null) {
client.close();
}
}
}
public ListenableFuture<SyncResult> syncProject(ProjectSystemSyncManager.SyncReason reason) {
SettableFuture<ProjectSystemSyncManager.SyncResult> syncResult = SettableFuture.create();
if (BlazeSyncStatus.getInstance(project).syncInProgress()) {
syncResult.setException(
new RuntimeException(
"A sync was requested while one is already in progress."
+ " Use ProjectSystemSyncManager.isSyncInProgress to detect this scenario."));
} else {
BlazeSyncParams syncParams =
BlazeSyncParams.builder()
.setTitle("Sync")
.setSyncMode(SyncMode.INCREMENTAL)
.setSyncOrigin("ProjectSystemSyncManager")
.setBlazeBuildParams(BlazeBuildParams.fromProject(project))
.setAddProjectViewTargets(true)
.setAddWorkingSet(BlazeUserSettings.getInstance().getExpandSyncToWorkingSet())
.setBackgroundSync(true)
.build();
MessageBusConnection connection = project.getMessageBus().connect(project);
connection.subscribe(
PROJECT_SYSTEM_SYNC_TOPIC,
new SyncResultListener() {
@Override
public void syncEnded(@NotNull SyncResult result) {
connection.disconnect();
syncResult.set(result);
}
});
try {
BlazeSyncManager.getInstance(project).requestProjectSync(syncParams);
} catch (Throwable t) {
if (!Disposer.isDisposed(connection)) {
connection.disconnect();
}
syncResult.setException(t);
}
}
return syncResult;
}
/**
* Delete an element from a Mobile Service Table
*
* @param element The JsonObject to undelete
* @param parameters A list of user-defined parameters and values to include in the
* request URI query string
*/
public ListenableFuture<Void> delete(JsonObject element, List<Pair<String, String>> parameters) {
validateId(element);
final SettableFuture<Void> future = SettableFuture.create();
Object id = null;
String version = null;
try {
id = validateId(element);
} catch (Exception e) {
future.setException(e);
return future;
}
if (!isNumericType(id)) {
version = getVersionSystemProperty(element);
}
EnumSet<MobileServiceFeatures> features = mFeatures.clone();
if (parameters != null && parameters.size() > 0) {
features.add(MobileServiceFeatures.AdditionalQueryParameters);
}
List<Pair<String, String>> requestHeaders = null;
if (version != null) {
requestHeaders = new ArrayList<Pair<String, String>>();
requestHeaders.add(new Pair<String, String>("If-Match", getEtagFromValue(version)));
features.add(MobileServiceFeatures.OpportunisticConcurrency);
}
ListenableFuture<Pair<JsonObject, ServiceFilterResponse>> internalFuture = this.executeTableOperation(TABLES_URL + mTableName + "/" + id.toString(), null, HttpConstants.DeleteMethod, requestHeaders, parameters, features);
Futures.addCallback(internalFuture, new FutureCallback<Pair<JsonObject, ServiceFilterResponse>>() {
@Override
public void onFailure(Throwable exc) {
future.setException(exc);
}
@Override
public void onSuccess(Pair<JsonObject, ServiceFilterResponse> result) {
future.set(null);
}
}, MoreExecutors.directExecutor());
return future;
}
/**
* Undelete an element from a Mobile Service Table
*
* @param element The JsonObject to undelete
* @param parameters A list of user-defined parameters and values to include in the
* request URI query string
*/
public ListenableFuture<JsonObject> undelete(final JsonObject element, List<Pair<String, String>> parameters) {
final SettableFuture<JsonObject> future = SettableFuture.create();
Object id = null;
String version = null;
try {
id = validateId(element);
} catch (Exception e) {
future.setException(e);
return future;
}
if (!isNumericType(id)) {
version = getVersionSystemProperty(element);
}
EnumSet<MobileServiceFeatures> features = mFeatures.clone();
if (parameters != null && parameters.size() > 0) {
features.add(MobileServiceFeatures.AdditionalQueryParameters);
}
List<Pair<String, String>> requestHeaders = null;
if (version != null) {
requestHeaders = new ArrayList<Pair<String, String>>();
requestHeaders.add(new Pair<String, String>("If-Match", getEtagFromValue(version)));
features.add(MobileServiceFeatures.OpportunisticConcurrency);
}
ListenableFuture<Pair<JsonObject, ServiceFilterResponse>> internalFuture = this.executeTableOperation(TABLES_URL + mTableName + "/" + id.toString(), null, HttpConstants.PostMethod, requestHeaders, parameters, features);
Futures.addCallback(internalFuture, new FutureCallback<Pair<JsonObject, ServiceFilterResponse>>() {
@Override
public void onFailure(Throwable exc) {
future.setException(exc);
}
@Override
public void onSuccess(Pair<JsonObject, ServiceFilterResponse> result) {
JsonObject patchedJson = patchOriginalEntityWithResponseEntity(element, result.first);
updateVersionFromETag(result.second, patchedJson);
future.set(patchedJson);
}
}, MoreExecutors.directExecutor());
return future;
}
@Test(expected = ExecutionException.class)
public void test_execution_failed() throws ExecutionException, InterruptedException {
final SettableFuture<Void> voidListenableFuture = SettableFuture.create();
final Function<Void, String> functionMock = Mockito.mock(Function.class);
final CompletableFuture<String> voidCompletableFuture = ListenableFutureConverter.toCompletable(voidListenableFuture, functionMock, MoreExecutors.directExecutor());
voidListenableFuture.setException(TestException.INSTANCE);
voidCompletableFuture.get();
}
/**
* Complete target {@link SettableFuture} either successfully or exceptionally based on the state of this object.
*
* @param future Future to complete
* @return True if this call has transitioned the future to a completed state, false otherwise.
* @throws NullPointerException if {code future} is null
*/
public final boolean completeFuture(final SettableFuture<T> future) {
return isFirst() ? future.set(first()) : future.setException(second());
}