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

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

源代码1 项目: buck   文件: AbstractMemoizer.java
/**
 * Get the value and memoize the result. Constructs the value if it hasn't been memoized before,
 * or if the previously memoized value has been collected.
 *
 * @param delegate delegate for constructing the value
 * @return the value
 */
public T get(ThrowingSupplier<T, E> delegate, Class<E> exceptionClass) throws E {
  if (value == null) {
    synchronized (this) {
      if (value == null) {
        try {
          T t = Preconditions.checkNotNull(delegate.get());
          value = Either.ofLeft(t);
          return t;
        } catch (Exception e) {
          if (exceptionClass.isInstance(e)) {
            value = Either.ofRight(exceptionClass.cast(e));
            Throwables.throwIfInstanceOf(e, exceptionClass);
          }
          Throwables.throwIfUnchecked(e);
          throw new IllegalStateException(e);
        }
      }
    }
  }
  if (value.isLeft()) {
    return value.getLeft();
  }
  throw value.getRight();
}
 
源代码2 项目: FastLogin   文件: ConnectListener.java
private void setOfflineId(InitialHandler connection, String username) {
    try {
        final UUID oldPremiumId = connection.getUniqueId();
        final UUID offlineUUID = UUIDAdapter.generateOfflineId(username);

        // BungeeCord only allows setting the UUID in PreLogin events and before requesting online mode
        // However if online mode is requested, it will override previous values
        // So we have to do it with reflection
        uniqueIdSetter.invokeExact(connection, offlineUUID);

        String format = "Overridden UUID from {} to {} (based of {}) on {}";
        plugin.getLog().info(format, oldPremiumId, offlineUUID, username, connection);
    } catch (Exception ex) {
        plugin.getLog().error("Failed to set offline uuid of {}", username, ex);
    } catch (Throwable throwable) {
        // throw remaining exceptions like outofmemory that we shouldn't handle ourself
        Throwables.throwIfUnchecked(throwable);
    }
}
 
源代码3 项目: nexus-public   文件: TemplateHelperImpl.java
@Override
public String render(final URL template, final TemplateParameters parameters) {
  checkNotNull(template);
  checkNotNull(parameters);

  log.trace("Rendering template: {} w/params: {}", template, parameters);

  try (Reader input = new InputStreamReader(template.openStream(), StandardCharsets.UTF_8)) {
    StringWriter buff = new StringWriter();
    velocityEngine.evaluate(new VelocityContext(parameters.get()), buff, template.getFile(), input);

    String result = buff.toString();
    log.trace("Result: {}", result);

    return result;
  }
  catch (Exception e) {
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
}
 
源代码4 项目: selenium   文件: DriverCommandExecutor.java
/**
 * Sends the {@code command} to the driver server for execution. The server will be started
 * if requesting a new session. Likewise, if terminating a session, the server will be shutdown
 * once a response is received.
 *
 * @param command The command to execute.
 * @return The command response.
 * @throws IOException If an I/O error occurs while sending the command.
 */
@Override
public Response execute(Command command) throws IOException {
  if (DriverCommand.NEW_SESSION.equals(command.getName())) {
    service.start();
  }

  try {
    return super.execute(command);
  } catch (Throwable t) {
    Throwable rootCause = Throwables.getRootCause(t);
    if (rootCause instanceof ConnectException &&
        "Connection refused".equals(rootCause.getMessage()) &&
        !service.isRunning()) {
      throw new WebDriverException("The driver server has unexpectedly died!", t);
    }
    Throwables.throwIfUnchecked(t);
    throw new WebDriverException(t);
  } finally {
    if (DriverCommand.QUIT.equals(command.getName())) {
      service.stop();
    }
  }
}
 
源代码5 项目: n4js   文件: GitUtils.java
/**
 * Initialize the submodules with the given repository-relative <code>submodulePaths</code> inside the Git
 * repository at the given clone path. Throws exceptions in case of error.
 *
 * @param submodulePaths
 *            repository-relative paths of the submodules to initialized; if empty, all submodules will be
 *            initialized.
 */
public static void initSubmodules(final Path localClonePath, final Iterable<String> submodulePaths) {

	if (!isValidLocalClonePath(localClonePath)) {
		throw new IllegalArgumentException("invalid localClonePath: " + localClonePath);
	}

	try (final Git git = open(localClonePath.toFile())) {
		final SubmoduleInitCommand cmd = git.submoduleInit();
		for (String submodulePath : submodulePaths) {
			cmd.addPath(submodulePath);
		}
		cmd.call();
	} catch (Exception e) {
		LOGGER.error(e.getClass().getSimpleName()
				+ " while trying to initialize submodules " + Iterables.toString(submodulePaths)
				+ " of repository '" + localClonePath
				+ "':" + e.getLocalizedMessage());
		Throwables.throwIfUnchecked(e);
		throw new RuntimeException(e);
	}
}
 
源代码6 项目: nexus-public   文件: EntityAdapter.java
/**
 * Read entity from document.
 */
public T readEntity(final OIdentifiable identifiable) {
  ODocument document = identifiable.getRecord(); // no-op if it's already a document
  checkNotNull(document);

  T entity = newEntity();
  if (!partialLoading) {
    document.deserializeFields();
  }
  try {
    readFields(document, entity);
  }
  catch (Exception e) {
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
  attachMetadata(entity, document);

  return entity;
}
 
@Override
public IResolvedTypes reentrantResolve(CancelIndicator monitor) {
	if (resolving) {
		throw new UnsupportedOperationException("TODO: import a functional handle on the type resolution that delegates to the best available (current, but evolving) result");
	}
	StoppedTask task = Stopwatches.forTask("DefaultReentrantTypeResolver.resolve");
	try {
		task.start();
		resolving = true;
		return resolve(monitor);
	} catch(Throwable e) {
		clear();
		if (operationCanceledManager.isOperationCanceledException(e)) {
			operationCanceledManager.propagateAsErrorIfCancelException(e);
		}
		Throwables.throwIfUnchecked(e);
		throw new RuntimeException(e);
	} finally {
		resolving = false;
		task.stop();
	}
}
 
源代码8 项目: grpc-java   文件: DnsNameResolver.java
private List<EquivalentAddressGroup> resolveAddresses() {
  List<? extends InetAddress> addresses;
  Exception addressesException = null;
  try {
    addresses = addressResolver.resolveAddress(host);
  } catch (Exception e) {
    addressesException = e;
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  } finally {
    if (addressesException != null) {
      logger.log(Level.FINE, "Address resolution failure", addressesException);
    }
  }
  // Each address forms an EAG
  List<EquivalentAddressGroup> servers = new ArrayList<>(addresses.size());
  for (InetAddress inetAddr : addresses) {
    servers.add(new EquivalentAddressGroup(new InetSocketAddress(inetAddr, port)));
  }
  return Collections.unmodifiableList(servers);
}
 
源代码9 项目: nexus-public   文件: SchedulerTest.java
protected Scheduler createScheduler(String name, int threadPoolSize) throws SchedulerException {
  try {
    this.taskSchedulerHelper = new TaskSchedulerHelper(database.getInstance());
    this.taskSchedulerHelper.init(threadPoolSize, new SimpleJobFactory());
    this.taskSchedulerHelper.start();
    return ((QuartzSchedulerSPI) taskSchedulerHelper.getScheduler()).getScheduler();
  }
  catch (Exception e) {
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
}
 
源代码10 项目: dremio-oss   文件: JobDataClientUtils.java
/**
 * Wait for BatchSchema (Query Metadata) to be retrievable via JobDetails. Use this
 * method sparingly, prefer reusing the listener from Job submission instead.
 */
public static void waitForBatchSchema(JobsService jobsService, final JobId jobId) {
  final SettableFuture<Void> settableFuture = SettableFuture.create();

  jobsService.getJobsClient()
    .getAsyncStub()
    .subscribeToJobEvents(JobsProtoUtil.toBuf(jobId), new StreamObserver<JobEvent>() {
      @Override
      public void onNext(JobEvent value) {
        if (value.hasQueryMetadata() || value.hasFinalJobSummary()) {
          settableFuture.set(null);
        }
      }

      @Override
      public void onError(Throwable t) {
        settableFuture.setException(t);
      }

      @Override
      public void onCompleted() {

      }
    });

  try {
    settableFuture.get();
  } catch (Exception e) {
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
}
 
源代码11 项目: buck   文件: KnownRuleTypesProvider.java
/** Returns {@link KnownRuleTypes} for a given {@link Cell}. */
public KnownRuleTypes get(Cell cell) {
  try {
    return typesCache.getUnchecked(cell);
  } catch (UncheckedExecutionException e) {
    Throwables.throwIfUnchecked(e.getCause());
    throw e;
  }
}
 
源代码12 项目: styx   文件: PublisherHandler.java
private Callable<Void> meteredPublishing(Try.CheckedRunnable f, Stats stats, String type, String state) {
  return () -> {
    try {
      f.run();
      stats.recordPublishing(type, state);
      return null;
    } catch (Throwable e) {
      stats.recordPublishingError(type, state);
      LOG.warn("Failed to publish event for {} state", state, e);
      Throwables.throwIfUnchecked(e);
      throw new RuntimeException(e);
    }
  };
}
 
源代码13 项目: nexus-public   文件: LogbackLoggerOverrides.java
@Override
public synchronized void save() {
  log.debug("Save");

  try {
    write(file, loggerLevels);
  }
  catch (Exception e) {
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
}
 
源代码14 项目: buck   文件: Jsr199JavacInvocation.java
public int buildClasses() throws InterruptedException {
  shouldCompileFullJar.set(true);
  try {
    String threadName = startCompiler(getJavacTask(false));
    try (JavacEventSinkScopedSimplePerfEvent event =
        new JavacEventSinkScopedSimplePerfEvent(context.getEventSink(), threadName)) {
      return compilerResult.get();
    }
  } catch (ExecutionException e) {
    Throwables.throwIfUnchecked(e.getCause());
    throw new HumanReadableException("Failed to compile: %s", e.getCause().getMessage());
  }
}
 
源代码15 项目: nexus-public   文件: UpgradeServiceImpl.java
private Consumer<Checkpoint> begin() {
  return checkpoint -> {
    String model = upgradeManager.getModel(checkpoint);
    try {
      log.info("Checkpoint {}", model);
      checkpoint.begin(modelVersions.getOrDefault(model, "1.0"));
    }
    catch (Throwable e) {
      log.warn("Problem checkpointing {}", model, e);
      Throwables.throwIfUnchecked(e);
      throw new RuntimeException(e);
    }
  };
}
 
源代码16 项目: nexus-public   文件: Operations.java
private <T> T proceedWithTransaction(final OperationPoint<T, E> point, final Transaction tx) throws E {

    log.trace("Invoking: {} -> {}", spec, point);

    try {
      return (T) new TransactionalWrapper(spec, point).proceedWithTransaction(tx);
    }
    catch (final Throwable e) {
      if (throwing != null) {
        Throwables.propagateIfPossible(e, throwing);
      }
      Throwables.throwIfUnchecked(e);
      throw new RuntimeException(e);
    }
  }
 
源代码17 项目: buck   文件: KnownRuleTypesProvider.java
/** Get details for just rules implemented in Buck itself, rather than user defined rules */
public KnownNativeRuleTypes getNativeRuleTypes(Cell cell) {
  try {
    return nativeTypesCache.getUnchecked(cell);
  } catch (UncheckedExecutionException e) {
    Throwables.throwIfUnchecked(e.getCause());
    throw e;
  }
}
 
源代码18 项目: dremio-oss   文件: CompletionListener.java
/**
 * blocks until the job finishes successfully or not
 * if job failed with a checked exception, throws the exception wrapped into RuntimeException
 */
public void awaitUnchecked() {
  try {
    await();
  } catch (Exception e) {
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
}
 
源代码19 项目: incubator-iotdb   文件: WrappedRunnable.java
@SuppressWarnings("squid:S112")
private static RuntimeException propagate(Throwable throwable) {
  Throwables.throwIfUnchecked(throwable);
  throw new RuntimeException(throwable);
}
 
源代码20 项目: buck   文件: MoreFutures.java
public static <X extends Throwable> void propagateCauseIfInstanceOf(Throwable e, Class<X> type) {
  if (e.getCause() != null && type.isInstance(e)) {
    Throwables.throwIfUnchecked(e.getCause());
    throw new RuntimeException(e.getCause());
  }
}