下面列出了com.google.common.base.Throwables#throwIfUnchecked ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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();
}
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);
}
}
@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);
}
}
/**
* 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();
}
}
}
/**
* 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);
}
}
/**
* 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();
}
}
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);
}
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);
}
}
/**
* 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);
}
}
/** 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;
}
}
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);
}
};
}
@Override
public synchronized void save() {
log.debug("Save");
try {
write(file, loggerLevels);
}
catch (Exception e) {
Throwables.throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
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());
}
}
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);
}
};
}
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);
}
}
/** 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;
}
}
/**
* 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);
}
}
@SuppressWarnings("squid:S112")
private static RuntimeException propagate(Throwable throwable) {
Throwables.throwIfUnchecked(throwable);
throw new RuntimeException(throwable);
}
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());
}
}