下面列出了怎么用com.google.common.base.Throwables的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Statement apply(Statement statement) throws Throwable {
return () -> {
Clock clock = new SystemClock();
long end = clock.laterBy(timeout.in(TimeUnit.MILLISECONDS));
Throwable lastException;
do {
try {
return statement.evaluate();
} catch (Throwable e) {
lastException = e;
if (ignoring.stream().anyMatch(clazz -> clazz.isInstance(e))) {
try {
Thread.sleep(polling.in(TimeUnit.MILLISECONDS));
} catch (InterruptedException i) {
break;
}
} else {
Throwables.propagate(e);
}
}
} while ((clock.isNowBefore(end)));
throw lastException;
};
}
@Test
public void testWriteSession$completed$saveChanges(@Mocked final WriteSession nativeSession) throws Exception {
new Expectations() {{
delegate.createSession();result=nativeSession;
}};
ApplicationContext sut = createContext();
WriteSession session = sut.createSession();
session.saveChanges();
try {
session.saveChanges();
fail("Session should not save changes after being completed");
} catch (Exception e) {
assertThat(Throwables.getRootCause(e),instanceOf(IllegalStateException.class));
} finally {
session.close();
}
verifySessionUsage(nativeSession);
}
private String parseMessage(final HttpCommand command, final HttpResponse response) {
if (response.getPayload() != null) {
try {
return Strings2.toStringAndClose(response.getPayload().openStream());
} catch (IOException e) {
throw Throwables.propagate(e);
}
} else {
final String errorMessage = response.getFirstHeaderOrNull("X-Error");
return new StringBuffer(command.getCurrentRequest().getRequestLine())
.append(" -> ")
.append(response.getStatusLine())
.append(" -> ")
.append(errorMessage != null ? errorMessage : "")
.toString();
}
}
public byte[] getContent() {
synchronized (mutex) {
if (content == null) {
InputStream in = null;
try {
in = response.getEntity().getContent();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteStreams.copy(in, out);
content = out.toByteArray();
} catch (IOException e) {
throw Throwables.propagate(e);
} finally {
Streams.closeQuietly(in);
}
}
}
return content;
}
private static void verifySingleGetterExecution(IMethodExecutor executor, Field targetField) {
final IPropertyCallback target = mock(SingleCallbackSource.class);
final IConverter converter = mock(IConverter.class);
final IMethodCall call = executor.startCall(target);
call.setEnv(Constants.ARG_CONVERTER, converter);
final Value markerValue = new Value();
when(target.getField(any(Field.class))).thenReturn(markerValue);
final ConvertedValue markerConvertedValue = new ConvertedValue();
when(converter.fromJava(any())).thenReturn(markerConvertedValue);
try {
final Object[] result = call.call();
Assert.assertArrayEquals(new Object[] { markerConvertedValue }, result);
} catch (Exception e) {
throw Throwables.propagate(e);
}
verify(target).getField(targetField);
verify(converter).fromJava(markerValue);
}
private ClassLoader buildPluginClassLoader(List<ArtifactResult> artifactResults)
{
ImmutableList.Builder<URL> urls = ImmutableList.builder();
for (ArtifactResult artifactResult : artifactResults) {
URL url;
try {
url = artifactResult.getArtifact().getFile().toPath().toUri().toURL();
}
catch (MalformedURLException ex) {
throw Throwables.propagate(ex);
}
urls.add(url);
}
return new PluginClassLoader(urls.build(), RemotePluginLoader.class.getClassLoader(),
PARENT_FIRST_PACKAGES, PARENT_FIRST_RESOURCES);
}
public final Object watch(Map<String, Object> params) {
try {
if (cacheTime == null) {
cacheTime = getCacheTime();
}
if (isCacheNotEnable()) {
return doMonitor(params);
} else {
String key = buildKey(params);
Object result = MetricsCache.INSTANCE.get(key);
if (result == null) {
result = doMonitor(params);
if (result == null) {
result = Constants.NULL;
}
MetricsCache.INSTANCE.put(key, result, cacheTime.getCacheTime());
return result;
} else {
return result;
}
}
} catch (Throwable throwable) {
throw Throwables.propagate(throwable);
}
}
private static TrustManager createTrustManager(ClientConfig config) {
Preconditions.checkNotNull(config.getSSLTrustStoreLocation(),
"Could not create TrustManager, No SSL trust store provided");
//trust store
String trustStoreType = config.getSslTrustStoreType();
if (StringUtils.isEmpty(trustStoreType)) {
trustStoreType = DEFAULT_TRUST_STORE_TYPE;
}
String trustStoreLocation = config.getSSLTrustStoreLocation();
Preconditions.checkArgument(StringUtils.isNotEmpty(trustStoreLocation),
"Trust store location not provided");
String trustStorePassword = config.getSSLTrustStorePassword();
Preconditions.checkArgument(StringUtils.isNotEmpty(trustStorePassword),
"Trust store password not provided");
try {
return loadTrustManager(trustStoreType,
trustStoreLocation,
trustStorePassword);
} catch (IOException | GeneralSecurityException e) {
throw Throwables.propagate(e);
}
}
@Test
public void lookupShouldBeRunnable() throws Exception {
final Future<TableId> future = FloRunner.runTask(BigQueryTasks.lookup(
"non-existent-project", "non-existent-dataset", "non-existent-table")).future();
try {
future.get();
fail("Did not expect to find a non-existent table");
} catch (ExecutionException e) {
// Verify that we are getting some well known error here so we know with some
// certainty that we didn't get a serialization error. Yes, this is quite awful.
final Throwable rootCause = Throwables.getRootCause(e);
if (rootCause instanceof NotReady) {
// Seems we had working credentials and the lookup worked. We're done here.
} else if (rootCause instanceof GoogleJsonResponseException) {
// Seems we managed to make a request, so the lookup executed. We're done here.
} else if (rootCause instanceof IllegalArgumentException &&
rootCause.getMessage().startsWith("A project ID is required")) {
// Seems we managed to get as far as trying to instantiate the BigQuery client (in the task process).
// We're done here.
} else {
// Not sure what went wrong here, might be serialization error, so be conservative and fail here.
throw e;
}
}
}
/**
* Runs a Supplier within the context of a specified ClassLoader and in priviledged mode.
*
* @param classLoader the ClassLoader to run the Supplier.
* @param e1 Exception class that should be propagated as-is
* @param e2 Exception class that should be propagated as-is
* @param supplier the Supplier to run within the context of a specified ClassLoader.
*/
public static <T, E1 extends Exception, E2 extends Exception> T privilegedWithClassLoader(
ClassLoader classLoader,
Class<E1> e1,
Class<E2> e2,
ExceptionSupplier<T> supplier
) throws E1, E2 {
try {
return AccessController.doPrivileged((PrivilegedExceptionAction<T>) () -> withClassLoaderInternal(classLoader, supplier));
} catch (PrivilegedActionException e) {
Throwables.propagateIfPossible(e.getCause(), e1, e2);
Throwables.propagate(e);
}
return null;
}
public synchronized void recoverState() {
try {
TransactionSnapshot lastSnapshot = persistor.getLatestSnapshot();
// if we failed before a snapshot could complete, we might not have one to restore
if (lastSnapshot != null) {
restoreSnapshot(lastSnapshot);
}
// replay any WALs since the last snapshot
Collection<TransactionLog> logs = persistor.getLogsSince(lastSnapshotTime);
if (logs != null) {
replayLogs(logs);
}
} catch (IOException e) {
LOG.error("Unable to read back transaction state:", e);
throw Throwables.propagate(e);
}
}
@Override
public final void awaitQuiescence(boolean interruptWorkers) throws InterruptedException {
Throwables.propagateIfPossible(catastrophe);
try {
synchronized (zeroRemainingTasks) {
while (remainingTasks.get() != 0 && !jobsMustBeStopped) {
zeroRemainingTasks.wait();
}
}
} catch (InterruptedException e) {
// Mark the visitor, so that it's known to be interrupted, and
// then break out of here, stop the worker threads and return ASAP,
// sending the interruption to the parent thread.
setInterrupted();
}
awaitTermination(interruptWorkers);
}
private Model setupModel() {
// Prevent INFO messages from polluting the log.
Logger.getLogger("").setLevel(Level.WARNING);
try {
serviceConfig = generateServiceConfig();
} catch (IOException e) {
getDiagCollector().addDiag(Diag.error(SimpleLocation.TOPLEVEL,
"Unexpected exception:%n%s", Throwables.getStackTraceAsString(e)));
}
model = Model.create(serviceConfig);
onErrorsExit();
// Register standard processors.
StandardSetup.registerStandardProcessors(model);
// Register standard config aspects.
StandardSetup.registerStandardConfigAspects(model);
return model;
}
private void startThriftServer(Configuration conf, BookKeeper bookKeeper)
{
processor = new BookKeeperService.Processor(bookKeeper);
log.info("Starting BookKeeperServer on port " + getBookKeeperServerPort(conf));
try {
TServerTransport serverTransport = new TServerSocket(
new TServerSocket.ServerSocketTransportArgs().bindAddr(new InetSocketAddress(getBookKeeperServerPort(conf))).backlog(Integer.MAX_VALUE));
server = new TThreadPoolServer(new TThreadPoolServer
.Args(serverTransport)
.processor(processor)
.maxWorkerThreads(getServerMaxThreads(conf)));
server.serve();
}
catch (TTransportException e) {
log.error(Throwables.getStackTraceAsString(e));
}
}
@Override
public BrooklynPropertiesImpl addFrom(InputStream i) {
// Ugly way to load them in order, but Properties is a Hashtable so loses order otherwise.
@SuppressWarnings({ "serial" })
Properties p = new Properties() {
@Override
public synchronized Object put(Object key, Object value) {
// Trim the string values to remove leading and trailing spaces
String s = (String) value;
if (Strings.isBlank(s)) {
s = Strings.EMPTY;
} else {
s = CharMatcher.BREAKING_WHITESPACE.trimFrom(s);
}
return BrooklynPropertiesImpl.this.put(key, s);
}
};
try {
p.load(i);
} catch (IOException e) {
throw Throwables.propagate(e);
}
return this;
}
/**
* Loads configuration from a specified path. If not absolute, will look in
* the user home directory, the current classpath and the system classpath.
* Absolute classpath references will not work.
*
* @param path the path to try first as a resource, then as a file
* @throws ConfigurationLoadException if the configuration could not be
* loaded.
* @returns properties loaded from the specified path or null.
*/
public Configuration fromFile(String path) throws ConfigurationLoadException {
PropertiesConfiguration propertiesConfiguration =
setupConfiguration(new PropertiesConfiguration());
propertiesConfiguration.setFileName(path);
try {
propertiesConfiguration.load();
} catch (ConfigurationException e) {
if (Throwables.getRootCause(e) instanceof AccessControlException){
AdsServiceLoggers.ADS_API_LIB_LOG.debug("Properties could not be loaded.", e);
} else {
throw new ConfigurationLoadException(
"Encountered a problem reading the provided configuration file \"" + path + "\"!", e);
}
}
return propertiesConfiguration;
}
private SecretKey createKey(byte[] initializationBytes) {
try {
// Create the encryption key from a SecureRandom seeded with the secret SEED value and initialization bytes.
// This way different initialization values will generate different keys.
SecureRandom random = SecureRandom.getInstance(SEED_PRNG);
random.setSeed(BaseEncoding.base64().decode(SEED));
random.setSeed(initializationBytes);
byte[] keyBytes = new byte[16];
random.nextBytes(keyBytes);
return new SecretKeySpec(keyBytes, ALGORITHM);
} catch (NoSuchAlgorithmException e) {
// This shouldn't happen since SHA1PRNG is supported by all JVMs.
throw Throwables.propagate(e);
}
}
private void dummyRead(final long initPos, final byte[] buffer, final int offset, final int length)
{
final long initNextReadBlock = initPos / blockSize;
readService.execute(new Runnable()
{
@Override
public void run()
{
try {
long endBlock = ((initPos + (length - 1)) / blockSize) + 1;
final List<ReadRequestChain> readRequestChains = setupReadRequestChains(buffer, offset, endBlock, length,
initPos, initNextReadBlock);
updateCacheAndStats(readRequestChains);
}
catch (IOException e) {
throw Throwables.propagate(e);
}
}
});
}
@Override
public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
BlockingQueue<Runnable> queue = executor.getQueue();
while (true) {
if (executor.isShutdown()) {
throw new RejectedExecutionException("ThreadPoolExecutor has shut down");
}
try {
if (queue.offer(task, 300, TimeUnit.MILLISECONDS)) {
break;
}
}
catch (InterruptedException e) {
throw Throwables.propagate(e);
}
}
}
private void init(boolean enableEventRecording)
{
setupWsClient();
setupRecording(enableEventRecording);
setupStringCodecs();
try {
Path file = new Path(this.vars.appPath);
URI uri = file.toUri();
Configuration config = new YarnConfiguration();
fileContext = uri.getScheme() == null ? FileContext.getFileContext(config) : FileContext.getFileContext(uri, config);
saveMetaInfo();
String fileName = String.format(CONTAINERS_INFO_FILENAME_FORMAT, plan.getLogicalPlan().getValue(LogicalPlan.APPLICATION_ATTEMPT_ID));
this.containerFile = new FSJsonLineFile(fileContext, new Path(this.vars.appPath, fileName), FsPermission.getDefault());
this.containerFile.append(getAppMasterContainerInfo());
fileName = String.format(OPERATORS_INFO_FILENAME_FORMAT, plan.getLogicalPlan().getValue(LogicalPlan.APPLICATION_ATTEMPT_ID));
this.operatorFile = new FSJsonLineFile(fileContext, new Path(this.vars.appPath, fileName), FsPermission.getDefault());
} catch (IOException ex) {
throw Throwables.propagate(ex);
}
}
/**
* Obtain information about all submodules of the Git repository at the given path. Returns an empty map in case the
* repository does not include submodules. Throws exceptions in case of error.
*/
public static Map<String, SubmoduleStatus> getSubmodules(final Path localClonePath) {
if (!isValidLocalClonePath(localClonePath)) {
throw new IllegalArgumentException("invalid localClonePath: " + localClonePath);
}
try (final Git git = open(localClonePath.toFile())) {
return git.submoduleStatus().call();
} catch (Exception e) {
LOGGER.error(e.getClass().getSimpleName()
+ " while trying to obtain status of all submodules"
+ " of repository '" + localClonePath
+ "':" + e.getLocalizedMessage());
Throwables.throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
/**
* This is the main method takes SQL statement as input and contructs a DAG using contructs registered with this
* {@link SQLExecEnvironment}.
*
* @param sql SQL statement that should be converted to a DAG.
*/
public void executeSQL(DAG dag, String sql)
{
FrameworkConfig config = buildFrameWorkConfig();
Planner planner = Frameworks.getPlanner(config);
try {
logger.info("Parsing SQL statement: {}", sql);
SqlNode parsedTree = planner.parse(sql);
SqlNode validatedTree = planner.validate(parsedTree);
RelNode relationalTree = planner.rel(validatedTree).rel;
logger.info("RelNode relationalTree generate from SQL statement is:\n {}",
Util.toLinux(RelOptUtil.toString(relationalTree)));
RelNodeVisitor visitor = new RelNodeVisitor(dag, typeFactory);
visitor.traverse(relationalTree);
} catch (Exception e) {
throw Throwables.propagate(e);
} finally {
planner.close();
}
}
@Override
public SSLContext getSSLContext() {
SSLContext _sslcontext = this.sslcontext; // local variable allows concurrent removeTrustCertificate
if (_sslcontext == null) {
try {
// the trusted key store may have asychronously changed when NXRM is clustered, reload the managed store used
// for fallback so the context doesn't use stale key store
this.managedTrustManager = getManagedTrustManager(keyStoreManager);
_sslcontext = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
_sslcontext.init(keyManagers, trustManagers, DEFAULT_RANDOM);
this.sslcontext = _sslcontext;
}
catch (Exception e) {
log.debug("Could not create SSL context", e);
Throwables.throwIfUnchecked(e);
throw new RuntimeException(e);
}
}
return _sslcontext;
}
@Test
public void testUnboundedRangeIsRejected() {
try {
final Restriction ageRestrictionInt = doInJPA(new JPATransactionFunction<Restriction>() {
@Override
public Restriction apply(EntityManager entityManager) {
Restriction restriction = new Restriction();
restriction.setRangeInt(Ranges.<Integer>all());
entityManager.persist(restriction);
return restriction;
}
});
fail("An unbounded range should throw an exception!");
} catch (Exception e) {
Throwable rootCause = Throwables.getRootCause(e);
assertTrue(rootCause instanceof IllegalArgumentException);
assertTrue(rootCause.getMessage().contains("doesn't have any upper or lower bound!"));
}
}
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);
}
}
@Test
public void testChecksumDataError()
{
CuratorOp op1 = client.transactionOp().create().forPath("/test");
CuratorOp op2 = client.transactionOp().create().forPath("/test/bar", "first".getBytes());
Migration migration = () -> Arrays.asList(op1, op2);
MigrationSet migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
complete(manager.migrate(migrationSet));
CuratorOp op2Changed = client.transactionOp().create().forPath("/test/bar", "second".getBytes());
migration = () -> Arrays.asList(op1, op2Changed);
migrationSet = MigrationSet.build("1", Collections.singletonList(migration));
try
{
complete(manager.migrate(migrationSet));
Assert.fail("Should throw");
}
catch ( Throwable e )
{
Assert.assertTrue(Throwables.getRootCause(e) instanceof MigrationException);
}
}
/** Terminates connection upon outbound exception. */
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
throws Exception {
promise.addListener(
(ChannelFuture channelFuture) -> {
if (!channelFuture.isSuccess()) {
Throwable cause = channelFuture.cause();
if (NON_FATAL_OUTBOUND_EXCEPTIONS.contains(Throwables.getRootCause(cause).getClass())) {
logger.atWarning().withCause(channelFuture.cause()).log(
"Outbound exception caught for channel %s", channelFuture.channel());
} else {
logger.atSevere().withCause(channelFuture.cause()).log(
"Outbound exception caught for channel %s", channelFuture.channel());
}
ChannelFuture unusedFuture = channelFuture.channel().close();
}
});
super.write(ctx, msg, promise);
}
private void throwIfNotValidationException(Throwable original, Throwable alternativeCause) {
Throwable cause = original.getCause();
if (original instanceof ValidationException || cause instanceof ValidationException) {
// fine... already parsed
log.trace("swallowing {}", cause);
} else {
Throwables.propagateIfPossible(alternativeCause);
throw new ApplicationLogicException(alternativeCause);
}
}
public static void writeValue(Writer writer, Object obj) {
try {
objectMapper.writeValue(writer, obj);
} catch (IOException e) {
Throwables.propagateIfPossible(e);
}
}
private byte[] gcm(boolean encrypt, byte[] input, byte[] nonce) throws AEADBadTagException {
try {
Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
SecretKey secretKey = new SecretKeySpec(key, KEY_ALGORITHM);
GCMParameterSpec gcmParameters = new GCMParameterSpec(TAG_BITS, nonce);
cipher.init(encrypt ? ENCRYPT_MODE : DECRYPT_MODE, secretKey, gcmParameters);
return cipher.doFinal(input);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException | InvalidKeyException e) {
Throwables.propagateIfInstanceOf(e, AEADBadTagException.class);
throw Throwables.propagate(e);
}
}