下面列出了org.apache.commons.lang3.exception.ExceptionUtils#getRootCause ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void show() {
if (throwable == null) {
throw new IllegalStateException("throwable should not be null");
}
Throwable rootCause = ExceptionUtils.getRootCause(throwable);
if (rootCause == null) {
rootCause = throwable;
}
ExceptionDialog dialog = new ExceptionDialog(rootCause, caption, message);
for (com.vaadin.ui.Window window : ui.getWindows()) {
if (window.isModal()) {
dialog.setModal(true);
break;
}
}
ui.addWindow(dialog);
dialog.focus();
}
@Test
public void shouldReportErrorWhenRequestCantBeSerialized() throws Exception {
final Cluster cluster = TestClientFactory.build().serializer(Serializers.GRAPHSON_V3D0).create();
final Client client = cluster.connect().alias("g");
try {
final Map<String,Object> params = new HashMap<>();
params.put("r", Color.RED);
client.submit("r", params).all().get();
fail("Should have thrown exception over bad serialization");
} catch (Exception ex) {
final Throwable inner = ExceptionUtils.getRootCause(ex);
assertThat(inner, instanceOf(ResponseException.class));
assertEquals(ResponseStatusCode.REQUEST_ERROR_SERIALIZATION, ((ResponseException) inner).getResponseStatusCode());
assertTrue(ex.getMessage().contains("An error occurred during serialization of this request"));
}
// should not die completely just because we had a bad serialization error. that kind of stuff happens
// from time to time, especially in the console if you're just exploring.
assertEquals(2, client.submit("1+1").all().get().get(0).getInt());
cluster.close();
}
@Test
public void shouldRequireAliasedGraphVariablesInStrictTransactionMode() throws Exception {
final Cluster cluster = TestClientFactory.open();
final Client client = cluster.connect();
try {
client.submit("1+1").all().get();
fail("Should have tossed an exception because strict mode is on and no aliasing was performed");
} catch (Exception ex) {
final Throwable root = ExceptionUtils.getRootCause(ex);
assertThat(root, instanceOf(ResponseException.class));
final ResponseException re = (ResponseException) root;
assertEquals(ResponseStatusCode.REQUEST_ERROR_INVALID_REQUEST_ARGUMENTS, re.getResponseStatusCode());
}
cluster.close();
}
@Test
public void shouldFailClientSideWithTooLargeAResponse() {
final Cluster cluster = TestClientFactory.build().maxContentLength(1).create();
final Client client = cluster.connect();
try {
final String fatty = IntStream.range(0, 100).mapToObj(String::valueOf).collect(Collectors.joining());
client.submit("'" + fatty + "'").all().get();
fail("Should throw an exception.");
} catch (Exception re) {
final Throwable root = ExceptionUtils.getRootCause(re);
assertTrue(root.getMessage().equals("Max frame length of 1 has been exceeded."));
} finally {
cluster.close();
}
}
@Test
public void shouldAliasGraphVariables() throws Exception {
final Cluster cluster = TestClientFactory.open();
final Client client = cluster.connect();
try {
client.submit("g.addVertex(label,'person','name','stephen');").all().get().get(0).getVertex();
fail("Should have tossed an exception because \"g\" does not have the addVertex method under default config");
} catch (Exception ex) {
final Throwable root = ExceptionUtils.getRootCause(ex);
assertThat(root, instanceOf(ResponseException.class));
final ResponseException re = (ResponseException) root;
assertEquals(ResponseStatusCode.SERVER_ERROR_EVALUATION, re.getResponseStatusCode());
}
final Client rebound = cluster.connect().alias("graph");
final Vertex v = rebound.submit("g.addVertex(label,'person','name','jason')").all().get().get(0).getVertex();
assertEquals("person", v.label());
cluster.close();
}
@Test
public void shouldFailAuthenticateWithPlainTextNoCredentials() throws Exception {
final Cluster cluster = TestClientFactory.open();
final Client client = cluster.connect();
try {
client.submit("1+1").all().get();
fail("This should not succeed as the client did not provide credentials");
} catch(Exception ex) {
final Throwable root = ExceptionUtils.getRootCause(ex);
// depending on the configuration of the system environment you might get either of these
assertThat(root, anyOf(instanceOf(GSSException.class), instanceOf(ResponseException.class)));
} finally {
cluster.close();
}
}
@Test
public void shouldEventuallySucceedAfterChannelLevelError() throws Exception {
final Cluster cluster = TestClientFactory.build()
.reconnectInterval(500)
.maxContentLength(1024).create();
final Client client = cluster.connect();
try {
client.submit("def x = '';(0..<1024).each{x = x + '$it'};x").all().get();
fail("Request should have failed because it exceeded the max content length allowed");
} catch (Exception ex) {
final Throwable root = ExceptionUtils.getRootCause(ex);
assertThat(root.getMessage(), containsString("Max frame length of 1024 has been exceeded."));
}
assertEquals(2, client.submit("1+1").all().join().get(0).getInt());
cluster.close();
}
public void getAppenderLevel() {
if (StringUtils.isNotEmpty(appenderNameField.getValue())) {
String appenderName = appenderNameField.getValue();
String threshold;
try {
threshold = jmxRemoteLoggingAPI.getAppenderThreshold(getSelectedConnection(), appenderName);
} catch (LogControlException | JmxControlException e) {
log.error("Error getting appender level", e);
Throwable rootCause = ExceptionUtils.getRootCause(e);
showNotification(getMessage("exception.logControl"), rootCause.getMessage(), NotificationType.ERROR);
return;
}
if (threshold != null)
appenderLevelField.setValue(LoggingHelper.getLevelFromString(threshold));
} else {
appenderLevelField.setValue(null);
showNotification(getMessage("appender.notSelected"), NotificationType.HUMANIZED);
}
}
@Test
public void shouldCloseSessionOnClientClose() throws Exception {
assumeNeo4jIsPresent();
final Cluster cluster1 = TestClientFactory.open();
final Client client1 = cluster1.connect(name.getMethodName());
client1.submit("x = 1").all().join();
client1.submit("graph.addVertex()").all().join();
client1.close();
cluster1.close();
assertThat(recordingAppender.getMessages(), hasItem("INFO - Skipped attempt to close open graph transactions on shouldCloseSessionOnClientClose - close was forced\n"));
assertThat(recordingAppender.getMessages(), hasItem("INFO - Session shouldCloseSessionOnClientClose closed\n"));
// try to reconnect to that session and make sure no state is there
final Cluster clusterReconnect = TestClientFactory.open();
final Client clientReconnect = clusterReconnect.connect(name.getMethodName());
// should get an error because "x" is not defined as this is a new session
try {
clientReconnect.submit("x").all().join();
fail("Should not have been successful as 'x' was only defined in the old session");
} catch(Exception ex) {
final Throwable root = ExceptionUtils.getRootCause(ex);
assertThat(root.getMessage(), startsWith("No such property"));
}
// the commit from client1 should not have gone through so there should be no data present.
assertEquals(0, clientReconnect.submit("graph.traversal().V().count()").all().join().get(0).getInt());
clusterReconnect.close();
}
@Test
public void shouldEventuallySucceedOnSameServerWithDefault() throws Exception {
stopServer();
final Cluster cluster = TestClientFactory.open();
final Client client = cluster.connect();
try {
client.submit("1+1").all().join().get(0).getInt();
fail("Should not have gone through because the server is not running");
} catch (Exception i) {
final Throwable root = ExceptionUtils.getRootCause(i);
assertThat(root, instanceOf(TimeoutException.class));
}
startServer();
// default reconnect time is 1 second so wait some extra time to be sure it has time to try to bring it
// back to life. usually this passes on the first attempt, but docker is sometimes slow and we get failures
// waiting for Gremlin Server to pop back up
for (int ix = 3; ix < 13; ix++) {
TimeUnit.SECONDS.sleep(ix);
try {
final int result = client.submit("1+1").all().join().get(0).getInt();
assertEquals(2, result);
break;
} catch (Exception ignored) {
logger.warn("Attempt {} failed on shouldEventuallySucceedOnSameServerWithDefault", ix);
}
}
cluster.close();
}
private void logSSLException(final ChannelHandlerContext ctx, final Throwable cause) {
if (log.isDebugEnabled()) {
final Throwable rootCause = ExceptionUtils.getRootCause(cause);
final String clientId = ctx.channel().attr(ChannelAttributes.CLIENT_ID).get();
if (clientId != null) {
log.debug("SSL message transmission for client {} failed: {}", clientId, rootCause.getMessage());
} else {
log.debug("SSL message transmission failed for client with IP {}: {}", ChannelUtils.getChannelIP(ctx.channel()).or("UNKNOWN"), rootCause.getMessage());
}
log.trace("Original Exception", rootCause);
}
}
/**
* Make a shallow copy of an instance. <br> This method copies attributes according to the metadata and relies on
* {@link com.haulmont.chile.core.model.Instance#getMetaClass()} method which should not return null for both
* objects. <br> The source and destination instances don't have to be of the same Java class or metaclass. Copying
* is performed in the following scenario: get each source property and copy the value to the destination if it
* contains a property with the same name and it is not read-only.
*
* @param source source instance
* @param dest destination instance
*/
public void copy(Instance source, Instance dest) {
checkNotNullArgument(source, "source is null");
checkNotNullArgument(dest, "dest is null");
MetaClass sourceMetaClass = metadata.getClassNN(source.getClass());
MetaClass destMetaClass = metadata.getClassNN(dest.getClass());
for (MetaProperty srcProperty : sourceMetaClass.getProperties()) {
String name = srcProperty.getName();
MetaProperty dstProperty = destMetaClass.getProperty(name);
if (dstProperty != null && !dstProperty.isReadOnly() && persistentAttributesLoadChecker.isLoaded(source, name)) {
try {
dest.setValue(name, source.getValue(name));
} catch (RuntimeException e) {
Throwable cause = ExceptionUtils.getRootCause(e);
if (cause == null)
cause = e;
// ignore exception on copy for not loaded fields
if (!isNotLoadedAttributeException(cause)) {
throw e;
}
}
}
}
if (source instanceof BaseGenericIdEntity && dest instanceof BaseGenericIdEntity) {
((BaseGenericIdEntity) dest).setDynamicAttributes(((BaseGenericIdEntity<?>) source).getDynamicAttributes());
}
}
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@Test
public void shouldBlockRequestWhenTooBig() throws Exception {
final Cluster cluster = TestClientFactory.open();
final Client client = cluster.connect();
try {
final String fatty = IntStream.range(0, 1024).mapToObj(String::valueOf).collect(Collectors.joining());
final CompletableFuture<ResultSet> result = client.submitAsync("'" + fatty + "';'test'");
final ResultSet resultSet = result.get(10000, TimeUnit.MILLISECONDS);
resultSet.all().get(10000, TimeUnit.MILLISECONDS);
fail("Should throw an exception.");
} catch (TimeoutException te) {
// the request should not have timed-out - the connection should have been reset, but it seems that
// timeout seems to occur as well on some systems (it's not clear why). however, the nature of this
// test is to ensure that the script isn't processed if it exceeds a certain size, so in this sense
// it seems ok to pass in this case.
} catch (Exception re) {
final Throwable root = ExceptionUtils.getRootCause(re);
// went with two possible error messages here as i think that there is some either non-deterministic
// behavior around the error message or it's environmentally dependent (e.g. different jdk, versions, etc)
assertThat(root.getMessage(), Matchers.anyOf(is("Connection to server is no longer active"), is("Connection reset by peer")));
// validate that we can still send messages to the server
assertEquals(2, client.submit("1+1").all().join().get(0).getInt());
} finally {
cluster.close();
}
}
public void handleStackCreationFailure(StackView stack, Exception errorDetails) {
LOGGER.info("Error during stack creation flow:", errorDetails);
String errorReason = errorDetails == null ? "Unknown error" : errorDetails.getMessage();
if (errorDetails instanceof CancellationException || ExceptionUtils.getRootCause(errorDetails) instanceof CancellationException) {
LOGGER.debug("The flow has been cancelled.");
} else {
if (!stack.isStackInDeletionPhase()) {
handleFailure(stack, errorReason);
stackUpdater.updateStackStatus(stack.getId(), DetailedStackStatus.PROVISION_FAILED, errorReason);
flowMessageService.fireEventAndLog(stack.getId(), CREATE_FAILED.name(), STACK_INFRASTRUCTURE_CREATE_FAILED, errorReason);
} else {
flowMessageService.fireEventAndLog(stack.getId(), UPDATE_IN_PROGRESS.name(), STACK_INFRASTRUCTURE_CREATE_FAILED, errorReason);
}
}
}
private void handleProcessingException(ProcessingException ex) {
Throwable rootEx = ExceptionUtils.getRootCause(ex);
if (rootEx != null && (rootEx instanceof UnknownHostException || rootEx instanceof ConnectException)) {
System.err.println("The specified host is unknown.");
} else {
throw ex;
}
}
protected LoginException wrapInLoginException(Throwable throwable) {
//noinspection ThrowableResultOfMethodCallIgnored
Throwable rootCause = ExceptionUtils.getRootCause(throwable);
if (rootCause == null) {
rootCause = throwable;
}
// todo rework, do not send exception messages they can contain sensitive configuration data
// send text only to avoid ClassNotFoundException when the client has no dependency to some library
return new InternalAuthenticationException(rootCause.toString());
}
@Override
public void error(final ErrorEvent event) {
if (ExceptionUtils.getRootCause(event.getThrowable()) instanceof AccessDeniedException) {
final AccessDeniedException accessDeniedException = (AccessDeniedException) ExceptionUtils.getRootCause(event.getThrowable());
Notification.show(accessDeniedException.getMessage(), Notification.Type.ERROR_MESSAGE);
ui.getNavigator().navigateTo(CommonsViews.MAIN_VIEW_NAME);
} else {
LOGGER.warn(LOG_WARN_VAADIN_ERROR, event.getThrowable());
}
}
private boolean runMicroflowTest(String mf, UnitTest test, TestSuite testSuite) throws CoreException
{
/**
* Prepare...
*/
LOG.info("Starting unittest for microflow " + mf);
reportStep("Starting microflow test '" + mf + "'");
test.setResult(UnitTestResult._1_Running);
test.setName(mf);
test.setResultMessage("");
test.setLastRun(new Date());
if (Core.getInputParameters(mf).size() != 0) {
test.setResultMessage("Unable to start test '" + mf + "', microflow has parameters");
test.setResult(UnitTestResult._2_Failed);
}
else if (Core.getReturnType(mf).getType() != IDataType.DataTypeEnum.Boolean &&
Core.getReturnType(mf).getType() != IDataType.DataTypeEnum.String &&
Core.getReturnType(mf).getType() != IDataType.DataTypeEnum.Nothing) {
test.setResultMessage("Unable to start test '" + mf + "', microflow should return either a boolean or a string or nothing at all");
test.setResult(UnitTestResult._2_Failed);
}
commitSilent(test);
IContext mfContext = Core.createSystemContext();
if (testSuite.getAutoRollbackMFs())
mfContext.startTransaction();
long start = System.currentTimeMillis();
try {
Object resultObject = Core.execute(mfContext, mf, emptyArguments);
start = System.currentTimeMillis() - start;
boolean res = resultObject == null || Boolean.TRUE.equals(resultObject) || "".equals(resultObject);
test.setResult(res ? UnitTestResult._3_Success : UnitTestResult._2_Failed);
if (res) {
test.setResultMessage("Microflow completed successfully");
}
return res;
}
catch(Exception e) {
start = System.currentTimeMillis() - start;
test.setResult(UnitTestResult._2_Failed);
Throwable cause = ExceptionUtils.getRootCause(e);
if (cause != null && cause instanceof AssertionException)
test.setResultMessage(cause.getMessage());
else
test.setResultMessage("Exception: " + e.getMessage() + "\n\n" + ExceptionUtils.getStackTrace(e));
return false;
}
finally {
if (testSuite.getAutoRollbackMFs())
mfContext.rollbackTransAction();
test.setLastStep(lastStep);
test.setReadableTime((start > 10000 ? Math.round(start / 1000) + " seconds" : start + " milliseconds"));
commitSilent(test);
LOG.info("Finished unittest " + mf + ": " + test.getResult());
}
}
private SQLResponse getPrepareOnlySqlResponse(String projectName, String correctedSql, Connection conn,
Boolean isPushDown, List<List<String>> results, List<SelectedColumnMeta> columnMetas) throws SQLException {
CalcitePrepareImpl.KYLIN_ONLY_PREPARE.set(true);
PreparedStatement preparedStatement = null;
try {
preparedStatement = conn.prepareStatement(correctedSql);
throw new IllegalStateException("Should have thrown OnlyPrepareEarlyAbortException");
} catch (Exception e) {
Throwable rootCause = ExceptionUtils.getRootCause(e);
if (rootCause != null && rootCause instanceof OnlyPrepareEarlyAbortException) {
OnlyPrepareEarlyAbortException abortException = (OnlyPrepareEarlyAbortException) rootCause;
CalcitePrepare.Context context = abortException.getContext();
CalcitePrepare.ParseResult preparedResult = abortException.getPreparedResult();
List<RelDataTypeField> fieldList = preparedResult.rowType.getFieldList();
CalciteConnectionConfig config = context.config();
// Fill in selected column meta
for (int i = 0; i < fieldList.size(); ++i) {
RelDataTypeField field = fieldList.get(i);
String columnName = field.getKey();
if (columnName.startsWith("_KY_")) {
continue;
}
BasicSqlType basicSqlType = (BasicSqlType) field.getValue();
columnMetas.add(new SelectedColumnMeta(false, config.caseSensitive(), false, false,
basicSqlType.isNullable() ? 1 : 0, true, basicSqlType.getPrecision(), columnName,
columnName, null, null, null, basicSqlType.getPrecision(),
basicSqlType.getScale() < 0 ? 0 : basicSqlType.getScale(),
basicSqlType.getSqlTypeName().getJdbcOrdinal(), basicSqlType.getSqlTypeName().getName(),
true, false, false));
}
} else {
throw e;
}
} finally {
CalcitePrepareImpl.KYLIN_ONLY_PREPARE.set(false);
DBUtils.closeQuietly(preparedStatement);
}
return buildSqlResponse(projectName, isPushDown, results, columnMetas);
}
private String extractFailReason(Throwable t) {
Throwable root = ExceptionUtils.getRootCause(t);
t = ObjectUtils.defaultIfNull(root, t);
return t != null ? t.getMessage() : null;
}