Java Code Examples for com.google.common.base.Throwables#propagateIfPossible()

The following examples show how to use com.google.common.base.Throwables#propagateIfPossible() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DynMethods.java    From kite with Apache License 2.0 6 votes vote down vote up
@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());
  }
}
 
Example 2
Source File: TestDriftServer.java    From drift with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 3
Source File: Exceptions.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 4
Source File: BasicDatabaseStoreManager.java    From digdag with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 5
Source File: RecursivePackageProviderBackedTargetPatternResolver.java    From bazel with Apache License 2.0 5 votes vote down vote up
@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());
  }
}
 
Example 6
Source File: Chunker.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 7
Source File: EasyFormatDatasetAccessor.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public PartitionChunkListing listPartitionChunks(ListPartitionChunkOption... options) throws ConnectorException {
  try {
    buildIfNecessary();
  } catch (Exception e) {
    Throwables.propagateIfPossible(e, ConnectorException.class);
    throw new ConnectorException(e);
  }

  return partitionChunkListing;
}
 
Example 8
Source File: SimpleWorkerPool.java    From bazel with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example 9
Source File: Exceptions.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 10
Source File: WorkerPool.java    From bazel with Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 11
Source File: MoreFutures.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 12
Source File: PrefetchingDatabaseProvider.java    From embedded-database-spring-test with Apache License 2.0 5 votes vote down vote up
public DataSource get() throws Exception {
    if (result != null) {
        return result;
    }
    Throwables.propagateIfPossible(error, Exception.class);
    throw new RuntimeException(error);
}
 
Example 13
Source File: DremioHadoopFileSystemWrapper.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
public static IOException propagateFSError(FSError e) throws IOException {
  Throwables.propagateIfPossible(e.getCause(), IOException.class);
  return new IOException("Unexpected FSError", e);
}
 
Example 14
Source File: KuduLookupProcessor.java    From datacollector with Apache License 2.0 4 votes vote down vote up
/** {@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()));
  }
}
 
Example 15
Source File: FilesystemValueChecker.java    From bazel with Apache License 2.0 4 votes vote down vote up
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();
}
 
Example 16
Source File: SkyQueryEnvironment.java    From bazel with Apache License 2.0 4 votes vote down vote up
@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);
    }
  }
}
 
Example 17
Source File: ThrowableFunction.java    From arctic-sea with Apache License 2.0 4 votes vote down vote up
public <X extends Throwable> void propagateIfPossible(Class<X> declaredType)
        throws X {
    Throwables.propagateIfPossible(getFirstError(), declaredType);
}
 
Example 18
Source File: ResultSetCloser.java    From glowroot with Apache License 2.0 4 votes vote down vote up
RuntimeException rethrow(Throwable e) throws SQLException {
    thrown = e;
    Throwables.propagateIfPossible(e, SQLException.class);
    throw new RuntimeException(e);
}
 
Example 19
Source File: Closer.java    From codebuff with BSD 2-Clause "Simplified" License 3 votes vote down vote up
/**
 * 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);
}
 
Example 20
Source File: Closer.java    From codebuff with BSD 2-Clause "Simplified" License 3 votes vote down vote up
/**
 * 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);
}