下面列出了com.google.common.base.Throwables#getCausalChain ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private RuntimeException handleException(final RuntimeException e) {
//
// On table creation, hive metastore validates the table location.
// On iceberg table get and update, the iceberg method uses the metadata location.
// On both occasions, FileSystem uses a relevant file system based on the location scheme. Noticed an error
// where the s3 client's pool closed abruptly. This causes subsequent request to the s3 client to fail.
// FileSystem caches the file system instances.
// The fix is to clear the FileSystem cache so that it can recreate the file system instances.
//
for (Throwable ex : Throwables.getCausalChain(e)) {
if (ex instanceof IllegalStateException && ex.getMessage().contains("Connection pool shut down")) {
log.warn("File system connection pool is down. It will be restarted.");
registry.counter(HiveMetrics.CounterHiveFileSystemFailure.getMetricName()).increment();
try {
FileSystem.closeAll();
} catch (Exception fe) {
log.warn("Failed closing the file system.", fe);
}
Throwables.propagate(ex);
}
}
throw e;
}
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
Deadline.registerIfNot(timeout);
try {
Deadline.startTimer(method.getName());
final Object object = method.invoke(metacatHMSHandler, args);
Deadline.stopTimer();
return object;
} catch (InvocationTargetException e) {
for (Throwable ex : Throwables.getCausalChain(e)) {
if (ex instanceof JDODataStoreException) {
throw ex;
}
}
throw e.getCause();
}
}
/**
* Read the next row from the split, storing the coordinate in "key" and the content in "value". If there are no
* more rows then false is returned and "key" and "value" are not modified.
* @return true if a row was read, false if there were no more rows
*/
public boolean setNextKeyValue(Text key, Row value)
throws IOException {
if (!_rows.hasNext()) {
Closeables.close(this, true);
return false;
}
try {
Map<String, Object> content = _rows.next();
key.set(Coordinate.fromJson(content).toString());
value.set(content);
_rowsRead += 1;
} catch (Exception e) {
for (Throwable cause : Throwables.getCausalChain(e)) {
Throwables.propagateIfInstanceOf(cause, IOException.class);
}
throw new IOException("Failed to read next row", e);
}
return true;
}
/**
* Unmarshal bytes into Epp classes. Does the same as {@link EppXmlTransformer#unmarshal(Class,
* byte[])} but with exception-handling logic to throw {@link EppException} instead.
*/
public static <T> T unmarshalEpp(Class<T> clazz, byte[] bytes) throws EppException {
try {
return EppXmlTransformer.unmarshal(clazz, bytes);
} catch (XmlException e) {
// If this XmlException is wrapping a known type find it. If not, it's a syntax error.
List<Throwable> causalChain = Throwables.getCausalChain(e);
if (causalChain.stream().anyMatch(IpVersionMismatchException.class::isInstance)) {
throw new IpAddressVersionMismatchException();
}
if (causalChain.stream().anyMatch(WrongProtocolVersionException.class::isInstance)) {
throw new UnimplementedProtocolVersionException();
}
if (causalChain.stream().anyMatch(UnknownCurrencyException.class::isInstance)) {
throw new UnknownCurrencyEppException();
}
throw new GenericXmlSyntaxErrorException(e.getMessage());
}
}
static Matcher<? extends Throwable> causalChainContains(final Class<?> cls) {
return new TypeSafeMatcher<Throwable>() {
@Override
protected boolean matchesSafely(Throwable item) {
final List<Throwable> causalChain = Throwables.getCausalChain(item);
for (Throwable throwable : causalChain) {
if(cls.isAssignableFrom(throwable.getClass())){
return true;
}
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendText("exception with causal chain containing " + cls.getSimpleName());
}
};
}
private static boolean sqlCodeStartsWith(Exception e, String code)
{
for (Throwable throwable : Throwables.getCausalChain(e)) {
if (throwable instanceof SQLException) {
String state = ((SQLException) throwable).getSQLState();
if (state != null && state.startsWith(code)) {
return true;
}
}
}
return false;
}
/**
* Tests whether the exception itself, any of its causes, or any of their suppressed exceptions
* matches the given predicate.
*
* @return true if a match was found, false otherwise
* @throws IllegalArgumentException when there is a loop in the causal chain
*/
public static boolean anyInCausalChainOrSuppressedMatches(
Throwable baseThrowable, Predicate<Throwable> predicate) {
for (Throwable throwable : Throwables.getCausalChain(baseThrowable)) {
if (predicate.test(throwable)
|| Arrays.stream(throwable.getSuppressed()).anyMatch(predicate)) {
return true;
}
}
return false;
}
private static ClickHouseException getClickhouseException(Exception e) {
List<Throwable> causalChain = Throwables.getCausalChain(e);
for (Throwable throwable : causalChain) {
if (throwable instanceof ClickHouseException) {
return (ClickHouseException) throwable;
}
}
throw new IllegalArgumentException("no ClickHouseException found");
}
public void describeException(final Description d, final Exception e) {
d.topic("Exception during handler processing");
for (Throwable cause : Throwables.getCausalChain(e)) {
d.addTable(cause.getClass().getName(),
ImmutableMap.<String, Object>of("Message", nullToEmpty(cause.getMessage())));
}
}
@Test
public void testReplaceMemberRemovesAndThowsIfFailToStopOld() throws Exception {
final int failNum = 1;
final AtomicInteger counter = new AtomicInteger(0);
DynamicCluster cluster = app.createAndManageChild(EntitySpec.create(DynamicCluster.class)
.configure("initialSize", 1)
.configure("memberSpec", EntitySpec.create(FailingEntity.class)
.configure(FailingEntity.FAIL_ON_STOP_CONDITION, new Predicate<FailingEntity>() {
@Override public boolean apply(FailingEntity input) {
return counter.incrementAndGet() == failNum;
}})));
cluster.start(ImmutableList.of(loc));
Entity member = Iterables.get(cluster.getMembers(), 0);
try {
cluster.replaceMember(member.getId());
fail();
} catch (Exception e) {
if (Exceptions.getFirstThrowableOfType(e, StopFailedRuntimeException.class) == null) throw e;
boolean found = false;
for (Throwable t : Throwables.getCausalChain(e)) {
if (t.toString().contains("Simulating entity stop failure")) {
found = true;
break;
}
}
if (!found) throw e;
}
assertFalse(Entities.isManaged(member));
assertEquals(cluster.getMembers().size(), 1);
}
private static String getChainAsString(final Throwable th) {
final List<Throwable> causalChain = Throwables.getCausalChain(th);
final List<String> messages = Lists.transform(causalChain, new Function<Throwable, String>() {
@Override
public String apply(final Throwable input) {
return input.toString();
}
});
return Joiner.on(", ").join(messages);
}
protected void assertDirtyState(boolean enabled) throws IOException {
String dirtyResourceName = "test/test." + fileExt.getPrimaryFileExtension();
final URI dirtyResourceURI = URI.createPlatformResourceURI(dirtyResourceName, true);
final String testModel = "stuff foo stuff bar refs foo";
IDirtyResource mockDirtyResource = new IDirtyResource() {
@Override
public String getActualContents() {
return testModel;
}
@Override
public String getContents() {
return testModel;
}
@Override
public IResourceDescription getDescription() {
return new URIBasedTestResourceDescription(dirtyResourceURI);
}
@Override
public URI getURI() {
return dirtyResourceURI;
}
};
try {
assertTrue(dirtyStateManager.manageDirtyState(mockDirtyResource));
Resource dirtyResource = resourceSet.getResource(dirtyResourceURI, true);
assertTrue(dirtyResource instanceof XtextResource);
assertTrue(dirtyResource.isLoaded());
assertFalse(dirtyResource.getContents().isEmpty());
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
dirtyResource.save(byteArrayOutputStream, null);
assertEquals(testModel, new String(byteArrayOutputStream.toByteArray()));
assertTrue(enabled);
} catch (Throwable t) {
assertFalse(enabled);
boolean isResourceException = false;
for (Throwable tx : Throwables.getCausalChain(t)) {
if (tx instanceof org.eclipse.core.internal.resources.ResourceException) {
isResourceException = true;
break;
}
}
if (!isResourceException)
Exceptions.throwUncheckedException(t);
} finally {
dirtyStateManager.discardDirtyState(mockDirtyResource);
}
}
@Test
public void testUpdateCacheFrequencyWithAddAndDropTable() throws Exception {
// Create connections 1 and 2
Properties longRunningProps = new Properties(); // Must update config before starting server
longRunningProps.put(QueryServices.EXTRA_JDBC_ARGUMENTS_ATTRIB,
QueryServicesOptions.DEFAULT_EXTRA_JDBC_ARGUMENTS);
longRunningProps.put(QueryServices.DROP_METADATA_ATTRIB, Boolean.TRUE.toString());
Connection conn1 = DriverManager.getConnection(url, longRunningProps);
String url2 = url + PhoenixRuntime.JDBC_PROTOCOL_SEPARATOR + "LongRunningQueries";
Connection conn2 = DriverManager.getConnection(url2, longRunningProps);
conn1.setAutoCommit(true);
conn2.setAutoCommit(true);
String tableName = generateUniqueName();
String tableCreateQuery =
"create table "+tableName+" (k VARCHAR PRIMARY KEY, v1 VARCHAR, v2 VARCHAR)"
+ " UPDATE_CACHE_FREQUENCY=1000000000";
String dropTableQuery = "DROP table "+tableName;
try {
conn1.createStatement().execute(tableCreateQuery);
conn1.createStatement()
.execute("upsert into "+tableName+" values ('row1', 'value1', 'key1')");
conn1.createStatement()
.execute("upsert into "+tableName+" values ('row2', 'value2', 'key2')");
conn1.commit();
ResultSet rs =conn1.createStatement()
.executeQuery("select * from "+tableName);
assertTrue(rs.next());
assertTrue(rs.next());
assertFalse(rs.next());
rs = conn2.createStatement().executeQuery("select * from "+tableName);
assertTrue(rs.next());
assertTrue(rs.next());
assertFalse(rs.next());
//Drop table from conn1
conn1.createStatement().execute(dropTableQuery);
try {
rs = conn1.createStatement().executeQuery("select * from "+tableName);
fail("Should throw TableNotFoundException after dropping table");
} catch (TableNotFoundException e) {
//Expected
}
rs = conn2.createStatement().executeQuery("select * from "+tableName);
try {
rs.next();
fail("Should throw org.apache.hadoop.hbase.TableNotFoundException since the latest metadata " +
"wasn't fetched");
} catch (PhoenixIOException ex) {
boolean foundHBaseTableNotFound = false;
for(Throwable throwable : Throwables.getCausalChain(ex)) {
if(org.apache.hadoop.hbase.TableNotFoundException.class.equals(throwable.getClass())) {
foundHBaseTableNotFound = true;
break;
}
}
assertTrue("Should throw org.apache.hadoop.hbase.TableNotFoundException since the latest" +
" metadata wasn't fetched", foundHBaseTableNotFound);
}
} finally {
conn1.close();
conn2.close();
}
}