下面列出了怎么用org.apache.commons.lang3.exception.ExceptionUtils的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public boolean handle(Throwable exception, WindowManager windowManager) {
List<Throwable> list = ExceptionUtils.getThrowableList(exception);
for (Throwable throwable : list) {
if (className.contains(throwable.getClass().getName()) && isDateOutOfRangeMessage(throwable.getMessage())) {
doHandle(windowManager);
return true;
}
if (throwable instanceof RemoteException) {
RemoteException remoteException = (RemoteException) throwable;
for (RemoteException.Cause cause : remoteException.getCauses()) {
if (className.contains(cause.getClassName()) && isDateOutOfRangeMessage(throwable.getMessage())) {
doHandle(windowManager);
return true;
}
}
}
}
return false;
}
@Test
public void formatNotNullThrown() throws Exception {
final String previousLineSeparatorProperty = System.getProperty(LINE_SEPARATOR_KEY);
try {
final String lineSeparatorValue = "\n";
final String logMessage = "An example log record";
final Level level = Level.CONFIG;
final String exceptionMessage = "An example exception";
final Throwable thrown = new Exception(exceptionMessage);
System.setProperty(LINE_SEPARATOR_KEY, lineSeparatorValue);
final LogRecord logRecordInput = new LogRecord(level, logMessage);
logRecordInput.setThrown(thrown);
final Formatter formatter = new SimpleTomEEFormatter();
final String actualFormatOutput = formatter.format(logRecordInput);
final String expectedFormatOutput = level.getLocalizedName() + " - " + logMessage + lineSeparatorValue + ExceptionUtils.getStackTrace(thrown);
assertEquals(expectedFormatOutput, actualFormatOutput);
} finally {
System.setProperty(LINE_SEPARATOR_KEY, previousLineSeparatorProperty);
}
}
@Override
public SendResult send(String[] msgData) {
SendResult sendResult = new SendResult();
try {
String openId = msgData[0];
WxMpTemplateMessage wxMessageTemplate = wxMpTemplateMsgMaker.makeMsg(msgData);
wxMessageTemplate.setToUser(openId);
if (PushControl.dryRun) {
sendResult.setSuccess(true);
return sendResult;
} else {
wxMpService.getTemplateMsgService().sendTemplateMsg(wxMessageTemplate);
}
} catch (Exception e) {
sendResult.setSuccess(false);
sendResult.setInfo(e.getMessage());
log.error(ExceptionUtils.getStackTrace(e));
return sendResult;
}
sendResult.setSuccess(true);
return sendResult;
}
@Override
public boolean handleException(final JobServiceConfiguration jobServiceConfiguration, final JobInfo job, final Throwable exception) {
if (HANDLER_TYPE_BREAK_POINT.equals(job.getJobHandlerType())) {
LOGGER.debug("break point execution throws an exception which will be swallowed", exception);
jobServiceConfiguration.getCommandExecutor().execute(
commandContext -> {
JobEntity jobEntity = jobServiceConfiguration.getJobService().findJobById(job.getId());
SuspendedJobEntity suspendedJobEntity = jobServiceConfiguration.getJobService().moveJobToSuspendedJob(jobEntity);
if (exception != null) {
LOGGER.info("Debugger exception ", exception);
suspendedJobEntity.setExceptionMessage(exception.getMessage());
suspendedJobEntity.setExceptionStacktrace(ExceptionUtils.getStackTrace(exception));
}
return null;
}
);
return true;
}
return false;
}
@Override
public SendResult send(String[] msgData) {
SendResult sendResult = new SendResult();
try {
String openId = msgData[0];
WxMaSubscribeMessage wxMaSubscribeMessage = new WxMaSubscribeMessage();
wxMaSubscribeMessage.setToUser(openId);
wxMaSubscribeMessage.setTemplateId(msgData[1]);
if (PushControl.dryRun) {
sendResult.setSuccess(true);
return sendResult;
} else {
wxMaService.getMsgService().sendSubscribeMsg(wxMaSubscribeMessage);
}
} catch (Exception e) {
sendResult.setSuccess(false);
sendResult.setInfo(e.getMessage());
log.error(ExceptionUtils.getStackTrace(e));
return sendResult;
}
sendResult.setSuccess(true);
return sendResult;
}
@Override
public List<String> listSchemaNames(ConnectorSession session) {
List<String> prestoSchemas = new LinkedList<>();
try {
List<String> tenants = pulsarAdmin.tenants().getTenants();
for (String tenant : tenants) {
prestoSchemas.addAll(pulsarAdmin.namespaces().getNamespaces(tenant).stream().map(namespace ->
rewriteNamespaceDelimiterIfNeeded(namespace, pulsarConnectorConfig)).collect(Collectors.toList()));
}
} catch (PulsarAdminException e) {
if (e.getStatusCode() == 401) {
throw new PrestoException(QUERY_REJECTED, "Failed to get schemas from pulsar: Unauthorized");
}
throw new RuntimeException("Failed to get schemas from pulsar: "
+ ExceptionUtils.getRootCause(e).getLocalizedMessage(), e);
}
return prestoSchemas;
}
/**
* Clean return of Exception in JSon format & log Exception.
*
* @param request
* @param response
* @param out
* @param exception
*/
public static void logAndReturnException(HttpServletRequest request,
HttpServletResponse response, PrintWriter out,
Exception exception) {
try {
JsonErrorReturn jsonErrorReturn = new JsonErrorReturn(response,
HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
JsonErrorReturn.ERROR_ACEQL_ERROR, exception.getMessage(),
ExceptionUtils.getStackTrace(exception));
out.println(jsonErrorReturn.build());
LoggerUtil.log(request, exception);
} catch (Exception e) {
// Should never happen
e.printStackTrace();
}
}
public void review(@NotNull ReviewProcessor processor) {
log.info("Review started for processor {}", processor.getName());
long start = System.currentTimeMillis();
ReviewResult reviewResult = null;
try {
reviewResult = processor.process(review);
} catch (ReviewException e) {
log.error("Processor {} error", processor.getName(), e);
review.addProblem(processor.getName(), ExceptionUtils.getRootCauseMessage(e));
}
log.info("Review finished for processor {}. Took {} s", processor.getName(), (System.currentTimeMillis() - start) / THOUSAND);
if (reviewResult == null) {
log.warn("Review for processor {} returned empty review", processor.getName());
} else {
log.info("Review for processor {} returned {} violations", processor.getName(), reviewResult.getViolations().size());
review.add(processor.getName(), reviewResult);
}
}
@Override
public void onComplete(ListenableFuture<Object> future) throws Exception {
if (context.session.isClosed()) {
return;
}
final RpcErrorCode errorCode;
final Object body;
if (future.isCompletedExceptionally()) {
errorCode = RpcErrorCode.SERVER_EXCEPTION;
// 不返回完整信息,意义不大
body = ExceptionUtils.getRootCauseMessage(future.cause());
} else {
errorCode = RpcErrorCode.SUCCESS;
body = future.getNow();
}
// 此时已经在网络线程,直接write,但还是需要流经整个管道
final RpcResponseMessage responseMessage = new RpcResponseMessage(context.requestGuid, context.sync, errorCode, body);
context.session.fireWrite(responseMessage);
}
@Override
public boolean handle(Throwable exception, UiContext context) {
List<Throwable> list = ExceptionUtils.getThrowableList(exception);
for (Throwable throwable : list) {
if (classNames.contains(throwable.getClass().getName())
&& canHandle(throwable.getClass().getName(), throwable.getMessage(), throwable)) {
doHandle(throwable.getClass().getName(), throwable.getMessage(), throwable, context);
return true;
}
if (throwable instanceof RemoteException) {
RemoteException remoteException = (RemoteException) throwable;
for (RemoteException.Cause cause : remoteException.getCauses()) {
if (classNames.contains(cause.getClassName())
&& canHandle(cause.getClassName(), cause.getMessage(), cause.getThrowable())) {
doHandle(cause.getClassName(), cause.getMessage(), cause.getThrowable(), context);
return true;
}
}
}
}
return false;
}
@ProcessElement
public void processElement(ProcessContext context) {
byte[] value = context.element().getKV().getValue();
FeatureRow featureRow;
try {
featureRow = FeatureRow.parseFrom(value);
} catch (InvalidProtocolBufferException e) {
context.output(
getFailureTag(),
FailedElement.newBuilder()
.setTransformName("KafkaRecordToFeatureRow")
.setStackTrace(ExceptionUtils.getStackTrace(e))
.setJobName(context.getPipelineOptions().getJobName())
.setPayload(new String(Base64.getEncoder().encode(value)))
.setErrorMessage(e.getMessage())
.build());
return;
}
context.output(featureRow);
}
/**
* move partitions to the target host
* @param datastreamName
* Name of the datastream to move.
* @param partitions
* partitions that need to be moved, separate by comma, ex topicA-0,topicB-1
* @param targetHost
* the target host the partition assignment
* @throws RemoteInvocationException
*/
public void movePartitions(String datastreamName, String partitions, String targetHost) throws RemoteInvocationException {
Instant startTime = Instant.now();
PollUtils.poll(() -> {
try {
ActionRequest<Void> request = _builders.actionMovePartitions().id(datastreamName).
partitionsParam(partitions).targetHostParam(targetHost).build();
ResponseFuture<Void> datastreamResponseFuture = _restClient.sendRequest(request);
return datastreamResponseFuture.getResponse();
} catch (RemoteInvocationException e) {
if (ExceptionUtils.getRootCause(e) instanceof TimeoutException) {
LOG.warn("Timeout: movePartitions. May retry...", e);
return null;
}
if (isNotFoundHttpStatus(e)) {
LOG.warn(String.format("Datastream {%s} is not found", datastreamName), e);
throw new DatastreamNotFoundException(datastreamName, e);
} else {
String errorMessage = String.format("move partitions failed with error, Datastream {%s}.", datastreamName);
ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e);
}
return null; // not reachable
}
}, Objects::nonNull, getRetryPeriodMs(), getRetryTimeoutMs()).orElseThrow(RetriesExhaustedException::new);
LOG.info("move partitions for datastream {} took {} ms", datastreamName, Duration.between(startTime, Instant.now()).toMillis());
}
/**
* Add new repository.
*
* @param message Repository
*/
@POST
@Path("repository")
@ZeppelinApi
public Response addRepository(String message) {
try {
Repository request = Repository.fromJson(message);
interpreterSettingManager.addRepository(request.getId(), request.getUrl(),
request.isSnapshot(), request.getAuthentication(), request.getProxy());
logger.info("New repository {} added", request.getId());
} catch (Exception e) {
logger.error("Exception in InterpreterRestApi while adding repository ", e);
return new JsonResponse<>(Status.INTERNAL_SERVER_ERROR, e.getMessage(),
ExceptionUtils.getStackTrace(e)).build();
}
return new JsonResponse(Status.OK).build();
}
@Override
public void acquire() {
lock.lock();
try {
acquireCnt++;
while (!acquirable()) {
try {
doWait();
} catch (InterruptedException e) {
ExceptionUtils.wrapAndThrow(e);
}
}
onAcquired();
} finally {
acquireCnt--;
lock.unlock();
}
}
@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();
}
public boolean closeSession(String paragraphId) throws UniverseException {
try {
if (tokens.containsKey(paragraphId)) {
HttpPost httpPost = new HttpPost(String.format("%s%s", apiUrl, "/logoff"));
setHeaders(httpPost, tokens.get(paragraphId));
HttpResponse response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) {
return true;
}
}
return false;
} catch (Exception e) {
throw new UniverseException(String.format(errorMessageTemplate, "UniverseClient "
+ "(close session): Request failed", ExceptionUtils.getStackTrace(e)));
} finally {
tokens.remove(paragraphId);
}
}
@Test
public void shouldEnableSslAndFailIfCiphersDontMatch() {
final Cluster cluster = TestClientFactory.build().enableSsl(true).keyStore(JKS_SERVER_KEY).keyStorePassword(KEY_PASS)
.sslSkipCertValidation(true).sslCipherSuites(Arrays.asList("SSL_RSA_WITH_RC4_128_SHA")).create();
final Client client = cluster.connect();
try {
client.submit("'test'").one();
fail("Should throw exception because ssl client requires TLSv1.2 whereas server supports only TLSv1.1");
} catch (Exception x) {
final Throwable root = ExceptionUtils.getRootCause(x);
assertThat(root, instanceOf(TimeoutException.class));
} finally {
cluster.close();
}
}
@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();
}
@Override
public BackgroundException map(final ApiException failure) {
for(Throwable cause : ExceptionUtils.getThrowableList(failure)) {
if(cause instanceof SocketException) {
// Map Connection has been shutdown: javax.net.ssl.SSLException: java.net.SocketException: Broken pipe
return new DefaultSocketExceptionMappingService().map((SocketException) cause);
}
if(cause instanceof HttpResponseException) {
return new DefaultHttpResponseExceptionMappingService().map((HttpResponseException) cause);
}
if(cause instanceof IOException) {
return new DefaultIOExceptionMappingService().map((IOException) cause);
}
if(cause instanceof IllegalStateException) {
// Caused by: ch.cyberduck.core.sds.io.swagger.client.ApiException: javax.ws.rs.ProcessingException: java.lang.IllegalStateException: Connection pool shut down
return new ConnectionCanceledException(cause);
}
}
return new DefaultHttpResponseExceptionMappingService().map(new HttpResponseException(failure.getCode(), failure.getMessage()));
}
@BeforeClass
public static void setup() throws Exception {
try {
System.setProperty("org.apache.commons.logging.Log", "org.openas2.logging.Log");
//System.setProperty("org.openas2.logging.defaultlog", "TRACE");
FilenameParsingTest.session = new XMLSession(RESOURCE.get("MyCompany", "config", "config.xml").getAbsolutePath());
msg = new AS2Message();
msg.setAttribute(FileAttribute.MA_FILENAME, testFileName);
PartnershipFactory pf = session.getPartnershipFactory();
Partnership myPartnership = msg.getPartnership();
myPartnership.setSenderID(Partnership.PID_AS2, myCompanyOid);
myPartnership.setReceiverID(Partnership.PID_AS2, myPartnerOid);
myPartnership.setSenderID(Partnership.PID_AS2, myCompanyOid);
Partnership configuredPartnership = pf.getPartnership(myPartnership, false);
configuredPartnership.setAttribute(Partnership.PAIB_VALUES_REGEX_ON_FILENAME, fileNameRegex);
configuredPartnership.setAttribute(Partnership.PAIB_NAMES_FROM_FILENAME, attribNamesFromFileName);
configuredPartnership.setAttribute(Partnership.PA_SUBJECT, subjectAttrib);
// update the message's partnership with any stored information
pf.updatePartnership(msg, true);
} catch (Throwable e) {
// aid for debugging JUnit tests
System.err.println("ERROR occurred: " + ExceptionUtils.getStackTrace(e));
throw new Exception(e);
}
}
public ScheduleLogRequest(JobExecutionContext jobExecutionContext, JobExecutionException jobExecutionException) {
JobDetail jobDetail = jobExecutionContext.getJobDetail();
this.className = jobDetail.getKey().getName();
this.application = jobDetail.getKey().getGroup();
this.node = jobDetail.getDescription();
this.type = jobExecutionContext.getTrigger().getDescription();
this.elapsed = jobExecutionContext.getJobRunTime();
this.fireTime = jobExecutionContext.getFireTime();
if (null != jobExecutionException) {
this.stackTrace = ExceptionUtils.getStackTrace(jobExecutionException);
this.success = false;
} else {
this.success = true;
}
}
private static void processValidateCCDAException(ValidationResultsMetaData resultsMetaData,
String serviceErrorStart, String validationObjective, Exception exception) {
resultsMetaData.setServiceError(true);
String fullErrorWithStackTrace = serviceErrorStart + ExceptionUtils.getStackTrace(exception);
if (exception.getMessage() != null) {
String fullError = serviceErrorStart + exception.getMessage();
resultsMetaData.setServiceErrorMessage(fullError);
} else {
resultsMetaData.setServiceErrorMessage(fullErrorWithStackTrace);
}
logger.error(fullErrorWithStackTrace);
resultsMetaData.setObjectiveProvided(validationObjective);
}
@CommonColumns(@CommonColumn(value = Column.ServiceName, required = true))
@ActionMethod
public void initService(IActionContext actionContext, HashMap<?, ?> message) throws IllegalAccessException, InvocationTargetException, InterruptedException, IOException {
ServiceName serviceName = ServiceName.parse(actionContext.getServiceName());
IActionServiceManager serviceManager = actionContext.getServiceManager();
try {
IServiceSettings serviceSettings = serviceManager.getServiceSettings(serviceName);
BeanMap beanMap = new BeanMap(serviceSettings);
Set<String> editedProperty = new HashSet<>();
Set<String> incorrectProperty = new HashSet<>();
for (Entry<?, ?> entry : message.entrySet()) {
String property = convertProperty(entry.getKey().toString());
if (beanMap.containsKey(property)){
BeanUtils.setProperty(serviceSettings, property, converter.get().convert((Object)unwrapFilters(entry.getValue()), beanMap.getType(property)));
editedProperty.add(property);
} else {
incorrectProperty.add(property);
}
}
if (!incorrectProperty.isEmpty()) {
throw new EPSCommonException(serviceSettings.getClass().getName() + " does not contain properties: " + incorrectProperty);
}
serviceManager.updateService(serviceName, serviceSettings, null).get();
try (FileOutputStream out = new FileOutputStream(actionContext.getReport().createFile(StatusType.NA, servicesFolder, changingSettingFolder, serviceName + FORMATTER.format(DateTimeUtility.nowLocalDateTime()) + servicesFileExpression))) {
actionContext.getServiceManager().serializeServiceSettings(serviceName, out);
}
} catch (ExecutionException e) {
ExceptionUtils.rethrow(ObjectUtils.defaultIfNull(e.getCause(), e));
}
}
@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());
}
}
public static void withContext(final ProcessorContext context, final Runnable runnable) {
Validate.notNull(context, "Processor context must be defined");
Validate.notNull(runnable, "Operation must be defined");
CONTEXT.set(context);
try {
runnable.run();
} catch (final Exception ex) {
MessageUtils.error(ExceptionUtils.getMessage(ex));
} finally {
CONTEXT.remove();
}
}
/**
* 重写默认的accept函数
*
* @param t 接受的泛型参数
*/
@Override
default void accept(T t) {
try {
acceptException(t);
} catch (Exception e) {
throw new RuntimeException(ExceptionUtils.getRootCause(e).getMessage());
}
}
public boolean deleteBlock(TownBlock block) {
try {
// Delete Block from Datasource
PreparedStatement deleteBlockStatement = prepare("DELETE FROM " + prefix + "Blocks WHERE dim=? AND x=? AND z=?", true);
deleteBlockStatement.setInt(1, block.getDim());
deleteBlockStatement.setInt(2, block.getX());
deleteBlockStatement.setInt(3, block.getZ());
deleteBlockStatement.execute();
if (block.isChunkloaded()) {
block.getTown().ticketMap.chunkUnload(block);
}
// Delete Block from Town
block.getTown().townBlocksContainer.remove(block);
// Delete Plots contained in the Block
for (Plot p : ImmutableList.copyOf(block.plotsContainer)) {
deletePlot(p);
}
// Remove Block from Map
MyTownUniverse.instance.removeTownBlock(block);
} catch (SQLException e) {
LOG.error("Failed to delete Block {}!", block.getKey());
LOG.error(ExceptionUtils.getStackTrace(e));
return false;
}
return true;
}
/**
* 重写默认的apply函数
*
* @param t 接受的泛型参数
* @return 返回泛型R
*/
@Override
default R apply(T t) {
try {
return applyException(t);
} catch (Exception e) {
throw new RuntimeException(ExceptionUtils.getRootCause(e).getMessage());
}
}
@Override
public SendResult send(String[] msgData) {
SendResult sendResult = new SendResult();
try {
int templateId = TxYunMsgMaker.templateId;
String smsSign = App.config.getTxyunSign();
String[] params = txYunMsgMaker.makeMsg(msgData);
String telNum = msgData[0];
if (PushControl.dryRun) {
sendResult.setSuccess(true);
return sendResult;
} else {
SmsSingleSenderResult result = smsSingleSender.sendWithParam("86", telNum,
templateId, params, smsSign, "", "");
if (result.result == 0) {
sendResult.setSuccess(true);
} else {
sendResult.setSuccess(false);
sendResult.setInfo(result.toString());
}
}
} catch (Exception e) {
sendResult.setSuccess(false);
sendResult.setInfo(e.getMessage());
log.error(ExceptionUtils.getStackTrace(e));
}
return sendResult;
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public MultipleRowSetResponse getRows(MultipleRowSetRequest request) {
MultipleRowSetResponse response = new MultipleRowSetResponse();
try {
conf.set(MacroBaseConf.DB_URL, request.pgUrl);
// Need a CSV ingester. Changing so it's not fixed during construction (used to be final, but changed as
// this is set in AnalyzeResource after construction)
configuredIngester = conf.getString(MacroBaseConf.DATA_LOADER_TYPE, MacroBaseDefaults.DATA_LOADER_TYPE.toString());
DataIngester loader = getLoader();
List<RowSet> lr = new ArrayList<RowSet>();
for (List<RowSetResource.RowSetRequest.RowRequestPair> columnValue : request.columnValues) {
HashMap<String, String> preds = new HashMap<>();
columnValue.stream().forEach(a -> preds.put(a.column, a.value));
lr.add(loader.getRows(request.baseQuery,
preds,
request.limit,
request.offset));
}
response.rowSets = lr;
} catch (Exception e) {
log.error("An error occurred while processing a request:", e);
response.errorMessage = ExceptionUtils.getStackTrace(e);
}
return response;
}