Example usage for java.lang Throwable getStackTrace

List of usage examples for java.lang Throwable getStackTrace

Introduction

In this page you can find the example usage for java.lang Throwable getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:com.evolveum.midpoint.schema.result.OperationResult.java

private void dumpInnerCauses(StringBuilder sb, Throwable innerCause, int indent) {
    if (innerCause == null) {
        return;/*w ww . j ava  2s. c om*/
    }
    for (int i = 0; i < indent; i++) {
        sb.append(INDENT_STRING);
    }
    sb.append("Caused by ");
    sb.append(innerCause.getClass().getName());
    sb.append(": ");
    sb.append(innerCause.getMessage());
    sb.append("\n");
    dumpStackTrace(sb, innerCause.getStackTrace(), indent + 1);
    dumpInnerCauses(sb, innerCause.getCause(), indent);
}

From source file:org.nightlabs.jfire.trade.Article.java

public void setReleaseException(Throwable t) {
    if (t == null) {
        this.releaseExceptionClass = null;
        this.releaseExceptionMessage = null;
        this.releaseExceptionStackTrace = null;
        return;//w w w.  j a  va 2 s  . co m
    }

    Throwable root = ExceptionUtils.getRootCause(t);
    if (root == null)
        root = t;
    StackTraceElement ste = root.getStackTrace()[0];

    this.releaseExceptionClass = root.getClass().getName();
    this.releaseExceptionMessage = root.getLocalizedMessage();
    this.releaseExceptionStackTrace = ste.toString();
}

From source file:net.sf.ehcache.constructs.web.filter.Filter.java

/**
 * This method should throw IOExceptions, not wrap them.
 *///w  w w  .  j av a  2  s  .c o m
private void logThrowable(final Throwable throwable, final HttpServletRequest httpRequest)
        throws ServletException, IOException {
    StringBuffer messageBuffer = new StringBuffer("Throwable thrown during doFilter on request with URI: ")
            .append(httpRequest.getRequestURI()).append(" and Query: ").append(httpRequest.getQueryString());
    String message = messageBuffer.toString();
    boolean matchFound = matches(throwable);
    if (matchFound) {
        try {
            if (suppressStackTraces) {
                Method method = Log.class.getMethod(exceptionsToLogDifferentlyLevel,
                        new Class[] { Object.class });
                method.invoke(LOG, new Object[] { throwable.getMessage() });
            } else {
                Method method = Log.class.getMethod(exceptionsToLogDifferentlyLevel,
                        new Class[] { Object.class, Throwable.class });
                method.invoke(LOG, new Object[] { throwable.getMessage(), throwable });
            }
        } catch (Exception e) {
            LOG.fatal("Could not invoke Log method for " + exceptionsToLogDifferentlyLevel, e);
        }
        if (throwable instanceof IOException) {
            throw (IOException) throwable;
        } else {
            throw new ServletException(message, throwable);
        }
    } else {

        if (suppressStackTraces) {
            LOG.warn(messageBuffer.append(throwable.getMessage()).append("\nTop StackTraceElement: ")
                    .append(throwable.getStackTrace()[0].toString()));
        } else {
            LOG.warn(messageBuffer.append(throwable.getMessage()), throwable);
        }
        if (throwable instanceof IOException) {
            throw (IOException) throwable;
        } else {
            throw new ServletException(throwable);
        }
    }
}

From source file:org.apache.hadoop.hbase.ipc.ScheduleHBaseServer.java

@Override
public Writable call(Writable param, long receivedTime) throws IOException {
    try {//w ww. ja va  2 s.c  om
        Invocation call = (Invocation) param;
        if (call.getMethodName() == null) {
            throw new IOException("Could not find requested method, the usual "
                    + "cause is a version mismatch between client and server.");
        }

        Method method = implementation.getMethod(call.getMethodName(), call.getParameterClasses());

        long startTime = System.currentTimeMillis();

        Object value = method.invoke(instance, call.getParameters());
        /**
         * do with openScanner option, added by ScheduleHBaseServer
         */
        if (call.getMethodName().endsWith("openScanner")) {
            this.initScannerPri(call, value);
        }

        int processingTime = (int) (System.currentTimeMillis() - startTime);
        int qTime = (int) (startTime - receivedTime);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Served: " + call.getMethodName() + " queueTime= " + qTime + " procesingTime= "
                    + processingTime);
        }
        rpcMetrics.rpcQueueTime.inc(qTime);
        rpcMetrics.rpcProcessingTime.inc(processingTime);
        rpcMetrics.inc(call.getMethodName(), processingTime);

        return new HbaseObjectWritable(method.getReturnType(), value);

    } catch (InvocationTargetException e) {
        Throwable target = e.getTargetException();
        if (target instanceof IOException) {
            throw (IOException) target;
        }
        IOException ioe = new IOException(target.toString());
        ioe.setStackTrace(target.getStackTrace());
        throw ioe;
    } catch (Throwable e) {
        IOException ioe = new IOException(e.toString());
        ioe.setStackTrace(e.getStackTrace());
        throw ioe;
    }
}

From source file:com.hijacker.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override//from  ww w  .  j  a v  a 2s .  c  om
        public void uncaughtException(Thread thread, Throwable throwable) {
            throwable.printStackTrace();
            String stackTrace = "";
            stackTrace += throwable.getMessage() + '\n';
            for (int i = 0; i < throwable.getStackTrace().length; i++) {
                stackTrace += throwable.getStackTrace()[i].toString() + '\n';
            }

            Intent intent = new Intent();
            intent.setAction("com.hijacker.SendLogActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra("exception", stackTrace);
            startActivity(intent);

            finish();
            System.exit(1);
        }
    });
    adapter = new MyListAdapter(); //ALWAYS BEFORE setContentView AND setup(), can't stress it enough...
    adapter.setNotifyOnChange(true);
    custom_action_adapter = new CustomActionAdapter();
    custom_action_adapter.setNotifyOnChange(true);
    file_explorer_adapter = new FileExplorerAdapter();
    file_explorer_adapter.setNotifyOnChange(true);
    setContentView(R.layout.activity_main);
    setSupportActionBar((Toolbar) findViewById(R.id.my_toolbar));

    //Google AppIndex
    client = new GoogleApiClient.Builder(MainActivity.this).addApi(AppIndex.API).build();

    //fullSetup();
    new SetupTask().execute();
}

From source file:sf.net.experimaestro.server.JsonRPCMethods.java

/**
 * Run javascript/* w w w .  j  a  va2s. c  o  m*/
 */
@RPCMethod(name = "run-javascript", help = "Run a javascript")
public String runJSScript(@RPCArgument(name = "files") List<JSONArray> files,
        @RPCArgument(name = "environment") Map<String, String> environment,
        @RPCArgument(name = "debug", required = false) Integer debugPort) {

    final StringWriter errString = new StringWriter();
    //        final PrintWriter err = new PrintWriter(errString);

    final Hierarchy loggerRepository = getScriptLogger();

    // TODO: should be a one shot repository - ugly
    Repositories repositories = new Repositories(new File("/").toPath());
    repositories.add(repository, 0);

    // Creates and enters a Context. The Context stores information
    // about the execution environment of a script.
    try (XPMContext jsXPM = new XPMContext(environment, repositories, scheduler, loggerRepository, debugPort)) {
        Object result = null;
        for (JSONArray filePointer : files) {
            boolean isFile = filePointer.size() < 2 || filePointer.get(1) == null;
            final String content = isFile ? null : filePointer.get(1).toString();
            final String filename = filePointer.get(0).toString();

            final LocalhostConnector connector = LocalhostConnector.getInstance();
            Path locator = connector.resolve(filename);
            if (isFile)
                result = jsXPM.evaluateReader(connector, locator, new FileReader(filename), filename, 1, null);
            else
                result = jsXPM.evaluateString(connector, locator, content, filename, 1, null);

        }

        if (result != null)
            LOGGER.debug("Returns %s", result.toString());
        else
            LOGGER.debug("Null result");

        return result != null && result != Scriptable.NOT_FOUND && result != Undefined.instance
                ? result.toString()
                : "";

    } catch (ExitException e) {
        if (e.getCode() == 0) {
            return null;
        }
        throw e;
    } catch (Throwable e) {
        Throwable wrapped = e;
        LOGGER.info("Exception thrown there: %s", e.getStackTrace()[0]);
        while (wrapped.getCause() != null)
            wrapped = wrapped.getCause();

        LOGGER.printException(Level.INFO, wrapped);

        org.apache.log4j.Logger logger = loggerRepository.getLogger("xpm-rpc");

        logger.error(wrapped.toString());

        for (Throwable ee = e; ee != null; ee = ee.getCause()) {
            if (ee instanceof ContextualException) {
                ContextualException ce = (ContextualException) ee;
                List<String> context = ce.getContext();
                if (!context.isEmpty()) {
                    logger.error("[Context]");
                    for (String s : context) {
                        logger.error(s);
                    }
                }
            }
        }

        if (wrapped instanceof NotImplementedException)
            logger.error(format("Line where the exception was thrown: %s", wrapped.getStackTrace()[0]));

        logger.error("[Stack trace]");
        final ScriptStackElement[] scriptStackTrace = JSUtils.getScriptStackTrace(wrapped);
        for (ScriptStackElement x : scriptStackTrace) {
            logger.error(format("  at %s:%d (%s)", x.fileName, x.lineNumber, x.functionName));
        }

        // TODO: We should have something better
        //            if (wrapped instanceof RuntimeException && !(wrapped instanceof RhinoException)) {
        //                err.format("Internal error:%n");
        //                e.printStackTrace(err);
        //            }

        throw new RuntimeException(errString.toString());

    }
}

From source file:org.apache.hadoop.hive.ql.exec.vector.VectorizationContext.java

public static String getStackTraceAsSingleLine(Throwable e) {
    StringBuilder sb = new StringBuilder();
    sb.append(e);//from  ww w . j  ava2  s.  co m
    sb.append(" stack trace: ");
    StackTraceElement[] stackTrace = e.getStackTrace();
    int length = stackTrace.length;
    boolean isTruncated = false;
    if (length > STACK_LENGTH_LIMIT) {
        length = STACK_LENGTH_LIMIT;
        isTruncated = true;
    }
    for (int i = 0; i < length; i++) {
        if (i > 0) {
            sb.append(", ");
        }
        sb.append(stackTrace[i]);
    }
    if (isTruncated) {
        sb.append(", ...");
    }

    // Attempt to cleanup stack trace elements that vary by VM.
    String cleaned = sb.toString().replaceAll("GeneratedConstructorAccessor[0-9]*",
            "GeneratedConstructorAccessor<omitted>");

    return cleaned;
}

From source file:lucee.runtime.tag.Http.java

private PageException toPageException(Throwable t, HTTPResponse4Impl rsp) {
    if (t instanceof SocketTimeoutException) {
        HTTPException he = new HTTPException("408 Request Time-out", "a timeout occurred in tag http", 408,
                "Time-out", rsp == null ? null : rsp.getURL());
        List<StackTraceElement> merged = ArrayUtil.merge(t.getStackTrace(), he.getStackTrace());
        StackTraceElement[] traces = new StackTraceElement[merged.size()];
        Iterator<StackTraceElement> it = merged.iterator();
        int index = 0;
        while (it.hasNext()) {
            traces[index++] = it.next();
        }/*from  www .jav a  2 s. co  m*/
        he.setStackTrace(traces);
        return he;
    }
    PageException pe = Caster.toPageException(t);
    if (pe instanceof NativeException) {
        ((NativeException) pe).setAdditional(KeyConstants._url, url);
    }
    return pe;
}

From source file:org.pentaho.di.core.Const.java

public static String getCustomStackTrace(Throwable aThrowable) {
    final StringBuilder result = new StringBuilder();
    String errorMessage = aThrowable.toString();
    result.append(errorMessage);//from   www  .java  2 s.c o  m
    if (!errorMessage.contains(Const.CR)) {
        result.append(CR);
    }

    // add each element of the stack trace
    //
    for (StackTraceElement element : aThrowable.getStackTrace()) {
        result.append(element);
        result.append(CR);
    }
    return result.toString();
}