com.google.common.base.Throwables#propagateIfPossible ( )源码实例Demo

下面列出了com.google.common.base.Throwables#propagateIfPossible ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: kite   文件: DynMethods.java
@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());
  }
}
 
源代码2 项目: drift   文件: TestDriftServer.java
@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);
    }
}
 
源代码3 项目: brooklyn-server   文件: Exceptions.java
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);
}
 
源代码4 项目: digdag   文件: BasicDatabaseStoreManager.java
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);
}
 
源代码6 项目: bazel   文件: MoreFutures.java
/**
 * 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);
  }
}
 
源代码7 项目: bazel   文件: WorkerPool.java
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);
  }
}
 
源代码8 项目: brooklyn-server   文件: Exceptions.java
/**
 * 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);
}
 
源代码9 项目: bazel   文件: SimpleWorkerPool.java
@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);
  }
}
 
源代码10 项目: dremio-oss   文件: EasyFormatDatasetAccessor.java
@Override
public PartitionChunkListing listPartitionChunks(ListPartitionChunkOption... options) throws ConnectorException {
  try {
    buildIfNecessary();
  } catch (Exception e) {
    Throwables.propagateIfPossible(e, ConnectorException.class);
    throw new ConnectorException(e);
  }

  return partitionChunkListing;
}
 
源代码11 项目: bazel-buildfarm   文件: Chunker.java
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());
  }
}
 
源代码13 项目: glowroot   文件: ResultSetCloser.java
RuntimeException rethrow(Throwable e) throws SQLException {
    thrown = e;
    Throwables.propagateIfPossible(e, SQLException.class);
    throw new RuntimeException(e);
}
 
源代码14 项目: arctic-sea   文件: ThrowableFunction.java
public <X extends Throwable> void propagateIfPossible(Class<X> declaredType)
        throws X {
    Throwables.propagateIfPossible(getFirstError(), declaredType);
}
 
源代码15 项目: dremio-oss   文件: DremioHadoopFileSystemWrapper.java
public static IOException propagateFSError(FSError e) throws IOException {
  Throwables.propagateIfPossible(e.getCause(), IOException.class);
  return new IOException("Unexpected FSError", e);
}
 
源代码16 项目: datacollector   文件: KuduLookupProcessor.java
/** {@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()));
  }
}
 
源代码17 项目: bazel   文件: FilesystemValueChecker.java
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();
}
 
源代码18 项目: bazel   文件: SkyQueryEnvironment.java
@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);
    }
  }
}
 
源代码19 项目: codebuff   文件: Closer.java
/**
 * 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);
}
 
源代码20 项目: codebuff   文件: Closer.java
/**
 * 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);
}