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

The following examples show how to use com.google.common.base.Throwables#throwIfUnchecked() . 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: AbstractMemoizer.java    From buck with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example 2
Source File: DnsNameResolver.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 3
Source File: DefaultReentrantTypeResolver.java    From xtext-extras with Eclipse Public License 2.0 6 votes vote down vote up
@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();
	}
}
 
Example 4
Source File: EntityAdapter.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 5
Source File: GitUtils.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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);
	}
}
 
Example 6
Source File: DriverCommandExecutor.java    From selenium with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
    }
  }
}
 
Example 7
Source File: TemplateHelperImpl.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
@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);
  }
}
 
Example 8
Source File: ConnectListener.java    From FastLogin with MIT License 6 votes vote down vote up
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);
    }
}
 
Example 9
Source File: LogbackLoggerOverrides.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public synchronized void save() {
  log.debug("Save");

  try {
    write(file, loggerLevels);
  }
  catch (Exception e) {
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
}
 
Example 10
Source File: PublisherHandler.java    From styx with Apache License 2.0 5 votes vote down vote up
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);
    }
  };
}
 
Example 11
Source File: KnownRuleTypesProvider.java    From buck with Apache License 2.0 5 votes vote down vote up
/** 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;
  }
}
 
Example 12
Source File: JobDataClientUtils.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 13
Source File: Jsr199JavacInvocation.java    From buck with Apache License 2.0 5 votes vote down vote up
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());
  }
}
 
Example 14
Source File: UpgradeServiceImpl.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
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);
    }
  };
}
 
Example 15
Source File: Operations.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
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);
    }
  }
 
Example 16
Source File: SchedulerTest.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
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);
  }
}
 
Example 17
Source File: KnownRuleTypesProvider.java    From buck with Apache License 2.0 5 votes vote down vote up
/** 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;
  }
}
 
Example 18
Source File: CompletionListener.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
  }
}
 
Example 19
Source File: MoreFutures.java    From buck with Apache License 2.0 4 votes vote down vote up
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());
  }
}
 
Example 20
Source File: WrappedRunnable.java    From incubator-iotdb with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("squid:S112")
private static RuntimeException propagate(Throwable throwable) {
  Throwables.throwIfUnchecked(throwable);
  throw new RuntimeException(throwable);
}