下面列出了怎么用java.util.concurrent.ExecutionException的API类实例代码及写法,或者点击链接到github查看源代码。
public void testBulkLoadUncheckedException() throws ExecutionException {
Exception e = new RuntimeException();
CacheLoader<Object, Object> loader = exceptionLoader(e);
LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
.recordStats(), bulkLoader(loader));
CacheStats stats = cache.stats();
assertEquals(0, stats.missCount());
assertEquals(0, stats.loadSuccessCount());
assertEquals(0, stats.loadExceptionCount());
assertEquals(0, stats.hitCount());
try {
cache.getAll(asList(new Object()));
fail();
} catch (UncheckedExecutionException expected) {
assertSame(e, expected.getCause());
}
stats = cache.stats();
assertEquals(1, stats.missCount());
assertEquals(0, stats.loadSuccessCount());
assertEquals(1, stats.loadExceptionCount());
assertEquals(0, stats.hitCount());
}
@Test
public void listenForValueThenWriteOnANodeWithExistingData()
throws DatabaseException, ExecutionException, TimeoutException, InterruptedException,
TestFailure {
List<DatabaseReference> refs = IntegrationTestHelpers.getRandomNode(2);
DatabaseReference reader = refs.get(0);
DatabaseReference writer = refs.get(1);
new WriteFuture(writer, new MapBuilder().put("a", 5).put("b", 2).build()).timedGet();
ReadFuture readFuture = new ReadFuture(reader);
// Slight race condition. We're banking on this local set being processed before the
// network catches up with the writer's broadcast.
reader.child("a").setValue(10);
EventRecord event = readFuture.timedGet().get(0);
assertEquals(10L, event.getSnapshot().child("a").getValue());
}
private synchronized NetworkResponse doGet(Long timeoutMs)
throws InterruptedException, ExecutionException, TimeoutException {
if (exception != null) {
throw new ExecutionException(exception);
}
if (resultReceived) {
return result;
}
if (timeoutMs == null) {
wait(0);
} else if (timeoutMs > 0) {
wait(timeoutMs);
}
if (exception != null) {
throw new ExecutionException(exception);
}
if (!resultReceived) {
throw new TimeoutException();
}
return result;
}
@Test
public void getCollections() throws InterruptedException, ExecutionException {
try {
final Collection<CollectionEntity> systemCollections = db.getCollections(null).get();
db.createCollection(COLLECTION_NAME + "1", null).get();
db.createCollection(COLLECTION_NAME + "2", null).get();
db.getCollections(null)
.whenComplete((collections, ex) -> {
assertThat(collections.size(), is(2 + systemCollections.size()));
assertThat(collections, is(notNullValue()));
})
.get();
} finally {
db.collection(COLLECTION_NAME + "1").drop().get();
db.collection(COLLECTION_NAME + "2").drop().get();
}
}
@Override
public int registerUnsuccessfulLogin(String login, String ipAddress) {
lock.readLock().lock();
try {
checkInitialized();
} finally {
lock.readLock().unlock();
}
lock.writeLock().lock();
try {
String cacheKey = makeCacheKey(login, ipAddress);
Integer attemptsNumber = loginAttemptsCache.get(cacheKey);
loginAttemptsCache.put(cacheKey, attemptsNumber + 1);
return serverConfig.getMaxLoginAttemptsNumber() - (attemptsNumber + 1);
} catch (ExecutionException e) {
throw new RuntimeException("BruteForceProtection error", e);
} finally {
lock.writeLock().unlock();
}
}
@Override
public InternalDocumentRevision read(final String id, final String rev) throws
DocumentNotFoundException, DocumentStoreException {
Misc.checkState(this.isOpen(), "Database is closed");
Misc.checkNotNullOrEmpty(id, "Document id");
try {
if (id.startsWith(CouchConstants._local_prefix)) {
Misc.checkArgument(rev == null, "Local documents must have a null revision ID");
String localId = id.substring(CouchConstants._local_prefix.length());
LocalDocument ld = get(queue.submit(new GetLocalDocumentCallable(localId)));
// convert to DocumentRevision, adding back "_local/" prefix which was stripped off when document was written
return new DocumentRevisionBuilder().setDocId(CouchConstants._local_prefix + ld.docId).setBody(ld.body).build();
} else {
return get(queue.submit(new GetDocumentCallable(id, rev, this.attachmentsDir, this.attachmentStreamFactory)));
}
} catch (ExecutionException e) {
throwCauseAs(e, DocumentNotFoundException.class);
String message = String.format(Locale.ENGLISH, "Failed to get document id %s at revision %s", id, rev);
logger.log(Level.SEVERE, message, e);
throw new DocumentStoreException(message, e.getCause());
}
}
private Throwable logFailedTasksAndGetCause(List<Future<Boolean>> failedFutures,
List<HTableInterfaceReference> failedTables) {
int i = 0;
Throwable t = null;
for (Future<Boolean> future : failedFutures) {
try {
future.get();
} catch (InterruptedException | ExecutionException e) {
LOGGER.warn("Index Write failed for table " + failedTables.get(i), e);
if (t == null) {
t = e;
}
}
i++;
}
return t;
}
private void confirmShutdown() throws ShutDownException {
int exitValue;
try {
ProcessResult rabbitMqProcessResult = rabbitMqProcess.get(timeoutDuration, TimeUnit.MILLISECONDS);
exitValue = rabbitMqProcessResult.getExitValue();
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new ShutDownException("Error while waiting " + timeoutDuration + " " + timeoutUnit + "for "
+ "RabbitMQ Server to shut down", e);
}
if (exitValue == 0) {
LOGGER.debug("RabbitMQ Server stopped successfully.");
} else {
LOGGER.warn("RabbitMQ Server stopped with exit value: " + exitValue);
}
}
public ProgressObject start(final TargetModuleID[] targetModuleID) throws IllegalStateException {
if (df == null) {
throw new IllegalStateException("Deployment manager is disconnected");
}
try {
return executeAction(new Action<ProgressObject>() {
@Override
public ProgressObject execute(DeploymentManager manager) throws ExecutionException {
if (isAs7()) {
return manager.start(unwrap(targetModuleID));
}
return manager.start(targetModuleID);
}
});
} catch (Exception ex) {
if (ex.getCause() instanceof IllegalStateException) {
throw (IllegalStateException) ex.getCause();
} else {
throw new IllegalStateException(ex.getCause());
}
}
}
/**
* Tests that an querying an unknown trigger id will return an exceptionally completed
* future.
*/
@Test
public void testUnknownTriggerId() throws Exception {
final TestingRestfulGateway testingRestfulGateway = new TestingRestfulGateway.Builder().build();
try {
testingStatusHandler.handleRequest(
statusOperationRequest(new TriggerId()),
testingRestfulGateway).get();
fail("This should have failed with a RestHandlerException.");
} catch (ExecutionException ee) {
final Optional<RestHandlerException> optionalRestHandlerException = ExceptionUtils.findThrowable(ee, RestHandlerException.class);
assertThat(optionalRestHandlerException.isPresent(), is(true));
final RestHandlerException restHandlerException = optionalRestHandlerException.get();
assertThat(restHandlerException.getMessage(), containsString("Operation not found"));
assertThat(restHandlerException.getHttpResponseStatus(), is(HttpResponseStatus.NOT_FOUND));
}
}
/**
* Test cleanup
*
*/
@AfterGroups(groups = {"http-commands"})
public static void stopGlassFish() {
final String METHOD = "stopGlassFish";
LOGGER.log(Level.INFO, METHOD, "stopFrame");
LOGGER.log(Level.INFO, METHOD, "stopText");
LOGGER.log(Level.INFO, METHOD, "stopFrame");
GlassFishServer server = glassFishServer();
Command command = new CommandStopDAS();
try {
Future<ResultString> future =
ServerAdmin.<ResultString>exec(server, command);
try {
ResultString result = future.get();
gfStdOut.close();
gfStdErr.close();
assertNotNull(result.getValue());
assertTrue(result.getState() == TaskState.COMPLETED);
} catch (InterruptedException | ExecutionException ie) {
fail("Version command execution failed: " + ie.getMessage());
}
} catch (GlassFishIdeException gfie) {
fail("Version command execution failed: " + gfie.getMessage());
}
}
@Override
public Alarm createOrUpdateAlarm(Alarm alarm) {
alarmDataValidator.validate(alarm);
try {
if (alarm.getStartTs() == 0L) {
alarm.setStartTs(System.currentTimeMillis());
}
if (alarm.getEndTs() == 0L) {
alarm.setEndTs(alarm.getStartTs());
}
if (alarm.getId() == null) {
Alarm existing = alarmDao.findLatestByOriginatorAndType(alarm.getTenantId(), alarm.getOriginator(), alarm.getType()).get();
if (existing == null || existing.getStatus().isCleared()) {
return createAlarm(alarm);
} else {
return updateAlarm(existing, alarm);
}
} else {
return updateAlarm(alarm).get();
}
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
}
@Test
public void testSyncSameUser() throws IOException, InterruptedException, ExecutionException {
IdentityUser previous =
new IdentityUser.Builder()
.setUserIdentity("user1")
.setSchema("schema")
.setAttribute("attrib")
.setGoogleIdentity("[email protected]")
.build();
IdentityUser current =
new IdentityUser.Builder()
.setUserIdentity("user1")
.setSchema("schema")
.setAttribute("attrib")
.setGoogleIdentity("[email protected]")
.build();
ListenableFuture<IdentityUser> sync = current.sync(previous, mockIdentityService);
assertEquals(current, sync.get());
}
@Test
public void testParallelConsumption() throws InterruptedException, ExecutionException {
final int messageCount = 10;
final MockEndpoint mockOut = getMockEndpoint("mock:out");
mockOut.setExpectedMessageCount(messageCount);
mockOut.setResultWaitTime(5000);
for (int i = 0; i < messageCount; i++) {
Future<Object> future = template.asyncRequestBody("direct:in", "Message[" + i + "]");
// here we ask the Future to return to us the response set by the thread assigned by the
// threads() DSL
String response = (String) future.get();
assertEquals("Processed", response);
}
assertMockEndpointsSatisfied();
}
private void deleteAllIndices() {
ImmutableOpenMap<String, IndexMetaData> indices = elasticSearchClient.admin().cluster()
.prepareState().get().getState()
.getMetaData().getIndices();
indices.forEach(cursor -> {
try {
elasticSearchClient.admin()
.indices()
.delete(new DeleteIndexRequest(cursor.value.getIndex().getName()))
.get();
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
});
}
@SuppressWarnings("unchecked")
private <T> T waitExpectedResponse(final Class<T> type) {
try {
Object response = responseCallback.get();
if (null == response) {
return null;
}
if (type.equals(response.getClass())) {
return (T) response;
}
if (response instanceof MySQLErrPacket) {
throw new RuntimeException(((MySQLErrPacket) response).getErrorMessage());
}
throw new RuntimeException("unexpected response type");
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
protected void customizeConfiguration() throws ExecutionException, InterruptedException, URISyntaxException {
log.info("Copying creation script " + getEntity().toString());
// TODO check these semantics are what we really want?
String configScriptUrl = entity.getConfig(RubyRepNode.CONFIGURATION_SCRIPT_URL);
Reader configContents;
if (configScriptUrl != null) {
// If set accept as-is
configContents = Streams.reader(resource.getResourceFromUrl(configScriptUrl));
} else {
String configScriptContents = processTemplate(entity.getConfig(RubyRepNode.TEMPLATE_CONFIGURATION_URL));
configContents = Streams.newReaderWithContents(configScriptContents);
}
getMachine().copyTo(configContents, getRunDir() + "/rubyrep.conf");
}
@VisibleForTesting
String pickHost(final List<String> filteredHosts) {
final List<String> mutatedList = Lists.newArrayList(filteredHosts);
while (true) {
final String candidateHost = hostPicker.pickHost(mutatedList);
try {
final HostStatus hostStatus = client.hostStatus(candidateHost).get();
if (hostStatus != null && Status.UP == hostStatus.getStatus()) {
return candidateHost;
}
mutatedList.remove(candidateHost);
if (mutatedList.isEmpty()) {
fail("all hosts matching filter pattern are DOWN");
}
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
}
private synchronized T doGet(Long timeoutMs)
throws InterruptedException, ExecutionException, TimeoutException {
if (mException != null) {
throw new ExecutionException(mException);
}
if (mResultReceived) {
return mResult;
}
if (timeoutMs == null) {
wait(0);
} else if (timeoutMs > 0) {
wait(timeoutMs);
}
if (mException != null) {
throw new ExecutionException(mException);
}
if (!mResultReceived) {
throw new TimeoutException();
}
return mResult;
}
@Override
public List<PortDescription> discoverPortDetails() {
DeviceId deviceId = handler().data().deviceId();
Tl1Controller ctrl = checkNotNull(handler().get(Tl1Controller.class));
// Assume we're successfully logged in
// Fetch port descriptions
Tl1Command pdCmd = DefaultTl1Command.builder()
.withVerb(RTRV)
.withModifier(PLUGGABLE_INV)
.withCtag(102)
.build();
Future<String> pd = ctrl.sendMsg(deviceId, pdCmd);
try {
String pdResponse = pd.get(TIMEOUT, TimeUnit.MILLISECONDS);
return extractPorts(pdResponse);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log.error("Port description not found", e);
return Collections.EMPTY_LIST;
}
}
@Test
public void testExpireOverwrite() throws InterruptedException, ExecutionException {
RMapCache<String, Integer> map = redisson.getMapCache("simple");
map.put("123", 3, 1, TimeUnit.SECONDS);
Thread.sleep(800);
map.put("123", 3, 1, TimeUnit.SECONDS);
Thread.sleep(800);
Assert.assertEquals(3, (int)map.get("123"));
Thread.sleep(200);
Assert.assertFalse(map.containsKey("123"));
map.destroy();
}
@Test
public void testSingleThreadedClient() throws InterruptedException, ExecutionException {
Random rand = ThreadLocalRandom.current();
String randomKey = String.valueOf(rand.nextInt());
String randomValue = String.valueOf(rand.nextInt());
// As long as the pool is not full, we'll get null back.
// This forces the user to create new values that can be used to populate
// the pool.
runThread(randomKey, randomValue, null);
assertEquals(1, poolMap.size(randomKey));
}
@Test
void sendTransactionsReusingListener() throws ExecutionException, InterruptedException {
RepositoryType type = DEFAULT_REPOSITORY_TYPE;
Account account1 = config().getNemesisAccount1();
Account account2 = Account.generateNewAccount(getNetworkType());
Account account3 = Account.generateNewAccount(getNetworkType());
Listener listener = createListener(type);
listener.unconfirmedRemoved(account1.getAddress()).subscribe(a -> {
System.out.println(">>>> account 1 " + a);
});
listener.unconfirmedRemoved(account2.getAddress()).subscribe(a -> {
System.out.println(">>>> account 2 " + a);
});
listener.unconfirmedRemoved(account3.getAddress()).subscribe(a -> {
System.out.println(">>>> account 3 " + a);
});
// IT PRINTS:
// >>>> account 1 94BE61F8FA091319A3564D843468ABD8E51034F7CDF132A74BBA2A7465E27C7D
// >>>> account 2 94BE61F8FA091319A3564D843468ABD8E51034F7CDF132A74BBA2A7465E27C7D
// >>>> account 3 94BE61F8FA091319A3564D843468ABD8E51034F7CDF132A74BBA2A7465E27C7D
// >>>> account 1 94BE61F8FA091319A3564D843468ABD8E51034F7CDF132A74BBA2A7465E27C7D
// >>>> account 2 94BE61F8FA091319A3564D843468ABD8E51034F7CDF132A74BBA2A7465E27C7D
// >>>> account 3 94BE61F8FA091319A3564D843468ABD8E51034F7CDF132A74BBA2A7465E27C7D
TransferTransaction transferTransaction =
TransferTransactionFactory.create(
getNetworkType(),
account2.getAddress(),
Collections
.singletonList(getNetworkCurrency().createAbsolute(BigInteger.valueOf(1))),
PlainMessage.create("test-message")
).maxFee(this.maxFee).build();
announceAndValidate(type, account1, transferTransaction);
sleep(1000);
}
@Test
public void conversionProblemIncomingSync() throws IOException, InterruptedException {
queue.addConverterFactory(new ToNumberConverterFactory() {
@Override
public Converter<NetworkResponse, ?> fromResponse(Type type, Annotation[] annotations) {
return new Converter<NetworkResponse, Number>() {
@Override
public Number convert(NetworkResponse value) throws IOException {
throw new UnsupportedOperationException("I am broken!");
}
};
}
});
server.enqueue(new MockResponse().setBody("Hi"));
Request<Number> call = example.postNumber(777, new
ToNumberConverterFactory().toRequest(Number.class, null));
try {
call.enqueue().getFuture().get();
fail();
} catch (ExecutionException e) {
assertThat(e.getCause()).isExactlyInstanceOf(ParseError.class);
assertThat(e.getCause().getCause())
.isExactlyInstanceOf(UnsupportedOperationException.class)
.hasMessage("I am broken!");
}
}
@Override
public Map<String, OptionalFailure<Object>> getAccumulators(final JobID jobID, ClassLoader loader) throws Exception {
final JobAccumulatorsHeaders accumulatorsHeaders = JobAccumulatorsHeaders.getInstance();
final JobAccumulatorsMessageParameters accMsgParams = accumulatorsHeaders.getUnresolvedMessageParameters();
accMsgParams.jobPathParameter.resolve(jobID);
accMsgParams.includeSerializedAccumulatorsParameter.resolve(Collections.singletonList(true));
CompletableFuture<JobAccumulatorsInfo> responseFuture = sendRequest(
accumulatorsHeaders,
accMsgParams);
Map<String, OptionalFailure<Object>> result = Collections.emptyMap();
try {
result = responseFuture.thenApply((JobAccumulatorsInfo accumulatorsInfo) -> {
try {
return AccumulatorHelper.deserializeAccumulators(
accumulatorsInfo.getSerializedUserAccumulators(),
loader);
} catch (Exception e) {
throw new CompletionException(
new FlinkException(
String.format("Deserialization of accumulators for job %s failed.", jobID),
e));
}
}).get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (ExecutionException ee) {
ExceptionUtils.rethrowException(ExceptionUtils.stripExecutionException(ee));
}
return result;
}
@Test
public void testNodeWithDefaultListener()
throws TestFailure, ExecutionException, TimeoutException, InterruptedException {
DatabaseReference ref = IntegrationTestUtils.getRandomNode(masterApp);
new WriteFuture(ref, new MapBuilder().put("a", 1).put("b", 2).put("c", 3).put("d", 4)
.put("e", 5).put("f", 6).build()).timedGet();
final AtomicInteger onCalled = new AtomicInteger(0);
final Semaphore semaphore = new Semaphore(0);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
// Should only be called once
if (onCalled.incrementAndGet() == 1) {
semaphore.release(1);
}
}
@Override
public void onCancelled(DatabaseError error) {
}
});
TestHelpers.waitFor(semaphore);
assertEquals(1, onCalled.get());
DataSnapshot snap = TestHelpers.getSnap(ref.limitToLast(1));
TestHelpers.assertDeepEquals(MapBuilder.of("f", 6L), snap.getValue());
}
@Test
public void scheduleRunnableTest() throws InterruptedException, ExecutionException {
ScheduledExecutorService scheduler = makeScheduler(1);
try {
TestRunnable tc = new TestRunnable();
ScheduledFuture<?> f = scheduler.schedule(tc, 0, TimeUnit.MILLISECONDS);
assertTrue(f.getDelay(TimeUnit.MILLISECONDS) <= 0);
assertNull(f.get());
assertTrue(f.isDone());
} finally {
scheduler.shutdownNow();
}
}
@Override
public Iterator<ShardEntryGroup> getReadShardGroup( final ApplicationScope scope, final long maxTimestamp,
final DirectedEdgeMeta directedEdgeMeta ) {
ValidationUtils.validateApplicationScope( scope );
GraphValidation.validateDirectedEdgeMeta( directedEdgeMeta );
final CacheKey key = new CacheKey( scope, directedEdgeMeta );
CacheEntry entry;
if( graphFig.getShardReadCacheEnabled() ) {
try {
entry = this.graphs.get(key);
} catch (ExecutionException e) {
throw new GraphRuntimeException("Unable to load shard key for graph", e);
}
} else {
entry = new CacheEntry(nodeShardAllocation.getShards( key.scope, key.directedEdgeMeta ));
}
Iterator<ShardEntryGroup> iterator = entry.getShards( maxTimestamp );
if ( iterator == null ) {
return Collections.<ShardEntryGroup>emptyList().iterator();
}
return iterator;
}
public static synchronized RcFile getRemoteRcFile(ExecutionEnvironment env)
throws IOException, RcFile.FormatException, ConnectException,
CancellationException, InterruptedException, InterruptedException,
ExecutionException {
if (env == null) {
new Exception("WARNING: null ExecutionEnvironment; returning dummy remote rc file").printStackTrace();
return RcFile.createDummy();
}
RcFile rcFile = remoteRcFiles.get(env);
if (rcFile == null) {
rcFile = createRemoteRcFile(env);
remoteRcFiles.put(env, rcFile);
}
return rcFile;
}
@Override
@Async
public Future<Void> operate(VirtualDeploymentUnit vdu, String operation)
throws PluginException, ExecutionException, InterruptedException, VimException {
for (VNFCInstance vnfcInstance : vdu.getVnfc_instance()) {
BaseVimInstance vimInstance = vimInstanceRepository.findFirstById(vnfcInstance.getVim_id());
org.openbaton.nfvo.vim_interfaces.resource_management.ResourceManagement vim =
vimBroker.getVim(vimInstance.getType());
log.info("rebuilding vnfcInstance: " + vnfcInstance.getHostname());
vim.operate(vimInstance, vdu, vnfcInstance, operation).get();
}
return new AsyncResult<>(null);
}