本文整理汇总了Java中com.google.common.util.concurrent.ListenableFuture.get方法的典型用法代码示例。如果您正苦于以下问题:Java ListenableFuture.get方法的具体用法?Java ListenableFuture.get怎么用?Java ListenableFuture.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类com.google.common.util.concurrent.ListenableFuture
的用法示例。
在下文中一共展示了ListenableFuture.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: loadBuildTypeList_callback_registers_exception_on_ack_future
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
@Test
public void loadBuildTypeList_callback_registers_exception_on_ack_future( ) throws Exception {
// Setup
when( _mockRequestController.sendRequest( getApiVersion( ), "buildTypes", BuildTypeList.class ) )
.thenReturn( Futures.immediateFailedFuture( new RuntimeException( "Unexpected test exception" ) ) );
// Exercise
final ListenableFuture<Void> ackFuture = _apiController.loadBuildTypeList( );
// Verify
try {
ackFuture.get( );
} catch ( ExecutionException e ) {
if ( e.getCause( ).getClass( ) == RuntimeException.class && e.getCause( ).getMessage( ).equals( "Unexpected test exception" ) )
return;
}
TestCase.fail( );
}
示例2: loadProjectList_callback_registers_exception_on_ack_future
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
@Test
public void loadProjectList_callback_registers_exception_on_ack_future( ) throws Exception {
// Setup
when( _mockRequestController.sendRequest( getApiVersion( ), "projects", ProjectList.class ) )
.thenReturn( Futures.immediateFailedFuture( new RuntimeException( "Unexpected test exception" ) ) );
// Exercise
final ListenableFuture<Void> ackFuture = _apiController.loadProjectList( );
// Verify
try {
ackFuture.get( );
} catch ( ExecutionException e ) {
if ( e.getCause( ).getClass( ) == RuntimeException.class && e.getCause( ).getMessage( ).equals( "Unexpected test exception" ) )
return;
}
TestCase.fail( );
}
示例3: deleteLocks
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
@Override
public ListenableFuture<Boolean> deleteLocks(String jobName) {
boolean result = true;
for (LockName lockName : LockName.values()) {
String path =
StateLocation.LOCKS.getNodePath(this.rootAddress, jobName, lockName.getName());
ListenableFuture<Boolean> thisResult = deleteNode(path, true);
try {
if (!thisResult.get()) {
result = false;
}
} catch (InterruptedException | ExecutionException e) {
LOG.log(Level.WARNING, "Error while waiting on result of delete lock at " + thisResult, e);
}
}
final SettableFuture<Boolean> future = SettableFuture.create();
future.set(result);
return future;
}
示例4: bodySuccess404
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
@Test public void bodySuccess404() throws Exception {
server.enqueue(new MockResponse().setResponseCode(404));
ListenableFuture<String> future = service.body();
try {
future.get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause())
.isInstanceOf(HttpException.class) // Required for backwards compatibility.
.isInstanceOf(retrofit2.HttpException.class)
.hasMessage("HTTP 404 Client Error");
}
}
示例5: bodyFailure
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
@Test public void bodyFailure() throws Exception {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
ListenableFuture<String> future = service.body();
try {
future.get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(IOException.class);
}
}
示例6: responseFailure
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
@Test public void responseFailure() throws Exception {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
ListenableFuture<Response<String>> future = service.response();
try {
future.get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause()).isInstanceOf(IOException.class);
}
}
示例7: canCommitBlocking
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
/**
*
* Invokes canCommit on underlying cohorts and blocks till
* all results are returned.
*
* Valid state transition is from SUBMITTED to CAN_COMMIT,
* if currentPhase is not SUBMITTED throws IllegalStateException.
*
* @throws TransactionCommitFailedException
* If one of cohorts failed can Commit
*
*/
private void canCommitBlocking() throws TransactionCommitFailedException {
for (final ListenableFuture<?> canCommit : canCommitAll()) {
try {
final Boolean result = (Boolean)canCommit.get();
if (result == null || !result) {
throw new TransactionCommitFailedException("Can Commit failed, no detailed cause available.");
}
} catch (InterruptedException | ExecutionException e) {
throw TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER.apply(e);
}
}
}
示例8: assertTestContainerExists
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
/**
* Reads /test from readTx Read should return container.
*/
private static Optional<NormalizedNode<?, ?>> assertTestContainerExists(final DOMStoreReadTransaction readTx)
throws InterruptedException, ExecutionException {
ListenableFuture<Optional<NormalizedNode<?, ?>>> writeTxContainer = readTx.read(TestModel.TEST_PATH);
assertTrue(writeTxContainer.get().isPresent());
return writeTxContainer.get();
}
示例9: pingPong
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
@Test
public void pingPong() throws Exception {
connect();
Utils.setMockClock();
// No ping pong happened yet.
assertEquals(Long.MAX_VALUE, peer.getLastPingTime());
assertEquals(Long.MAX_VALUE, peer.getPingTime());
ListenableFuture<Long> future = peer.ping();
assertEquals(Long.MAX_VALUE, peer.getLastPingTime());
assertEquals(Long.MAX_VALUE, peer.getPingTime());
assertFalse(future.isDone());
Ping pingMsg = (Ping) outbound(writeTarget);
Utils.rollMockClock(5);
// The pong is returned.
inbound(writeTarget, new Pong(pingMsg.getNonce()));
pingAndWait(writeTarget);
assertTrue(future.isDone());
long elapsed = future.get();
assertTrue("" + elapsed, elapsed > 1000);
assertEquals(elapsed, peer.getLastPingTime());
assertEquals(elapsed, peer.getPingTime());
// Do it again and make sure it affects the average.
future = peer.ping();
pingMsg = (Ping) outbound(writeTarget);
Utils.rollMockClock(50);
inbound(writeTarget, new Pong(pingMsg.getNonce()));
elapsed = future.get();
assertEquals(elapsed, peer.getLastPingTime());
assertEquals(7250, peer.getPingTime());
}
示例10: doCommit
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
void doCommit(final ListenableFuture<Boolean> canCommitFuture, final DOMStoreThreePhaseCommitCohort cohort)
throws Exception {
Boolean canCommit = canCommitFuture.get(commitTimeout, TimeUnit.SECONDS);
assertEquals("canCommit", true, canCommit);
cohort.preCommit().get(5, TimeUnit.SECONDS);
cohort.commit().get(5, TimeUnit.SECONDS);
}
示例11: testTransformObservableToGoogleGuavaListenableFuture
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
@Test
public void testTransformObservableToGoogleGuavaListenableFuture() throws Exception {
// You can convert an Observable to a ListenableFuture.
// ListenableFuture (part of google guava library) is a popular extension
// of Java's Future which allows registering listener callbacks:
// https://github.com/google/guava/wiki/ListenableFutureExplained
int requestPageSize = 3;
FeedOptions options = new FeedOptions();
options.setPageSize(requestPageSize);
Observable<FeedResponsePage<Document>> documentQueryObservable = asyncClient
.queryDocuments(createdCollection.getSelfLink(), "SELECT * FROM root", options);
// convert to observable of list of pages
Observable<List<FeedResponsePage<Document>>> allPagesObservable = documentQueryObservable.toList();
// convert the observable of list of pages to a Future
ListenableFuture<List<FeedResponsePage<Document>>> future = ListenableFutureObservable.to(allPagesObservable);
List<FeedResponsePage<Document>> pageList = future.get();
int totalNumberOfRetrievedDocuments = 0;
for(FeedResponsePage<Document> page: pageList) {
totalNumberOfRetrievedDocuments += page.getResults().size();
}
assertThat(numberOfDocuments, equalTo(totalNumberOfRetrievedDocuments));
}
示例12: getPivotHeaderByHash
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
private BlockHeader getPivotHeaderByHash(byte[] pivotBlockHash) throws Exception {
Channel bestIdle = pool.getAnyIdle();
if (bestIdle != null) {
try {
ListenableFuture<List<BlockHeader>> future =
bestIdle.getEthHandler().sendGetBlockHeaders(pivotBlockHash, 1, 0, false);
List<BlockHeader> blockHeaders = future.get(3, TimeUnit.SECONDS);
if (!blockHeaders.isEmpty()) {
BlockHeader ret = blockHeaders.get(0);
if (FastByteComparisons.equal(pivotBlockHash, ret.getHash())) {
logger.info("Pivot header fetched: " + ret.getShortDescr());
return ret;
}
logger.warn("Peer " + bestIdle + " returned pivot block with another hash: " +
Hex.toHexString(ret.getHash()) + " Dropping the peer.");
bestIdle.disconnect(ReasonCode.USELESS_PEER);
} else {
logger.warn("Peer " + bestIdle + " doesn't returned correct pivot block. Dropping the peer.");
bestIdle.getNodeStatistics().wrongFork = true;
bestIdle.disconnect(ReasonCode.USELESS_PEER);
}
} catch (TimeoutException e) {
logger.debug("Timeout waiting for answer", e);
}
}
return null;
}
示例13: checkQueuedBuildStatus
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
private Runnable checkQueuedBuildStatus( ) {
return ( ) -> {
if ( !isActive( ) )
return;
try {
final Instant before = Instant.now( );
ListenableFuture<Void> future = _apiController.requestQueuedBuilds( );
future.get( );
LOGGER.info( "Checking queued builds: done in {} s", Duration.between( before, Instant.now( ) ).getSeconds( ) );
} catch ( InterruptedException | ExecutionException ignored ) {
}
};
}
示例14: readData
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
protected Optional<NormalizedNode<?, ?>> readData(final YangInstanceIdentifier path) throws Exception {
DOMStoreReadTransaction transaction = store.newReadOnlyTransaction();
ListenableFuture<Optional<NormalizedNode<?, ?>>> future = transaction.read(path);
return future.get();
}
示例15: recursiveDependencyDownload_depthLimited
import com.google.common.util.concurrent.ListenableFuture; //导入方法依赖的package包/类
@Test
public void recursiveDependencyDownload_depthLimited() throws Exception {
peer.setDownloadTxDependencies(1); // Depth limit
connect();
// Make some fake transactions in the following graph:
// t1 -> t2 -> t3 -> [t4]
// The ones in brackets are assumed to be in the chain and are represented only by hashes.
Sha256Hash t4hash = Sha256Hash.wrap("2b801dd82f01d17bbde881687bf72bc62e2faa8ab8133d36fcb8c3abe7459da6");
Transaction t3 = new Transaction(PARAMS);
t3.addInput(new TransactionInput(PARAMS, t3, new byte[]{}, new TransactionOutPoint(PARAMS, 0, t4hash)));
t3.addOutput(COIN, new ECKey());
t3 = FakeTxBuilder.roundTripTransaction(PARAMS, t3);
Transaction t2 = new Transaction(PARAMS);
t2.addInput(t3.getOutput(0));
t2.addOutput(COIN, new ECKey());
t2 = FakeTxBuilder.roundTripTransaction(PARAMS, t2);
Transaction t1 = new Transaction(PARAMS);
t1.addInput(t2.getOutput(0));
t1.addOutput(COIN, new ECKey());
t1 = FakeTxBuilder.roundTripTransaction(PARAMS, t1);
// Announce the first one. Wait for it to be downloaded.
InventoryMessage inv = new InventoryMessage(PARAMS);
inv.addTransaction(t1);
inbound(writeTarget, inv);
GetDataMessage getdata = (GetDataMessage) outbound(writeTarget);
Threading.waitForUserCode();
assertEquals(t1.getHash(), getdata.getItems().get(0).hash);
inbound(writeTarget, t1);
pingAndWait(writeTarget);
// We want its dependencies so ask for them.
ListenableFuture<List<Transaction>> futures = peer.downloadDependencies(t1);
assertFalse(futures.isDone());
// level 1
getdata = (GetDataMessage) outbound(writeTarget);
assertEquals(1, getdata.getItems().size());
assertEquals(t2.getHash(), getdata.getItems().get(0).hash);
inbound(writeTarget, t2);
// no level 2
getdata = (GetDataMessage) outbound(writeTarget);
assertNull(getdata);
// That's it, now double check what we've got
pingAndWait(writeTarget);
assertTrue(futures.isDone());
List<Transaction> results = futures.get();
assertEquals(1, results.size());
assertTrue(results.contains(t2));
}