Java Code Examples for org.apache.commons.lang3.exception.ExceptionUtils#getStackTrace()

The following examples show how to use org.apache.commons.lang3.exception.ExceptionUtils#getStackTrace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ActionWithProgress.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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);
        }
    });
}
 
Example 2
Source File: ExceptionReturner.java    From aceql-http with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
    * 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();
}

   }
 
Example 3
Source File: BeanUtilTest.java    From fastquery with Apache License 2.0 5 votes vote down vote up
@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("主键值,必须传递!"));
	}
}
 
Example 4
Source File: ConditionHelpers.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * 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);
        }
    };
}
 
Example 5
Source File: JupyterKernelInterpreter.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example 6
Source File: FileStorage.java    From cuba with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 7
Source File: LogItem.java    From cuba with Apache License 2.0 5 votes vote down vote up
public String getStacktrace() {
    if (fullStackTrace != null) {
        return fullStackTrace;
    }

    return throwable != null ? ExceptionUtils.getStackTrace(throwable) : "";
}
 
Example 8
Source File: PersistenceManager.java    From cuba with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 9
Source File: ClassLoaderManager.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public String reloadClass(String className) {
    try {
        javaClassLoader.removeClass(className);
        return loadClass(className);
    } catch (Exception e) {
        return ExceptionUtils.getStackTrace(e);
    }
}
 
Example 10
Source File: BaseOptimizationRunner.java    From deeplearning4j with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: ClusterManager.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public String stop() {
    try {
        clusterManager.stop();
        return "Done";
    } catch (Exception e) {
        log.error("Unable to stop the cluster", e);
        return ExceptionUtils.getStackTrace(e);
    }
}
 
Example 12
Source File: JXErrorPaneExt.java    From cuba with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example 13
Source File: JobError.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 14
Source File: ReferenceCCDAValidationService.java    From reference-ccda-validator with BSD 2-Clause "Simplified" License 5 votes vote down vote up
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);
}
 
Example 15
Source File: AnalyzeResource.java    From macrobase with Apache License 2.0 4 votes vote down vote up
@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;
}
 
Example 16
Source File: DefaultExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
protected Object getEntity(Exception exception) {
    return ExceptionUtils.getStackTrace(exception);
}
 
Example 17
Source File: CqlExceptionHandler.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
@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));
}
 
Example 18
Source File: RemoteInterpreterServer.java    From zeppelin with Apache License 2.0 4 votes vote down vote up
@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();
  }
}
 
Example 19
Source File: LogEntry.java    From pmd-designer with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static LogEntry createUserExceptionEntry(Throwable thrown, Category cat) {
    return new LogEntry(ExceptionUtils.getStackTrace(thrown), thrown.getMessage(), cat, false);
}
 
Example 20
Source File: PcStringUtils.java    From parallec with Apache License 2.0 2 votes vote down vote up
/**
 * 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);

}