下面列出了com.google.common.base.Throwables#propagateIfPossible ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unchecked")
public <R> R invokeChecked(Object target, Object... args) throws Exception {
try {
if (argLength < 0) {
return (R) method.invoke(target, args);
} else {
return (R) method.invoke(target, Arrays.copyOfRange(args, 0, argLength));
}
} catch (InvocationTargetException e) {
// rethrow the cause is an exception
Throwables.propagateIfPossible(e.getCause(), Exception.class);
// otherwise, propagate the throwable
throw Throwables.propagate(e.getCause());
}
}
@ThriftMethod
public String test(int id, String name)
throws TestServiceException, TException
{
this.methodName = "test";
this.id = id;
this.name = name;
try {
return (String) getDone(resultsSupplier.get());
}
catch (ExecutionException e) {
Throwable failureResult = e.getCause();
Throwables.propagateIfPossible(failureResult, TestServiceException.class);
Throwables.propagateIfPossible(failureResult, TException.class);
throw new RuntimeException(failureResult);
}
}
private static RuntimeException propagate(String msg, Throwable throwable, boolean alwaysAnnotate) {
if (throwable instanceof InterruptedException) {
throw new RuntimeInterruptedException(msg, (InterruptedException) throwable);
} else if (throwable instanceof RuntimeInterruptedException) {
Thread.currentThread().interrupt();
if (alwaysAnnotate) {
throw new RuntimeInterruptedException(msg, (RuntimeInterruptedException) throwable);
} else {
throw (RuntimeInterruptedException) throwable;
}
}
if (throwable==null) {
throw new PropagatedRuntimeException(msg, new NullPointerException("No throwable supplied."));
}
if (!alwaysAnnotate) {
Throwables.propagateIfPossible(checkNotNull(throwable));
}
throw new PropagatedRuntimeException(msg, throwable);
}
public <T, E1 extends Exception, E2 extends Exception, E3 extends Exception> T transaction(
TransactionActionWithExceptions<T, D, E1, E2, E3> action,
Class<E1> exClass1,
Class<E2> exClass2,
Class<E3> exClass3)
throws E1, E2, E3
{
try {
Handle handle = transactionManager.getHandle(configMapper);
return action.call(handle, handle.attach(daoIface));
}
catch (Exception ex) {
Throwables.propagateIfInstanceOf(ex, exClass1);
Throwables.propagateIfInstanceOf(ex, exClass2);
Throwables.propagateIfInstanceOf(ex, exClass3);
Throwables.propagateIfPossible(ex);
throw new TransactionFailedException(
"Transaction failed due to exception being thrown " +
"from within the callback. See cause " +
"for the original exception.", ex);
}
}
public DataSource get() throws Exception {
if (result != null) {
return result;
}
Throwables.propagateIfPossible(error, Exception.class);
throw new RuntimeException(error);
}
/**
* Returns the result of {@code future}. If it threw an {@link InterruptedException} (wrapped in
* an {@link ExecutionException}), throws that underlying {@link InterruptedException}. Crashes on
* all other exceptions.
*/
public static <R> R waitForFutureAndGet(Future<R> future) throws InterruptedException {
try {
return future.get();
} catch (ExecutionException e) {
Throwables.propagateIfPossible(e.getCause(), InterruptedException.class);
throw new IllegalStateException(e);
}
}
public void invalidateObject(WorkerKey key, Worker obj) throws IOException, InterruptedException {
if (highPriorityWorkerMnemonics.contains(key.getMnemonic())) {
decrementHighPriorityWorkerCount();
}
try {
getPool(key).invalidateObject(key, obj);
} catch (Throwable t) {
Throwables.propagateIfPossible(t, IOException.class, InterruptedException.class);
throw new RuntimeException("unexpected", t);
}
}
/**
* Propagate a {@link Throwable} as a {@link RuntimeException}.
* <p>
* Like Guava {@link Throwables#propagate(Throwable)} but:
* <li> throws {@link RuntimeInterruptedException} to handle {@link InterruptedException}s; and
* <li> wraps as PropagatedRuntimeException for easier filtering
*/
public static RuntimeException propagate(Throwable throwable) {
if (throwable instanceof InterruptedException) {
throw new RuntimeInterruptedException((InterruptedException) throwable);
} else if (throwable instanceof RuntimeInterruptedException) {
Thread.currentThread().interrupt();
throw (RuntimeInterruptedException) throwable;
}
Throwables.propagateIfPossible(checkNotNull(throwable));
throw new PropagatedRuntimeException(throwable);
}
@Override
public void invalidateObject(WorkerKey key, Worker obj) throws IOException, InterruptedException {
try {
super.invalidateObject(key, obj);
} catch (Throwable t) {
Throwables.propagateIfPossible(t, IOException.class, InterruptedException.class);
throw new RuntimeException("unexpected", t);
}
}
@Override
public PartitionChunkListing listPartitionChunks(ListPartitionChunkOption... options) throws ConnectorException {
try {
buildIfNecessary();
} catch (Exception e) {
Throwables.propagateIfPossible(e, ConnectorException.class);
throw new ConnectorException(e);
}
return partitionChunkListing;
}
private void maybeInitialize() throws IOException {
if (initialized) {
return;
}
checkState(data == null);
checkState(offset == 0);
checkState(chunkCache == null);
try {
data = dataSupplier.get();
} catch (RuntimeException e) {
Throwables.propagateIfPossible(e.getCause(), IOException.class);
throw e;
}
initialized = true;
}
@Override
public <E extends Exception> void findTargetsBeneathDirectory(
final RepositoryName repository,
final String originalPattern,
String directory,
boolean rulesOnly,
ImmutableSet<PathFragment> blacklistedSubdirectories,
ImmutableSet<PathFragment> excludedSubdirectories,
BatchCallback<Target, E> callback,
Class<E> exceptionClass)
throws TargetParsingException, E, InterruptedException {
try {
findTargetsBeneathDirectoryAsyncImpl(
repository,
originalPattern,
directory,
rulesOnly,
blacklistedSubdirectories,
excludedSubdirectories,
callback,
MoreExecutors.newDirectExecutorService())
.get();
} catch (ExecutionException e) {
Throwables.propagateIfPossible(e.getCause(), TargetParsingException.class, exceptionClass);
throw new IllegalStateException(e.getCause());
}
}
RuntimeException rethrow(Throwable e) throws SQLException {
thrown = e;
Throwables.propagateIfPossible(e, SQLException.class);
throw new RuntimeException(e);
}
public <X extends Throwable> void propagateIfPossible(Class<X> declaredType)
throws X {
Throwables.propagateIfPossible(getFirstError(), declaredType);
}
public static IOException propagateFSError(FSError e) throws IOException {
Throwables.propagateIfPossible(e.getCause(), IOException.class);
return new IOException("Unexpected FSError", e);
}
/** {@inheritDoc} */
@Override
protected void process(Record record, SingleLaneProcessor.SingleLaneBatchMaker batchMaker) throws StageException {
RecordEL.setRecordInContext(tableNameVars, record);
String tableName = tableNameEval.eval(tableNameVars, conf.kuduTableTemplate, String.class);
if (!conf.caseSensitive) {
tableName = tableName.toLowerCase();
}
LOG.trace("Processing record:{} TableName={}", record.toString(), tableName);
try {
try {
KuduLookupKey key = generateLookupKey(record, tableName);
List<Map<String, Field>> values = cache.get(key);
if (values.isEmpty()) {
// No record found
if (conf.missingLookupBehavior == MissingValuesBehavior.SEND_TO_ERROR) {
errorRecordHandler.onError(new OnRecordErrorException(record, Errors.KUDU_31));
} else {
// Configured to 'Send to next stage' and 'pass as it is'
batchMaker.addRecord(record);
}
} else {
switch (conf.multipleValuesBehavior) {
case FIRST_ONLY:
setFieldsInRecord(record, values.get(0));
batchMaker.addRecord(record);
break;
case SPLIT_INTO_MULTIPLE_RECORDS:
for(Map<String, Field> lookupItem : values) {
Record newRecord = getContext().cloneRecord(record);
setFieldsInRecord(newRecord, lookupItem);
batchMaker.addRecord(newRecord);
}
break;
default:
throw new IllegalStateException("Unknown multiple value behavior: " + conf.multipleValuesBehavior);
}
}
} catch (ExecutionException|UncheckedExecutionException e) {
Throwables.propagateIfPossible(e.getCause(), StageException.class);
Throwables.propagateIfPossible(e.getCause(), OnRecordErrorException.class);
throw new IllegalStateException(e); // The cache loader shouldn't throw anything that isn't a StageException.
}
} catch (OnRecordErrorException error) { // NOSONAR
errorRecordHandler.onError(new OnRecordErrorException(record, error.getErrorCode(), error.getParams()));
}
}
private ImmutableBatchDirtyResult getDirtyValues(
ValueFetcher fetcher,
Collection<SkyKey> keys,
final SkyValueDirtinessChecker checker,
final boolean checkMissingValues)
throws InterruptedException {
ExecutorService executor =
Executors.newFixedThreadPool(
numThreads,
new ThreadFactoryBuilder().setNameFormat("FileSystem Value Invalidator %d").build());
ThrowableRecordingRunnableWrapper wrapper =
new ThrowableRecordingRunnableWrapper("FilesystemValueChecker#getDirtyValues");
final AtomicInteger numKeysChecked = new AtomicInteger(0);
MutableBatchDirtyResult batchResult = new MutableBatchDirtyResult(numKeysChecked);
ElapsedTimeReceiver elapsedTimeReceiver =
elapsedTimeNanos -> {
if (elapsedTimeNanos > 0) {
logger.atInfo().log(
"Spent %d nanoseconds checking %d filesystem nodes (%d scanned)",
elapsedTimeNanos, numKeysChecked.get(), keys.size());
}
};
try (AutoProfiler prof = AutoProfiler.create(elapsedTimeReceiver)) {
for (final SkyKey key : keys) {
if (!checker.applies(key)) {
continue;
}
Preconditions.checkState(
key.functionName().getHermeticity() == FunctionHermeticity.NONHERMETIC,
"Only non-hermetic keys can be dirty roots: %s",
key);
executor.execute(
wrapper.wrap(
() -> {
SkyValue value;
try {
value = fetcher.get(key);
} catch (InterruptedException e) {
// Exit fast. Interrupt is handled below on the main thread.
return;
}
if (!checkMissingValues && value == null) {
return;
}
numKeysChecked.incrementAndGet();
DirtyResult result = checker.check(key, value, tsgm);
if (result.isDirty()) {
batchResult.add(key, value, result.getNewValue());
}
}));
}
boolean interrupted = ExecutorUtil.interruptibleShutdown(executor);
Throwables.propagateIfPossible(wrapper.getFirstThrownError());
if (interrupted) {
throw new InterruptedException();
}
}
return batchResult.toImmutable();
}
@Override
protected void evalTopLevelInternal(
QueryExpression expr, OutputFormatterCallback<Target> callback)
throws QueryException, InterruptedException {
Throwable throwableToThrow = null;
try {
super.evalTopLevelInternal(expr, callback);
} catch (Throwable throwable) {
throwableToThrow = throwable;
} finally {
if (throwableToThrow != null) {
logger.atInfo().withCause(throwableToThrow).log(
"About to shutdown query threadpool because of throwable");
ListeningExecutorService obsoleteExecutor = executor;
// Signal that executor must be recreated on the next invocation.
executor = null;
// If evaluation failed abruptly (e.g. was interrupted), attempt to terminate all remaining
// tasks and then wait for them all to finish. We don't want to leave any dangling threads
// running tasks.
obsoleteExecutor.shutdownNow();
boolean interrupted = false;
boolean executorTerminated = false;
try {
while (!executorTerminated) {
try {
executorTerminated =
obsoleteExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
interrupted = true;
handleInterruptedShutdown();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
Throwables.propagateIfPossible(
throwableToThrow, QueryException.class, InterruptedException.class);
}
}
}
/**
* Stores the given throwable and rethrows it. It will be rethrown as is if it is an
* {@code IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the
* given type. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b>
* Be sure to declare all of the checked exception types your try block can throw when calling an
* overload of this method so as to avoid losing the original exception type.
*
* <p>This method always throws, and as such should be called as
* {@code throw closer.rethrow(e, ...);} to ensure the compiler knows that it will throw.
*
* @return this method does not return; it always throws
* @throws IOException when the given throwable is an IOException
* @throws X when the given throwable is of the declared type X
*/
public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType) throws IOException, X {
checkNotNull(e);
thrown = e;
Throwables.propagateIfPossible(e, IOException.class);
Throwables.propagateIfPossible(e, declaredType);
throw new RuntimeException(e);
}
/**
* Stores the given throwable and rethrows it. It will be rethrown as is if it is an
* {@code IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the
* given type. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b>
* Be sure to declare all of the checked exception types your try block can throw when calling an
* overload of this method so as to avoid losing the original exception type.
*
* <p>This method always throws, and as such should be called as
* {@code throw closer.rethrow(e, ...);} to ensure the compiler knows that it will throw.
*
* @return this method does not return; it always throws
* @throws IOException when the given throwable is an IOException
* @throws X when the given throwable is of the declared type X
*/
public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType)
throws IOException, X {
checkNotNull(e);
thrown = e;
Throwables.propagateIfPossible(e, IOException.class);
Throwables.propagateIfPossible(e, declaredType);
throw new RuntimeException(e);
}