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

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

源代码1 项目: buck   文件: LoadingCacheFileHashCache.java
@Override
public HashCode getForArchiveMember(Path archiveRelativePath, Path memberPath)
    throws IOException {
  Path relativeFilePath = archiveRelativePath.normalize();
  try {
    JarHashCodeAndFileType fileHashCodeAndFileType =
        (JarHashCodeAndFileType) loadingCache.get(relativeFilePath);
    HashCodeAndFileType memberHashCodeAndFileType =
        fileHashCodeAndFileType.getContents().get(memberPath);
    if (memberHashCodeAndFileType == null) {
      throw new NoSuchFileException(archiveRelativePath.toString());
    }

    return memberHashCodeAndFileType.getHashCode();
  } catch (ExecutionException e) {
    Throwables.throwIfInstanceOf(e.getCause(), IOException.class);
    throw new RuntimeException(e.getCause());
  }
}
 
源代码2 项目: bazel   文件: LegacyDynamicSpawnStrategy.java
@Override
public final DynamicExecutionResult call() throws InterruptedException {
  taskFinished.register();
  try {
    List<SpawnResult> spawnResults = callImpl();
    return DynamicExecutionResult.create(strategyIdentifier, fileOutErr, null, spawnResults);
  } catch (Exception e) {
    Throwables.throwIfInstanceOf(e, InterruptedException.class);
    return DynamicExecutionResult.create(
        strategyIdentifier,
        fileOutErr,
        e instanceof ExecException
            ? (ExecException) e
            : new UserExecException(
                e, createFailureDetail(Strings.nullToEmpty(e.getMessage()), Code.RUN_FAILURE)),
        /*spawnResults=*/ ImmutableList.of());
  } finally {
    try {
      fileOutErr.close();
    } catch (IOException ignored) {
      // Nothing we can do here.
    }
    taskFinished.arriveAndDeregister();
  }
}
 
源代码3 项目: dremio-oss   文件: S3FileSystem.java
private S3Client getSyncClient(String bucket) throws IOException {
  try {
    return syncClientCache.get(bucket);
  } catch (ExecutionException | SdkClientException e ) {
    final Throwable cause = e.getCause();
    final Throwable toChain;
    if (cause == null) {
      toChain = e;
    } else {
      Throwables.throwIfInstanceOf(cause, UserException.class);
      Throwables.throwIfInstanceOf(cause, IOException.class);

      toChain = cause;
    }

    throw new IOException(String.format("Unable to create a sync S3 client for bucket %s", bucket), toChain);
  }
}
 
源代码4 项目: buck   文件: Deserializer.java
private <T extends AddsToRuleKey> void initialize(T instance, ClassInfo<? super T> classInfo)
    throws IOException {
  if (classInfo.getSuperInfo().isPresent()) {
    initialize(instance, classInfo.getSuperInfo().get());
  }

  ImmutableCollection<FieldInfo<?>> fields = classInfo.getFieldInfos();
  for (FieldInfo<?> info : fields) {
    try {
      Object value = createForField(info);
      setField(info.getField(), instance, value);
    } catch (Exception e) {
      Throwables.throwIfInstanceOf(e, IOException.class);
      throw new BuckUncheckedExecutionException(
          e,
          "When trying to initialize %s.%s.",
          instance.getClass().getName(),
          info.getField().getName());
    }
  }
}
 
源代码5 项目: bazel   文件: OptionsParser.java
/**
 * Returns the {@link OptionsData} associated with the given list of options classes.
 */
static synchronized OptionsData getOptionsDataInternal(
    List<Class<? extends OptionsBase>> optionsClasses) throws ConstructionException {
  ImmutableList<Class<? extends OptionsBase>> immutableOptionsClasses =
      ImmutableList.copyOf(optionsClasses);
  OptionsData result = optionsData.get(immutableOptionsClasses);
  if (result == null) {
    try {
      result = OptionsData.from(immutableOptionsClasses);
    } catch (Exception e) {
      Throwables.throwIfInstanceOf(e, ConstructionException.class);
      throw new ConstructionException(e.getMessage(), e);
    }
    optionsData.put(immutableOptionsClasses, result);
  }
  return result;
}
 
源代码6 项目: bazel   文件: Retrier.java
/**
 * Execute a {@link Callable}, retrying execution in case of failure and returning the result in
 * case of success.
 *
 * <p>{@link InterruptedException} is not retried.
 *
 * @param call the {@link Callable} to execute.
 * @throws Exception if the {@code call} didn't succeed within the framework specified by {@code
 *     backoffSupplier} and {@code shouldRetry}.
 * @throws CircuitBreakerException in case a call was rejected because the circuit breaker
 *     tripped.
 * @throws InterruptedException if the {@code call} throws an {@link InterruptedException} or the
 *     current thread's interrupted flag is set.
 */
public <T> T execute(Callable<T> call) throws Exception {
  final Backoff backoff = newBackoff();
  while (true) {
    final State circuitState;
    circuitState = circuitBreaker.state();
    if (State.REJECT_CALLS.equals(circuitState)) {
      throw new CircuitBreakerException();
    }
    try {
      if (Thread.interrupted()) {
        throw new InterruptedException();
      }
      T r = call.call();
      circuitBreaker.recordSuccess();
      return r;
    } catch (Exception e) {
      circuitBreaker.recordFailure();
      Throwables.throwIfInstanceOf(e, InterruptedException.class);
      if (State.TRIAL_CALL.equals(circuitState)) {
        throw e;
      }
      if (!shouldRetry.test(e)) {
        throw e;
      }
      final long delayMillis = backoff.nextDelayMillis();
      if (delayMillis < 0) {
        throw e;
      }
      sleeper.sleep(delayMillis);
    }
  }
}
 
源代码7 项目: etcd-java   文件: EtcdClusterConfig.java
public static EtcdClient getClient(EtcdClusterConfig config) throws IOException, CertificateException {
    try {
        return clientCache.get(new CacheKey(config), config::newClient);
    } catch (ExecutionException ee) {
        Throwables.throwIfInstanceOf(ee.getCause(), IOException.class);
        Throwables.throwIfInstanceOf(ee.getCause(), CertificateException.class);
        Throwables.throwIfUnchecked(ee.getCause());
        throw new RuntimeException(ee.getCause());
    }
}
 
源代码8 项目: pgptool   文件: EncryptionServicePgpImpl.java
@Override
public void encrypt(String sourceFile, String targetFile, Collection<Key> recipients,
		ProgressHandler optionalProgressHandler, InputStreamSupervisor optionalInputStreamSupervisor,
		OutputStreamSupervisor optionalOutputStreamSupervisor) throws UserRequestedCancellationException {
	try {
		InputStreamSupervisor inputStreamSupervisor = optionalInputStreamSupervisor != null
				? optionalInputStreamSupervisor
				: new InputStreamSupervisorImpl();
		OutputStreamSupervisor outputStreamSupervisor = optionalOutputStreamSupervisor != null
				? optionalOutputStreamSupervisor
				: new OutputStreamSupervisorImpl();

		Updater progress = null;
		if (optionalProgressHandler != null) {
			progress = Progress.create("action.encrypt", optionalProgressHandler);
			progress.updateStepInfo("progress.preparingKeys");
		}

		PGPEncryptedDataGenerator dataGenerator = buildEncryptedDataGenerator(
				buildKeysListForEncryption(recipients));

		OutputStream out = new BufferedOutputStream(outputStreamSupervisor.get(targetFile));
		InputStream in = inputStreamSupervisor.get(sourceFile);
		doEncryptFile(in, SourceInfo.fromFile(sourceFile), out, dataGenerator, progress, PGPLiteralData.BINARY);
		out.close();
		in.close();
	} catch (Throwable t) {
		File fileToDelete = new File(targetFile);
		if (fileToDelete.exists() && !fileToDelete.delete()) {
			log.warn("Failed to delete file after failed encryption: " + targetFile);
		}
		Throwables.throwIfInstanceOf(t, UserRequestedCancellationException.class);
		throw new RuntimeException("Encryption failed", t);
	}
}
 
源代码9 项目: cloudbreak   文件: RetryUtil.java
/**
 * Throws an appropriate exception when all attempts failed.
 *
 * @param e                 the retry exception
 * @param actionDescription a description of the action being performed
 * @throws InterruptedException if the action was interrupted
 * @throws E                    if the action timed out
 */
private static <E extends CcmException> void handleAllAttemptsFailed(
        RetryException e, String actionDescription, Class<E> exceptionClass, Supplier<E> exceptionSupplier, Logger logger) throws InterruptedException, E {
    logger.info("Failed to {}", actionDescription);
    Attempt<?> lastFailedAttempt = e.getLastFailedAttempt();
    if (lastFailedAttempt.hasException()) {
        Throwable cause = lastFailedAttempt.getExceptionCause();
        Throwables.throwIfInstanceOf(cause, exceptionClass);
        Throwables.throwIfInstanceOf(cause, InterruptedException.class);
        Throwables.throwIfUnchecked(cause);
        throw new IllegalStateException(cause);
    } else {
        throw exceptionSupplier.get();
    }
}
 
源代码10 项目: buck   文件: SmartDexingStep.java
private void runDxCommands(ExecutionContext context, Multimap<Path, Path> outputToInputs)
    throws StepFailedException, InterruptedException {
  // Invoke dx commands in parallel for maximum thread utilization.  In testing, dx revealed
  // itself to be CPU (and not I/O) bound making it a good candidate for parallelization.
  Stream<ImmutableList<Step>> dxSteps = generateDxCommands(filesystem, outputToInputs);

  ImmutableList<Callable<Unit>> callables =
      dxSteps
          .map(
              steps ->
                  (Callable<Unit>)
                      () -> {
                        for (Step step : steps) {
                          StepRunner.runStep(context, step, Optional.of(buildTarget));
                        }
                        return Unit.UNIT;
                      })
          .collect(ImmutableList.toImmutableList());

  try {
    MoreFutures.getAll(executorService, callables);
  } catch (ExecutionException e) {
    Throwable cause = e.getCause();
    Throwables.throwIfInstanceOf(cause, StepFailedException.class);

    // Programmer error.  Boo-urns.
    throw new RuntimeException(cause);
  }
}
 
源代码11 项目: bazel   文件: BuildEventServiceGrpcClient.java
@Override
public void sendOverStream(PublishBuildToolEventStreamRequest buildEvent)
    throws InterruptedException {
  throwIfInterrupted();
  try {
    stream.onNext(buildEvent);
  } catch (StatusRuntimeException e) {
    Throwables.throwIfInstanceOf(Throwables.getRootCause(e), InterruptedException.class);
    streamStatus.set(Status.fromThrowable(e));
  }
}
 
源代码12 项目: bazel   文件: CcToolchainFeatures.java
/**
 * Given a list of {@code requestedSelectables}, returns all features that are enabled by the
 * toolchain configuration.
 *
 * <p>A requested feature will not be enabled if the toolchain does not support it (which may
 * depend on other requested features).
 *
 * <p>Additional features will be enabled if the toolchain supports them and they are implied by
 * requested features.
 *
 * <p>If multiple threads call this method we may do additional work in initializing the cache.
 * This reinitialization is benign.
 */
public FeatureConfiguration getFeatureConfiguration(ImmutableSet<String> requestedSelectables)
    throws CollidingProvidesException {
  try {
    if (configurationCache == null) {
      configurationCache = buildConfigurationCache();
    }
    return configurationCache.get(requestedSelectables);
  } catch (ExecutionException e) {
    Throwables.throwIfInstanceOf(e.getCause(), CollidingProvidesException.class);
    Throwables.throwIfUnchecked(e.getCause());
    throw new IllegalStateException("Unexpected checked exception encountered", e);
  }
}
 
源代码13 项目: pgptool   文件: KeyGeneratorServicePgpImpl.java
@Override
public Key createNewKey(CreateKeyParams params) throws FieldValidationException {
	try {
		Preconditions.checkArgument(params != null, "params must not be null");
		assertParamsValid(params);

		// Create Master key
		KeyPair masterKey = getOrGenerateKeyPair(getMasterKeyParameters());
		PGPKeyPair masterKeyBc = new JcaPGPKeyPair(algorithmNameToTag(masterKeyPurpose), masterKey, new Date());
		BcPGPContentSignerBuilder keySignerBuilderBc = new BcPGPContentSignerBuilder(
				algorithmNameToTag(masterKeyPurpose), hashAlgorithmNameToTag(masterKeySignerHashingAlgorithm));

		// Setup seret key encryption
		PGPDigestCalculator digestCalc = new BcPGPDigestCalculatorProvider()
				.get(hashAlgorithmNameToTag(secretKeyHashingAlgorithm));
		BcPBESecretKeyEncryptorBuilder encryptorBuilderBC = new BcPBESecretKeyEncryptorBuilder(
				symmetricKeyAlgorithmNameToTag(secretKeyEncryptionAlgorithm), digestCalc);
		PBESecretKeyEncryptor keyEncryptorBc = encryptorBuilderBC.build(params.getPassphrase().toCharArray());

		// Key pair generator
		String userName = params.getFullName() + " <" + params.getEmail() + ">";
		PGPKeyRingGenerator keyPairGeneratorBc = new PGPKeyRingGenerator(PGPSignature.POSITIVE_CERTIFICATION,
				masterKeyBc, userName, digestCalc, null, null, keySignerBuilderBc, keyEncryptorBc);

		// Add Sub-key for encryption
		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(encryptionKeyAlgorithm, PROVIDER);
		if ("ELGAMAL".equals(encryptionKeyAlgorithm)) {
			keyPairGenerator.initialize(new DHParameterSpec(dhParamsPrimeModulus, dhParamsBaseGenerator));
		} else if ("RSA".equals(encryptionKeyAlgorithm)) {
			// Re-using master key size.
			keyPairGenerator.initialize(new RSAKeyGenParameterSpec(masterKeySize, RSAKeyGenParameterSpec.F4));
		} else {
			throw new IllegalArgumentException(
					"Hanlding of parameter creation for " + encryptionKeyAlgorithm + " is not implemented");
		}
		KeyPair encryptionSubKey = keyPairGenerator.generateKeyPair();
		PGPKeyPair encryptionSubKeyBc = new JcaPGPKeyPair(algorithmNameToTag(encryptionKeyPurpose),
				encryptionSubKey, new Date());
		keyPairGeneratorBc.addSubKey(encryptionSubKeyBc);

		// TBD-191: Also add a sub-key for signing
		// KeyPair signatureSubKey = keyPairGenerator.generateKeyPair();
		// PGPKeyPair signatureSubKeyBc = new
		// TBD-191: RSA_SIGN must not be hardcoded
		// JcaPGPKeyPair(algorithmNameToTag("RSA_SIGN"), signatureSubKey,
		// new Date());
		// keyPairGeneratorBc.addSubKey(signatureSubKeyBc);

		// building ret
		return buildKey(keyPairGeneratorBc);
	} catch (Throwable t) {
		Throwables.throwIfInstanceOf(t, FieldValidationException.class);
		throw new RuntimeException("Failed to generate key", t);
	}
}
 
源代码14 项目: bazel   文件: IncludeScanningModule.java
@Override
public void extractSwigIncludes(
    Set<Artifact> includes,
    ActionExecutionMetadata actionExecutionMetadata,
    ActionExecutionContext actionExecContext,
    Artifact source,
    ImmutableSet<Artifact> legalOutputPaths,
    ImmutableList<PathFragment> swigIncludePaths,
    Artifact grepIncludes)
    throws IOException, ExecException, InterruptedException {
  SwigIncludeScanner scanner =
      new SwigIncludeScanner(
          includePool.get(),
          spawnScannerSupplier.get(),
          cache,
          swigIncludePaths,
          env.getDirectories(),
          env.getSkyframeBuildView().getArtifactFactory(),
          env.getExecRoot(),
          useAsyncIncludeScanner);
  ImmutableMap.Builder<PathFragment, Artifact> pathToLegalOutputArtifact =
      ImmutableMap.builder();
  for (Artifact path : legalOutputPaths) {
    pathToLegalOutputArtifact.put(path.getExecPath(), path);
  }
  try {
    scanner
        .processAsync(
            source,
            ImmutableList.of(source),
            // For Swig include scanning just point to the output file in the map.
            new IncludeScanningHeaderData.Builder(
                    pathToLegalOutputArtifact.build(), /*modularHeaders=*/ ImmutableSet.of())
                .build(),
            ImmutableList.of(),
            includes,
            actionExecutionMetadata,
            actionExecContext,
            grepIncludes)
        .get();
  } catch (ExecutionException e) {
    Throwables.throwIfInstanceOf(e.getCause(), ExecException.class);
    Throwables.throwIfInstanceOf(e.getCause(), InterruptedException.class);
    if (e.getCause() instanceof IORuntimeException) {
      throw ((IORuntimeException) e.getCause()).getCauseIOException();
    }
    Throwables.throwIfUnchecked(e.getCause());
    throw new IllegalStateException(e.getCause());
  }
}
 
源代码15 项目: bazel   文件: BuildEventServiceModule.java
private void waitForBuildEventTransportsToClose(
    Map<BuildEventTransport, ListenableFuture<Void>> transportFutures,
    boolean besUploadModeIsSynchronous)
    throws AbruptExitException {
  final ScheduledExecutorService executor =
      Executors.newSingleThreadScheduledExecutor(
          new ThreadFactoryBuilder().setNameFormat("bes-notify-ui-%d").build());
  ScheduledFuture<?> waitMessageFuture = null;

  try {
    // Notify the UI handler when a transport finished closing.
    transportFutures.forEach(
        (bepTransport, closeFuture) ->
            closeFuture.addListener(
                () -> {
                  reporter.post(new BuildEventTransportClosedEvent(bepTransport));
                },
                executor));

    try (AutoProfiler p = GoogleAutoProfilerUtils.logged("waiting for BES close")) {
      Uninterruptibles.getUninterruptibly(Futures.allAsList(transportFutures.values()));
    }
  } catch (ExecutionException e) {
    // Futures.withTimeout wraps the TimeoutException in an ExecutionException when the future
    // times out.
    if (isTimeoutException(e)) {
      throw createAbruptExitException(
          e,
          "The Build Event Protocol upload timed out.",
          ExitCode.TRANSIENT_BUILD_EVENT_SERVICE_UPLOAD_ERROR,
          BuildProgress.Code.BES_UPLOAD_TIMEOUT_ERROR);
    }

    Throwables.throwIfInstanceOf(e.getCause(), AbruptExitException.class);
    throw new RuntimeException(
        String.format(
            "Unexpected Exception '%s' when closing BEP transports, this is a bug.",
            e.getCause().getMessage()));
  } finally {
    if (besUploadModeIsSynchronous) {
      cancelAndResetPendingUploads();
    }
    if (waitMessageFuture != null) {
      waitMessageFuture.cancel(/* mayInterruptIfRunning= */ true);
    }
    executor.shutdown();
  }
}
 
源代码16 项目: buck   文件: DaemonicParserState.java
@Subscribe
public void invalidateBasedOn(WatchmanPathEvent event) {
  LOG.verbose("Parser watched event %s %s", event.getKind(), event.getPath());

  filesChangedCounter.inc();

  RelPath path = event.getPath();
  AbsPath fullPath = event.getCellPath().resolve(event.getPath());

  // We only care about creation and deletion events because modified should result in a
  // rule key change.  For parsing, these are the only events we need to care about.
  if (isPathCreateOrDeleteEvent(event)) {
    try (AutoCloseableLock readLock = cellStateLock.readLock()) {
      for (DaemonicCellState state : cellPathToDaemonicState.values()) {
        try {
          Cell cell = state.getCell();
          BuildFileTree buildFiles = buildFileTrees.get(cell);

          if (fullPath.endsWith(cell.getBuckConfigView(ParserConfig.class).getBuildFileName())) {
            LOG.debug(
                "Build file %s changed, invalidating build file tree for cell %s",
                fullPath, cell);
            // If a build file has been added or removed, reconstruct the build file tree.
            buildFileTrees.invalidate(cell);
          }

          // Added or removed files can affect globs, so invalidate the package build file
          // "containing" {@code path} unless its filename matches a temp file pattern.
          if (!cell.getFilesystem().isIgnored(path)) {
            invalidateContainingBuildFile(state, cell, buildFiles, path);
          } else {
            LOG.debug(
                "Not invalidating the owning build file of %s because it is a temporary file.",
                fullPath);
          }
        } catch (ExecutionException | UncheckedExecutionException e) {
          try {
            Throwables.throwIfInstanceOf(e, BuildFileParseException.class);
            Throwables.throwIfUnchecked(e);
            throw new RuntimeException(e);
          } catch (BuildFileParseException bfpe) {
            LOG.warn("Unable to parse already parsed build file.", bfpe);
          }
        }
      }
    }
  }

  if (configurationBuildFiles.contains(fullPath) || configurationRulesDependOn(path.getPath())) {
    invalidateAllCaches();
  } else {
    invalidatePath(fullPath);
  }
}
 
源代码17 项目: bazel   文件: SkyframeExecutor.java
/**
 * Returns the configurations corresponding to the given sets of build options. Output order is
 * the same as input order.
 *
 * @throws InvalidConfigurationException if any build options produces an invalid configuration
 */
// TODO(ulfjack): Remove this legacy method after switching to the Skyframe-based implementation.
private ImmutableList<BuildConfiguration> getConfigurations(
    ExtendedEventHandler eventHandler,
    List<BuildOptions> optionsList,
    BuildOptions referenceBuildOptions,
    boolean keepGoing)
    throws InvalidConfigurationException {
  Preconditions.checkArgument(!Iterables.isEmpty(optionsList));

  // Prepare the Skyframe inputs.
  // TODO(gregce): support trimmed configs.
  ImmutableSortedSet<Class<? extends Fragment>> allFragments =
      ruleClassProvider.getConfigurationFragments().stream()
          .map(factory -> factory.creates())
          .collect(
              ImmutableSortedSet.toImmutableSortedSet(BuildConfiguration.lexicalFragmentSorter));

  PlatformMappingValue platformMappingValue =
      getPlatformMappingValue(eventHandler, referenceBuildOptions);

  ImmutableList.Builder<SkyKey> configSkyKeysBuilder = ImmutableList.builder();
  for (BuildOptions options : optionsList) {
    configSkyKeysBuilder.add(toConfigurationKey(platformMappingValue, allFragments, options));
  }

  ImmutableList<SkyKey> configSkyKeys = configSkyKeysBuilder.build();

  // Skyframe-evaluate the configurations and throw errors if any.
  EvaluationResult<SkyValue> evalResult = evaluateSkyKeys(eventHandler, configSkyKeys, keepGoing);
  if (evalResult.hasError()) {
    Map.Entry<SkyKey, ErrorInfo> firstError = Iterables.get(evalResult.errorMap().entrySet(), 0);
    ErrorInfo error = firstError.getValue();
    Throwable e = error.getException();
    // Wrap loading failed exceptions
    if (e instanceof NoSuchThingException) {
      e = new InvalidConfigurationException(e);
    } else if (e == null && !error.getCycleInfo().isEmpty()) {
      getCyclesReporter().reportCycles(error.getCycleInfo(), firstError.getKey(), eventHandler);
      e =
          new InvalidConfigurationException(
              "cannot load build configuration because of this cycle");
    }
    if (e != null) {
      Throwables.throwIfInstanceOf(e, InvalidConfigurationException.class);
    }
    throw new IllegalStateException("Unknown error during configuration creation evaluation", e);
  }

  // Prepare and return the results.
  return configSkyKeys.stream()
      .map(key -> ((BuildConfigurationValue) evalResult.get(key)).getConfiguration())
      .collect(ImmutableList.toImmutableList());
}
 
源代码18 项目: buck   文件: AsyncVersionedTargetGraphBuilder.java
@Override
@SuppressWarnings("PMD")
public TargetGraph build() throws TimeoutException, InterruptedException, VersionException {
  LOG.debug(
      "Starting version target graph transformation (nodes %d)",
      unversionedTargetGraphCreationResult.getTargetGraph().getNodes().size());
  long start = System.currentTimeMillis();

  ImmutableSet<VersionTargetGraphKey> rootKeys =
      RichStream.from(
              unversionedTargetGraphCreationResult
                  .getTargetGraph()
                  .getAll(unversionedTargetGraphCreationResult.getBuildTargets()))
          .map(ImmutableVersionTargetGraphKey::of)
          .collect(ImmutableSet.toImmutableSet());

  ImmutableMap<VersionTargetGraphKey, Future<TargetNode<?>>> results =
      asyncTransformationEngine.computeAll(rootKeys);

  // Wait for actions to complete.
  for (Future<TargetNode<?>> futures : results.values()) {
    try {
      futures.get(timeout, timeUnit);
    } catch (ExecutionException e) {
      Throwable rootCause = Throwables.getRootCause(e);
      Throwables.throwIfInstanceOf(rootCause, VersionException.class);
      Throwables.throwIfInstanceOf(rootCause, TimeoutException.class);
      Throwables.throwIfInstanceOf(rootCause, RuntimeException.class);
      throw new IllegalStateException(
          String.format("Unexpected exception: %s: %s", e.getClass(), e.getMessage()), e);
    }
  }

  asyncTransformationEngine.close();
  versionInfoAsyncTransformationEngine.close();

  long end = System.currentTimeMillis();

  VersionedTargetGraph graph = versionedTargetGraphTransformer.targetGraphBuilder.build();
  LOG.debug(
      "Finished version target graph transformation in %.2f (nodes %d, roots: %d)",
      (end - start) / 1000.0, graph.getSize(), versionedTargetGraphTransformer.roots.get());

  return graph;
}
 
源代码19 项目: bazel   文件: PackageFunction.java
/**
 * Compute the BzlLoadValue for all given keys by "inlining" the BzlLoadFunction and bypassing
 * traditional Skyframe evaluation, returning {@code null} if Skyframe deps were missing and have
 * been requested.
 */
@Nullable
private static List<BzlLoadValue> computeBzlLoadsWithInlining(
    Environment env, List<BzlLoadValue.Key> keys, BzlLoadFunction bzlLoadFunctionForInlining)
    throws InterruptedException, BzlLoadFailedException, InconsistentFilesystemException {
  List<BzlLoadValue> bzlLoads = Lists.newArrayListWithExpectedSize(keys.size());
  Exception deferredException = null;
  boolean valuesMissing = false;
  // Compute BzlLoadValue for each key, sharing the same inlining state, i.e. cache of loaded
  // modules. This ensures that each .bzl is loaded only once, regardless of diamond dependencies
  // or cache eviction. (Multiple loads of the same .bzl would screw up identity equality of some
  // Starlark symbols -- see comments in BzlLoadFunction#computeInline.)
  BzlLoadFunction.InliningState inliningState = BzlLoadFunction.InliningState.create();
  for (BzlLoadValue.Key key : keys) {
    SkyValue skyValue;
    try {
      // Will complete right away if it's already cached in inliningState.
      skyValue = bzlLoadFunctionForInlining.computeInline(key, env, inliningState);
    } catch (BzlLoadFailedException | InconsistentFilesystemException e) {
      // For determinism's sake while inlining, preserve the first exception and continue to run
      // subsequently listed loads to completion/exception, loading all transitive deps anyway.
      deferredException = MoreObjects.firstNonNull(deferredException, e);
      continue;
    }
    if (skyValue == null) {
      checkState(env.valuesMissing(), "no starlark load value for %s", key);
      // We continue making inline calls even if some requested values are missing, to
      // maximize the number of dependent (non-inlined) SkyFunctions that are requested, thus
      // avoiding a quadratic number of restarts.
      valuesMissing = true;
    } else {
      bzlLoads.add((BzlLoadValue) skyValue);
    }
  }
  if (deferredException != null) {
    Throwables.throwIfInstanceOf(deferredException, BzlLoadFailedException.class);
    Throwables.throwIfInstanceOf(deferredException, InconsistentFilesystemException.class);
    throw new IllegalStateException(
        "caught a checked exception of unexpected type", deferredException);
  }
  return valuesMissing ? null : bzlLoads;
}
 
源代码20 项目: buck   文件: MoreThrowables.java
/**
 * Traverse exception chain by recursively calling {@code getCause()} and throws it if initial
 * exception (the one at the bottom of the stack) is an instance of {@code declaredType}.
 * Example usage:
 *
 * <pre>
 *   try {
 *     future.get()
 *   } catch (ExecutionException) {
 *     MoreThrowables.throwIfInitialCauseInstanceOf(t, BarException.class);
 *   }
 */
public static <X extends Throwable> void throwIfInitialCauseInstanceOf(
    Throwable throwable, Class<X> declaredType) throws X {
  Throwable cause = getInitialCause(throwable);
  Throwables.throwIfInstanceOf(cause, declaredType);
}