下面列出了java.util.concurrent.ExecutionException#getCause ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@NotNull
private GitlabProject getProjectViaSudo(@NotNull User user) throws IOException {
try {
if (user.isAnonymous())
return cache.get("");
final String key = user.getExternalId() != null ? user.getExternalId() : user.getUsername();
if (key.isEmpty()) {
throw new IllegalStateException("Found user without identificator: " + user);
}
return cache.get(key);
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
}
throw new IllegalStateException(e);
}
}
private Response handleAuditExceptions(final ExecutionException e) {
// list of all general exceptions in org.sonatype.nexus.repository.vulnerability.exceptions
Throwable cause = e.getCause();
if (cause instanceof CompatibilityException) {
return NpmResponses.npmErrorAuditResponse(BAD_REQUEST, cause.getMessage());
}
if (cause instanceof VulnerabilityFetchingException || cause instanceof InternalException) {
log.warn(cause.getMessage(), e);
return NpmResponses.npmErrorAuditResponse(INTERNAL_SERVER_ERROR, USER_ERROR_MSG);
}
else if (cause instanceof ConfigurationException) {
log.warn(cause.getMessage(), e);
return NpmResponses.npmErrorAuditResponse(BAD_REQUEST, cause.getMessage());
}
else {
log.error(e.getMessage(), e);
return NpmResponses.npmErrorAuditResponse(INTERNAL_SERVER_ERROR, USER_ERROR_MSG);
}
}
/**
* If the <code>ExecutionException</code> is caused by an
* <code>InterruptedException</code>, throw the
* <code>CancellationException</code> instead.
*/
@Override
public Object get()
throws InterruptedException, ExecutionException {
if (Thread.interrupted()) throw new InterruptedException();
try {
return super.get();
} catch (ExecutionException ex) {
for (Throwable cause = ex.getCause(); cause != null;
cause = cause.getCause()) {
if (cause instanceof InterruptedException) {
// We interrupted the runnable but we don't want the thread
// that called get to think he was interrupted.
CancellationException ex2 = new CancellationException(LocalizedStrings.AdminDistributedSystemImpl_BY_INTERRUPT.toLocalizedString());
ex2.setStackTrace(cause.getStackTrace());
throw ex2;
}
}
throw ex;
}
}
/**
* Reads list of actions from the stream. Reading ends with
* ActionEndFlag(=0) or end of the stream.
*
* @param listeners
* @param sis
* @param version
* @param ip
* @param endIp
* @param path
* @param deobfuscationMode
* @return List of actions
* @throws IOException
* @throws java.lang.InterruptedException
* @throws java.util.concurrent.TimeoutException
*/
public static ActionList readActionListTimeout(final List<DisassemblyListener> listeners, final SWFInputStream sis, final int version, final int ip, final int endIp, final String path, final int deobfuscationMode) throws IOException, InterruptedException, TimeoutException {
try {
ActionList actions = CancellableWorker.call(new Callable<ActionList>() {
@Override
public ActionList call() throws IOException, InterruptedException {
return readActionList(listeners, sis, version, ip, endIp, path, deobfuscationMode);
}
}, Configuration.decompilationTimeoutSingleMethod.get(), TimeUnit.SECONDS);
return actions;
} catch (ExecutionException ex) {
Throwable cause = ex.getCause();
if (cause instanceof InterruptedException) {
throw (InterruptedException) cause;
} else if (cause instanceof InterruptedException) {
throw (IOException) cause;
} else {
logger.log(Level.SEVERE, null, ex);
}
}
return new ActionList();
}
@Override
public V getUnchecked(K key) {
try {
return get(key);
} catch (ExecutionException e) {
throw new UncheckedExecutionException(e.getCause());
}
}
@SuppressWarnings("deprecation")
@Override
public boolean injectKeyEvent(final KeyEvent event) throws InjectEventSecurityException {
checkNotNull(event);
checkState(Looper.myLooper() == mainLooper, "Expecting to be on main thread!");
initialize();
loopMainThreadUntilIdle();
FutureTask<Boolean> injectTask =
new SignalingTask<Boolean>(
new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
return eventInjector.injectKeyEvent(event);
}
},
IdleCondition.KEY_INJECT_HAS_COMPLETED,
generation);
// Inject the key event.
@SuppressWarnings("unused") // go/futurereturn-lsc
Future<?> possiblyIgnoredError = keyEventExecutor.submit(injectTask);
loopUntil(IdleCondition.KEY_INJECT_HAS_COMPLETED, dynamicIdleProvider.get());
try {
checkState(injectTask.isDone(), "Key injection was signaled - but it wasnt done.");
return injectTask.get();
} catch (ExecutionException ee) {
if (ee.getCause() instanceof InjectEventSecurityException) {
throw (InjectEventSecurityException) ee.getCause();
} else {
throw new RuntimeException(ee.getCause());
}
} catch (InterruptedException neverHappens) {
// we only call get() after done() is signaled.
// we should never block.
throw new RuntimeException("impossible.", neverHappens);
}
}
/**
* Called when a future passed via setFuture has completed.
*
* @param future the done future to complete this future with.
* @param expected the expected value of the {@link #value} field.
*/
@CanIgnoreReturnValue
private boolean completeWithFuture(ListenableFuture<? extends V> future, Object expected) {
Object valueToSet;
if (future instanceof TrustedFuture) {
// Break encapsulation for TrustedFuture instances since we know that subclasses cannot
// override .get() (since it is final) and therefore this is equivalent to calling .get()
// and unpacking the exceptions like we do below (just much faster because it is a single
// field read instead of a read, several branches and possibly creating exceptions).
valueToSet = ((AbstractFuture<?>) future).value;
} else {
// Otherwise calculate valueToSet by calling .get()
try {
V v = getDone(future);
valueToSet = v == null ? NULL : v;
} catch (ExecutionException exception) {
valueToSet = new Failure(exception.getCause());
} catch (CancellationException cancellation) {
valueToSet = new Cancellation(false, cancellation);
} catch (Throwable t) {
valueToSet = new Failure(t);
}
}
// The only way this can fail is if we raced with another thread calling cancel(). If we lost
// that race then there is nothing to do.
if (ATOMIC_HELPER.casValue(AbstractFuture.this, expected, valueToSet)) {
complete();
return true;
}
return false;
}
public static MCRFileStore getInstance(String contentStoreId) throws IOException {
try {
return instanceHolder.get(contentStoreId);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException) {
throw (IOException) cause;
}
throw new IOException("Error while geting instance of " + MCRFileStore.class.getSimpleName(), cause);
}
}
/**
* Called when a future passed via setFuture has completed.
*
* @param future the done future to complete this future with.
* @param expected the expected value of the {@link #value} field.
*/
@CanIgnoreReturnValue
private boolean completeWithFuture(ListenableFuture<? extends V> future, Object expected) {
Object valueToSet;
if (future instanceof TrustedFuture) {
// Break encapsulation for TrustedFuture instances since we know that subclasses cannot
// override .get() (since it is final) and therefore this is equivalent to calling .get()
// and unpacking the exceptions like we do below (just much faster because it is a single
// field read instead of a read, several branches and possibly creating exceptions).
valueToSet = ((AbstractFuture<?>) future).value;
} else {
// Otherwise calculate valueToSet by calling .get()
try {
V v = getDone(future);
valueToSet = v == null ? NULL : v;
} catch (ExecutionException exception) {
valueToSet = new Failure(exception.getCause());
} catch (CancellationException cancellation) {
valueToSet = new Cancellation(false, cancellation);
} catch (Throwable t) {
valueToSet = new Failure(t);
}
}
// The only way this can fail is if we raced with another thread calling cancel(). If we lost
// that race then there is nothing to do.
if (ATOMIC_HELPER.casValue(AbstractFuture.this, expected, valueToSet)) {
complete();
return true;
}
return false;
}
static <T> T getOnlyInterruptibly(ListenableFuture<T> future) throws InterruptedException {
try {
return future.get();
} catch (ExecutionException e) {
// unlikely, successfulAsList prevents this as the only return
Throwable cause = e.getCause();
logger.log(Level.SEVERE, "unexpected exception", cause);
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
throw new UncheckedExecutionException(cause);
}
}
/**
* Waits for the task to complete with a failure.
*
* <p>This method will block the current thread and return the resulting exception. An assertion
* failure will be thrown if the task does not fail.
*/
public static Throwable waitForFailure(Task<?> task) throws Exception {
try {
Tasks.await(task, WAIT_DURATION, WAIT_UNIT);
} catch (ExecutionException ex) {
return ex.getCause();
}
throw new AssertionError("Task did not fail");
}
private static void checkInProgressToNotAvailableException(final Future<String> future,
final String expectedPartitionId,
final BlockState.State expectedState)
throws IllegalStateException, InterruptedException {
assertTrue(future.isDone());
try {
future.get();
throw new IllegalStateException("An ExecutionException was expected.");
} catch (final ExecutionException executionException) {
final AbsentBlockException absentBlockException
= (AbsentBlockException) executionException.getCause();
assertEquals(expectedPartitionId, absentBlockException.getBlockId());
assertEquals(expectedState, absentBlockException.getState());
}
}
private IExtractedFileSet getFileSet(Distribution distribution) throws IOException {
try {
return distributions.get(distribution);
} catch (ExecutionException e) {
Throwables.propagateIfPossible(e.getCause(), IOException.class);
throw new RuntimeException(e.getCause());
}
}
private HttpEntity.Strict perform(HttpRequest request) {
try {
HttpResponse response = send(request);
if (response.status().intValue() >= 400 && response.status().intValue() < 500) {
throw new AssertionError("Expected " + request + " to succeed, but failed with " + response);
} else if (response.status().isFailure()) {
throw new RuntimeException("Request " + request + " failed unexpectedly with " + response);
}
return response.entity().toStrict(timeout, materializer).toCompletableFuture().get(timeout, TimeUnit.MILLISECONDS);
} catch (ExecutionException x) {
throw (RuntimeException) x.getCause();
} catch (InterruptedException | TimeoutException e) {
throw new RuntimeException(e);
}
}
protected byte[] waitOnFuture(final Future<byte[]> future) throws Exception {
try {
return future.get(3, TimeUnit.MINUTES);
} catch (ExecutionException e) {
LOG.info("ExecutionException", e);
Exception ee = (Exception) e.getCause();
if (ee instanceof InterruptedIOException) {
for (Procedure<?> p : this.master.getMasterProcedureExecutor().getProcedures()) {
LOG.info(p.toStringDetails());
}
}
throw (Exception) e.getCause();
}
}
@Override
public int getDocumentCount() throws DocumentStoreException {
Misc.checkState(this.isOpen(), "Database is closed");
try {
return get(queue.submit(new GetDocumentCountCallable()));
} catch (ExecutionException e) {
String message = "Failed to get document count";
logger.log(Level.SEVERE, message, e);
throw new DocumentStoreException(message, e.getCause());
}
}
/**
* Test ability to run a {@link Callable} on the service which throws an
* exception, get() the result, and then shutdown the service.
*
* @throws InterruptedException
* @throws ExecutionException
* @throws TimeoutException
*/
public void test_runOneThrowsException() throws InterruptedException, ExecutionException,
TimeoutException {
final ExecutorService delegate = newExecutor();
final NonBlockingLockManagerWithNewDesign<String> service = new NonBlockingLockManagerWithNewDesign<String>(
10/* maxConcurrency */, 1/* maxLockTries */, true/* predeclareLocks */) {
protected void ready(Runnable r) {
delegate.execute(r);
}
};
try {
final LockFutureTask<String, String> f = (LockFutureTask<String, String>) service
.submit(new String[0], new Callable<String>() {
public String call() throws Exception {
// task throws exception.
throw new HorridTaskDeath();
}
});
assertFalse(f.isCancelled());
try {
// Note: Set unit to HOURS for debugging :-)
f.get(10/* ms */, TimeUnit.MILLISECONDS);
fail("Expecting: "+HorridTaskDeath.class);
} catch (ExecutionException ex) {
if (ex.getCause() instanceof HorridTaskDeath) {
if(INFO)
log.info("Ignoring expected exception: " + ex);
} else {
final AssertionFailedError err = new AssertionFailedError(
"Expecting: " + HorridTaskDeath.class
+ " as the cause");
err.initCause(ex);
throw err;
}
}
} finally {
service.shutdownNow();
delegate.shutdownNow();
}
}
/**
* Wait until a copy operation is done or until a timeout expires.
* <p>
* This method will wait until a copy operation is done (either gracefully or by producing an error), or until the timeout expires, whichever comes first.
* If the timeout expires, the copy operation will continue to run.
* </p>
* <p>
* The timeout is in milliseconds and must be >= 0. When timeout is 0, it will be ignored and this method will wait until the copy operation is done.
* </p>
* After this operation, the copy is forgotten and subsequent queries with this copy string will lead to {@link NoSuchCopyException}
* <p>
* A {@link CopyStatus} is returned that can be used to determine why the call returned.
* </p>
*
* @param copyIdentifier
* the identifier of the copy operation to wait for.
* @param timeout
* the maximum time to wait for the copy operation in milliseconds.
*
* @return a {@link CopyStatus} containing the status of the copy.
*
* @throws IllegalArgumentException
* If argument is illegal.
* @throws NoSuchCopyException
* If the copy handle is not known.
* @throws NotConnectedException
* If file system is closed.
* @throws XenonException
* if an I/O error occurred.
* @throws IllegalArgumentException
* If the copyIdentifier is null or if the value of timeout is negative.
*/
public CopyStatus waitUntilDone(String copyIdentifier, long timeout) throws XenonException {
if (copyIdentifier == null) {
throw new IllegalArgumentException("Copy identifier may not be null");
}
PendingCopy copy = pendingCopies.get(copyIdentifier);
if (copy == null) {
throw new NoSuchCopyException(getAdaptorName(), "Copy not found: " + copyIdentifier);
}
XenonException ex = null;
String state = "DONE";
try {
copy.future.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
state = "RUNNING";
} catch (ExecutionException ee) {
Throwable cause = ee.getCause();
if (cause instanceof XenonException) {
ex = (XenonException) cause;
} else {
ex = new XenonException(getAdaptorName(), cause.getMessage(), cause);
}
state = "FAILED";
} catch (CancellationException ce) {
ex = new CopyCancelledException(getAdaptorName(), "Copy cancelled by user");
state = "FAILED";
} catch (InterruptedException ie) {
ex = new CopyCancelledException(getAdaptorName(), "Copy interrupted by user");
state = "FAILED";
Thread.currentThread().interrupt();
}
if (copy.future.isDone()) {
pendingCopies.remove(copyIdentifier);
}
return new CopyStatusImplementation(copyIdentifier, state, copy.callback.getBytesToCopy(), copy.callback.getBytesCopied(), ex);
}
private int innerCommunicate(final Command process) {
final ByteArrayOutputStream stdoutStream = new ByteArrayOutputStream();
final ByteArrayOutputStream stderrStream = new ByteArrayOutputStream();
final SimpleKillableObserver observer = new SimpleKillableObserver();
Callable<Integer> waiter = new Callable<Integer>() {
@Override
public Integer call() throws Exception {
byte[] commandInput = EMPTY_INPUT;
if (null != input) {
commandInput = input.getBytes();
}
try {
CommandResult result = process.execute(
commandInput,
observer,
stdoutStream,
stderrStream,
true); /* kill subprocess if we're interrupted */
return result.getTerminationStatus().getExitCode();
} catch (BadExitStatusException bese) {
// don't care some of our commands are whacky in that non-zero is okay.
return bese.getResult().getTerminationStatus().getExitCode();
}
}
};
int exitCode = 0;
try {
// start the wait on a seperate thread.
// This work should be done on a seperate thread because we also must
// quickly consume all the output and send all the input or we may
// deadlock.
exitCode = executor.submit(waiter).get(timeout, unit);
} catch (TimeoutException te) {
observer.kill();
throw new RuntimeException(te);
} catch (InterruptedException ie) {
observer.kill();
throw new RuntimeException(ie);
} catch (ExecutionException ee) {
observer.kill();
throwIfUnchecked(ee.getCause());
throw new RuntimeException(ee.getCause());
}
try {
CharSource.wrap(new String(stdoutStream.toByteArray(), Charsets.UTF_8))
.readLines(stdoutProcessor);
CharSource.wrap(new String(stderrStream.toByteArray(), Charsets.UTF_8))
.readLines(stderrProcessor);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
return exitCode;
}
/**
* Inspects the cause of the specified {@code ExecutionException} and
* creates a {@code ConcurrentRuntimeException} with the checked cause if
* necessary. This method works exactly like
* {@link #extractCause(ExecutionException)}. The only difference is that
* the cause of the specified {@code ExecutionException} is extracted as a
* runtime exception. This is an alternative for client code that does not
* want to deal with checked exceptions.
*
* @param ex the exception to be processed
* @return a {@code ConcurrentRuntimeException} with the checked cause
*/
public static ConcurrentRuntimeException extractCauseUnchecked(
ExecutionException ex) {
if (ex == null || ex.getCause() == null) {
return null;
}
throwCause(ex);
return new ConcurrentRuntimeException(ex.getMessage(), ex.getCause());
}