下面列出了org.apache.commons.lang3.exception.ExceptionUtils#getStackTrace ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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();
}
}
/**
* Called if an error occurrs. Can be overridden. SHows dialog by default.
*
* @param e the exception thrown.
*/
public void onError( Exception e ) {
e.printStackTrace();
String localizedMessage = e.getLocalizedMessage();
if (localizedMessage == null) {
localizedMessage = e.getMessage();
}
if (localizedMessage == null || localizedMessage.trim().length() == 0) {
localizedMessage = "An undefined error was thrown. Please send the below trace to your technical contact:\n";
localizedMessage += ExceptionUtils.getStackTrace(e);
}
String _localizedMessage = localizedMessage;
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JOptionPane.showMessageDialog(parent, _localizedMessage, "ERROR", JOptionPane.ERROR_MESSAGE);
}
});
}
@Authenticated
@Override
public String jpqlLoadList(String queryString) {
try {
Transaction tx = persistence.createTransaction();
try {
EntityManager em = persistence.getEntityManager();
Query query = em.createQuery(queryString);
QueryParser parser = QueryTransformerFactory.createParser(queryString);
Set<String> paramNames = parser.getParamNames();
for (String paramName : paramNames) {
security.setQueryParam(query, paramName);
}
List resultList = query.getResultList();
tx.commit();
TextStringBuilder sb = new TextStringBuilder();
for (Object element : resultList) {
if (element instanceof Object[]) {
sb.appendWithSeparators((Object[]) element, " | ");
} else {
sb.append(element);
}
sb.append("\n");
}
return sb.toString();
} finally {
tx.end();
}
} catch (Throwable e) {
log.error("jpqlLoadList error", e);
return ExceptionUtils.getStackTrace(e);
}
}
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);
}
public void setThrowable(Throwable t) {
final String errorMsg;
if (t instanceof NullPointerException) {
errorMsg = "NullPointerException";
} else {
errorMsg = t.getMessage();
}
if(StringUtils.isEmpty(this.getMessage())) {
this.setMessage(errorMsg);
}
this.setExceptionClass(t.getClass().getName());
final String stacktrace = ExceptionUtils.getStackTrace(t);
this.setStacktrace(stacktrace);
}
private String getStackTrace(Throwable throwable) {
if (throwable instanceof RemoteException) {
RemoteException re = (RemoteException) throwable;
for (int i = re.getCauses().size() - 1; i >= 0; i--) {
if (re.getCauses().get(i).getThrowable() != null) {
throwable = re.getCauses().get(i).getThrowable();
break;
}
}
}
return ExceptionUtils.getStackTrace(throwable);
}
@Override
public String stop() {
try {
clusterManager.stop();
return "Done";
} catch (Exception e) {
log.error("Unable to stop the cluster", e);
return ExceptionUtils.getStackTrace(e);
}
}
private CandidateInfo processFailedCandidates(Candidate<?> candidate) {
//In case the candidate fails during the creation of the candidate
long time = System.currentTimeMillis();
String stackTrace = ExceptionUtils.getStackTrace(candidate.getException());
CandidateInfo newStatus = new CandidateInfo(candidate.getIndex(), CandidateStatus.Failed, null, time, time,
time, candidate.getFlatParameters(), stackTrace);
currentStatus.put(candidate.getIndex(), newStatus);
return newStatus;
}
@Override
public String reloadClass(String className) {
try {
javaClassLoader.removeClass(className);
return loadClass(className);
} catch (Exception e) {
return ExceptionUtils.getStackTrace(e);
}
}
@Test
public void toSelectSQL3(){
UserInfo userInfo = new UserInfo(33, "函数式编程", 18);
SQLValue sqlValue = BeanUtil.toSelectSQL(userInfo, null);
String sql = sqlValue.getSql();
List<Object> list = sqlValue.getValues();
assertThat(list.size(), is(2));
assertThat(sql,equalTo("select id,name,age from UserInfo where id = 33 and name = ? and age = ?"));
assertThat(list.get(0),equalTo("函数式编程"));
assertThat(list.get(1),is(18));
userInfo = new UserInfo(33, null,18);
sqlValue = BeanUtil.toSelectSQL(userInfo, null);
sql = sqlValue.getSql();
list = sqlValue.getValues();
assertThat(list.size(), is(1));
assertThat(sql,equalTo("select id,name,age from UserInfo where id = 33 and age = ?"));
assertThat(list.get(0),is(18));
userInfo = new UserInfo(33, null,null);
sqlValue = BeanUtil.toSelectSQL(userInfo, null);
sql = sqlValue.getSql();
list = sqlValue.getValues();
assertThat(list.size(), is(0));
assertThat(sql,equalTo("select id,name,age from UserInfo where id = 33"));
userInfo = new UserInfo(null, null,null);
try {
sqlValue = BeanUtil.toSelectSQL(userInfo, null);
} catch (RepositoryException e){
String stackMsg = ExceptionUtils.getStackTrace(e);
assertThat(stackMsg, containsString("主键值,必须传递!"));
}
}
public String getStacktrace() {
if (fullStackTrace != null) {
return fullStackTrace;
}
return throwable != null ? ExceptionUtils.getStackTrace(throwable) : "";
}
@Override
public String findOrphanDescriptors() {
com.haulmont.cuba.core.app.filestorage.FileStorage fileStorage;
FileStorageAPI fileStorageAPI = AppBeans.get(FileStorageAPI.class);
if (fileStorageAPI instanceof com.haulmont.cuba.core.app.filestorage.FileStorage) {
fileStorage = (com.haulmont.cuba.core.app.filestorage.FileStorage) fileStorageAPI;
} else {
return "<not supported>";
}
File[] roots = getStorageRoots();
if (roots.length == 0)
return "No storage directories defined";
StringBuilder sb = new StringBuilder();
Transaction tx = persistence.createTransaction();
try {
EntityManager em = persistence.getEntityManager();
TypedQuery<FileDescriptor> query = em.createQuery("select fd from sys$FileDescriptor fd", FileDescriptor.class);
List<FileDescriptor> fileDescriptors = query.getResultList();
for (FileDescriptor fileDescriptor : fileDescriptors) {
File dir = fileStorage.getStorageDir(roots[0], fileDescriptor);
File file = new File(dir, com.haulmont.cuba.core.app.filestorage.FileStorage.getFileName(fileDescriptor));
if (!file.exists()) {
sb.append(fileDescriptor.getId())
.append(", ")
.append(fileDescriptor.getName())
.append(", ")
.append(fileDescriptor.getCreateDate())
.append("\n");
}
}
tx.commit();
} catch (Exception e) {
return ExceptionUtils.getStackTrace(e);
} finally {
tx.end();
}
return sb.toString();
}
@Override
public void open() throws InterpreterException {
try {
if (jupyterKernelClient != null) {
// JupyterKernelInterpreter might already been opened
return;
}
pythonExecutable = getProperty("zeppelin.python", "python");
LOGGER.info("Python Exec: " + pythonExecutable);
String checkPrerequisiteResult = checkKernelPrerequisite(pythonExecutable);
if (!StringUtils.isEmpty(checkPrerequisiteResult)) {
throw new InterpreterException("Kernel prerequisite is not meet: " +
checkPrerequisiteResult);
}
kernelLaunchTimeout = Integer.parseInt(
getProperty("zeppelin.jupyter.kernel.launch.timeout", "30000"));
this.z = buildZeppelinContext();
int kernelPort = RemoteInterpreterUtils.findRandomAvailablePortOnAllLocalInterfaces();
int message_size = Integer.parseInt(getProperty("zeppelin.jupyter.kernel.grpc.message_size",
32 * 1024 * 1024 + ""));
jupyterKernelClient = new JupyterKernelClient(ManagedChannelBuilder.forAddress("127.0.0.1",
kernelPort).usePlaintext(true).maxInboundMessageSize(message_size),
getProperties(), kernel);
launchJupyterKernel(kernelPort);
} catch (Exception e) {
throw new InterpreterException("Fail to open JupyterKernelInterpreter:\n" +
ExceptionUtils.getStackTrace(e), e);
}
}
/**
* Wait till table cell has a given content.
*
* @param table
* the table bot reference
* @param content
* the content to check
* @param row
* the row of the cell
* @param column
* the column of the cell
* @return ICondition for verification
*/
public static ICondition isTableCellFilled(final SWTBotTable table,
final String content, final int row, final int column) {
return new SWTBotTestCondition() {
String actual;
Exception exception;
@Override
public boolean test() throws Exception {
try {
exception = null;
actual = table.cell(row, column);
if (actual == null) {
return false;
}
return actual.contains(content);
} catch (Exception e) {
exception = e;
}
return false;
}
@Override
public String getFailureMessage() {
if (exception != null) {
return ExceptionUtils.getStackTrace(exception);
}
if (actual == null) {
return NLS.bind("Cell absent, expected: ''{0}''", content);
}
return NLS.bind("Cell content: ''{0}'' expected: ''{1}''", actual, content);
}
};
}
public static LogEntry createUserExceptionEntry(Throwable thrown, Category cat) {
return new LogEntry(ExceptionUtils.getStackTrace(thrown), thrown.getMessage(), cat, false);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
Throwable rootCause = ExceptionUtils.getRootCause(e);
rootCause.printStackTrace(System.err);
throw new CqlException("Unexpected exception caught during execution: " + e.getClass().getName() + "\nWith trace:\n" + ExceptionUtils.getStackTrace(e));
}
@Override
protected Object getEntity(Exception exception) {
return ExceptionUtils.getStackTrace(exception);
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
public AnalysisResponse getAnalysis(AnalysisRequest request) {
AnalysisResponse response = new AnalysisResponse();
try {
List<String> allMetrics = new ArrayList<>();
allMetrics.addAll(request.highMetrics);
allMetrics.addAll(request.lowMetrics);
conf.set(MacroBaseConf.DB_URL, request.pgUrl);
conf.set(MacroBaseConf.BASE_QUERY, request.baseQuery);
conf.set(MacroBaseConf.ATTRIBUTES, request.attributes);
conf.set(MacroBaseConf.METRICS, allMetrics);
conf.set(MacroBaseConf.LOW_METRIC_TRANSFORM, request.lowMetrics);
conf.set(MacroBaseConf.USE_PERCENTILE, true);
// temp hack to enable CSV loading
if (request.baseQuery.contains("csv://")) {
conf.set(MacroBaseConf.CSV_INPUT_FILE, request.baseQuery.replace("csv://", ""));
conf.set(MacroBaseConf.DATA_LOADER_TYPE, MacroBaseConf.DataIngesterType.CSV_LOADER);
}
Class c = Class.forName(conf.getString(MacroBaseConf.PIPELINE_NAME, BasicBatchedPipeline.class.getName()));
Object ao = c.newInstance();
if (!(ao instanceof Pipeline)) {
log.error("{} is not an instance of Pipeline! Exiting...", ao);
response.errorMessage = "Requested pipeline of type "+c.getName()+ " is not a Pipeline";
return response;
}
Pipeline pipeline = (Pipeline) ao;
List<AnalysisResult> results = pipeline.initialize(conf).run();
for (AnalysisResult result : results) {
if (result.getItemSets().size() > 1000) {
log.warn("Very large result set! {}; truncating to 1000", result.getItemSets().size());
result.setItemSets(result.getItemSets().subList(0, 1000));
}
}
response.results = results;
MacroBase.reporter.report();
} catch (Exception e) {
log.error("An error occurred while processing a request: {}", e);
response.errorMessage = ExceptionUtils.getStackTrace(e);
}
return response;
}
@Override
public InterpreterResult jobRun() throws Throwable {
ClassLoader currentThreadContextClassloader = Thread.currentThread().getContextClassLoader();
try {
InterpreterContext.set(context);
// clear the result of last run in frontend before running this paragraph.
context.out.clear();
InterpreterResult result = null;
// Open the interpreter instance prior to calling interpret().
// This is necessary because the earliest we can register a hook
// is from within the open() method.
LazyOpenInterpreter lazy = (LazyOpenInterpreter) interpreter;
if (!lazy.isOpen()) {
lazy.open();
result = lazy.executePrecode(context);
}
if (result == null || result.code() == Code.SUCCESS) {
// Add hooks to script from registry.
// note scope first, followed by global scope.
// Here's the code after hooking:
// global_pre_hook
// note_pre_hook
// script
// note_post_hook
// global_post_hook
processInterpreterHooks(context.getNoteId());
processInterpreterHooks(null);
LOGGER.debug("Script after hooks: " + script);
result = interpreter.interpret(script, context);
}
// data from context.out is prepended to InterpreterResult if both defined
context.out.flush();
List<InterpreterResultMessage> resultMessages = context.out.toInterpreterResultMessage();
for (InterpreterResultMessage resultMessage : result.message()) {
// only add non-empty InterpreterResultMessage
if (!StringUtils.isBlank(resultMessage.getData())) {
resultMessages.add(resultMessage);
}
}
List<String> stringResult = new ArrayList<>();
for (InterpreterResultMessage msg : resultMessages) {
if (msg.getType() == InterpreterResult.Type.IMG) {
LOGGER.debug("InterpreterResultMessage: IMAGE_DATA");
} else {
LOGGER.debug("InterpreterResultMessage: " + msg.toString());
}
stringResult.add(msg.getData());
}
// put result into resource pool
if (context.getLocalProperties().containsKey("saveAs")) {
if (stringResult.size() == 1) {
LOGGER.info("Saving result into ResourcePool as single string: " +
context.getLocalProperties().get("saveAs"));
context.getResourcePool().put(
context.getLocalProperties().get("saveAs"), stringResult.get(0));
} else {
LOGGER.info("Saving result into ResourcePool as string list: " +
context.getLocalProperties().get("saveAs"));
context.getResourcePool().put(
context.getLocalProperties().get("saveAs"), stringResult);
}
}
return new InterpreterResult(result.code(), resultMessages);
} catch (Throwable e) {
return new InterpreterResult(Code.ERROR, ExceptionUtils.getStackTrace(e));
} finally {
Thread.currentThread().setContextClassLoader(currentThreadContextClassloader);
InterpreterContext.remove();
}
}
/**
* Prints the stack trace.
*
* @param t
* the throwable
* @return the string
*/
public static String printStackTrace(Throwable t) {
return t == null ? PcConstants.NA : ExceptionUtils.getStackTrace(t);
}