Example usage for java.lang StackTraceElement getLineNumber

List of usage examples for java.lang StackTraceElement getLineNumber

Introduction

In this page you can find the example usage for java.lang StackTraceElement getLineNumber.

Prototype

public int getLineNumber() 

Source Link

Document

Returns the line number of the source line containing the execution point represented by this stack trace element.

Usage

From source file:org.apache.fineract.infrastructure.jobs.service.JobRegisterServiceImpl.java

private String getStackTraceAsString(final Throwable throwable) {
    final StackTraceElement[] stackTraceElements = throwable.getStackTrace();
    final StringBuffer sb = new StringBuffer(throwable.toString());
    for (final StackTraceElement element : stackTraceElements) {
        sb.append("\n \t at ").append(element.getClassName()).append(".").append(element.getMethodName())
                .append("(").append(element.getLineNumber()).append(")");
    }//from w ww  .  j ava  2s  . com
    return sb.toString();
}

From source file:org.j2free.error.HoptoadNotifier.java

private Element createBacktraceNode(Document doc, Throwable thrown, StackTraceElement lastFrame) {
    Element node = doc.createElement("backtrace"), e;
    if (thrown != null) {
        for (StackTraceElement frame : thrown.getStackTrace()) {
            e = doc.createElement("line");
            e.setAttribute("file", frame.getFileName());
            e.setAttribute("number", String.valueOf(frame.getLineNumber()));
            e.setAttribute("method", frame.getMethodName());
            node.appendChild(e);//from   w  ww .  j a  v  a2 s . co m
        }

        Throwable rootCause = unwindException(thrown);
        if (rootCause != null && rootCause != thrown) {
            // DIVIDER --- 
            e = doc.createElement("line");
            e.setAttribute("file", "--------------------");
            e.setAttribute("number", "0");
            e.setAttribute("method", "--------------------");
            node.appendChild(e);

            for (StackTraceElement frame : rootCause.getStackTrace()) {
                e = doc.createElement("line");
                e.setAttribute("file", frame.getFileName());
                e.setAttribute("number", String.valueOf(frame.getLineNumber()));
                e.setAttribute("method", frame.getMethodName());
                node.appendChild(e);
            }
        }
    } else if (lastFrame != null) {
        e = doc.createElement("line");
        e.setAttribute("file", lastFrame.getFileName());
        e.setAttribute("number", String.valueOf(lastFrame.getLineNumber()));
        e.setAttribute("method", lastFrame.getMethodName());
        node.appendChild(e);
    } else {
        e = doc.createElement("line");
        e.setAttribute("file", "unknown");
        e.setAttribute("number", "0");
        e.setAttribute("method", "unknown");
        node.appendChild(e);
    }
    return node;
}

From source file:de.xwic.appkit.core.trace.impl.TraceDataManager.java

/**
 * @param traceContext/*from ww w  . j a v a2  s  .  c  o  m*/
 */
private synchronized void logContext(ITraceContext tx, OutputStream out) {

    if (traceLogFile != null) {

        long start = tx.getStartTime();
        PrintWriter pw = new PrintWriter(out);
        pw.println("---------------------------------------------------------------------");
        pw.println("Start-Time: " + DateFormat.getDateTimeInstance().format(new Date(start)));
        pw.println("Total-Duration: " + tx.getDuration());
        if (tx.getName() != null) {
            pw.println("Name: " + tx.getName());
        }
        if (tx.getInfo() != null) {
            pw.println("Info: " + tx.getInfo());
        }
        pw.println("Attributes:");
        Map<String, String> attrs = tx.getAttributes();
        for (String key : attrs.keySet()) {
            pw.println("   " + key + "=" + attrs.get(key));
        }
        if (traceLevel != TraceLevel.BASIC) {
            pw.println();
            Map<String, ITraceCategory> catMap = tx.getTraceCategories();
            for (String cat : catMap.keySet()) {
                ITraceCategory category = catMap.get(cat);
                pw.println("[ " + cat + " (" + category.getCount() + " op(s) / " + category.getTotalDuration()
                        + "ms)]");
                if (traceLevel == TraceLevel.DETAILED) {
                    for (ITraceOperation op : category.getTraceOperations()) {
                        pw.println(String.format("# %s [start: %d; end: %d; total: %d ms]", op.getName(),
                                op.getStartTime() - start, op.getEndTime() - start, op.getDuration()));
                        if (op.getInfo() != null) {
                            pw.println(op.getInfo());
                        }
                    }
                }
            }

            List<StackTraceSnapShot> snapShots = tx.getStackTraceSnapShots();
            if (snapShots.size() > 0) {
                pw.println();
                pw.println("SnapShots taken:");
                StringBuilder sb = new StringBuilder();
                String previous = null;
                for (StackTraceSnapShot ss : snapShots) {
                    sb.setLength(0);
                    pw.println("StackTrace at " + (ss.getSnapShotTime() - start) + "ms");
                    for (StackTraceElement elm : ss.getStackTrace()) {
                        sb.append("  " + elm.getClassName() + "." + elm.getMethodName() + "(..):"
                                + elm.getLineNumber()).append("\n");
                    }
                    if (sb.toString().equals(previous)) {
                        pw.println("[ SAME AS PREVIOUS Stack Trace ]");
                    } else {
                        previous = sb.toString();
                        pw.print(previous);
                    }
                    pw.println("----");
                }
            }

        }
        pw.flush();

    } else {
        log.warn("Can not log trace details as no traceLogFile is defined.");
    }

}

From source file:org.apache.log4j.layout.Log4j1XmlLayout.java

private void formatTo(final LogEvent event, final StringBuilder buf) {
    // We yield to the \r\n heresy.

    buf.append("<log4j:event logger=\"");
    buf.append(Transform.escapeHtmlTags(event.getLoggerName()));
    buf.append("\" timestamp=\"");
    buf.append(event.getTimeMillis());//  w  w  w . j  av  a 2  s  .  c  o m
    buf.append("\" level=\"");
    buf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
    buf.append("\" thread=\"");
    buf.append(Transform.escapeHtmlTags(event.getThreadName()));
    buf.append("\">\r\n");

    buf.append("<log4j:message><![CDATA[");
    // Append the rendered message. Also make sure to escape any existing CDATA sections.
    Transform.appendEscapingCData(buf, event.getMessage().getFormattedMessage());
    buf.append("]]></log4j:message>\r\n");

    List<String> ndc = event.getContextStack().asList();
    if (!ndc.isEmpty()) {
        buf.append("<log4j:NDC><![CDATA[");
        Transform.appendEscapingCData(buf, StringUtils.join(ndc, ' '));
        buf.append("]]></log4j:NDC>\r\n");
    }

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    Throwable thrown = event.getThrown();
    if (thrown != null) {
        buf.append("<log4j:throwable><![CDATA[");
        buf.append(thrown.toString());
        buf.append("\r\n");
        for (StackTraceElement element : thrown.getStackTrace()) {
            Transform.appendEscapingCData(buf, "\tat " + element.toString());
            buf.append("\r\n");
        }
        buf.append("]]></log4j:throwable>\r\n");
    }

    if (locationInfo) {
        StackTraceElement source = event.getSource();
        if (source != null) {
            buf.append("<log4j:locationInfo class=\"");
            buf.append(Transform.escapeHtmlTags(source.getClassName()));
            buf.append("\" method=\"");
            buf.append(Transform.escapeHtmlTags(source.getMethodName()));
            buf.append("\" file=\"");
            buf.append(Transform.escapeHtmlTags(source.getFileName()));
            buf.append("\" line=\"");
            buf.append(source.getLineNumber());
            buf.append("\"/>\r\n");
        }
    }

    if (properties) {
        Map<String, String> contextMap = event.getContextMap();
        if (!contextMap.isEmpty()) {
            buf.append("<log4j:properties>\r\n");
            Object[] keys = contextMap.keySet().toArray();
            Arrays.sort(keys);
            for (Object key1 : keys) {
                String key = key1.toString();
                String val = contextMap.get(key);
                if (val != null) {
                    buf.append("<log4j:data name=\"");
                    buf.append(Transform.escapeHtmlTags(key));
                    buf.append("\" value=\"");
                    buf.append(Transform.escapeHtmlTags(val));
                    buf.append("\"/>\r\n");
                }
            }
            buf.append("</log4j:properties>\r\n");
        }
    }

    buf.append("</log4j:event>\r\n\r\n");
}

From source file:org.apache.archiva.web.test.parent.AbstractSeleniumTest.java

public String captureScreenShotOnFailure(Throwable failure, String methodName, String className) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd-HH_mm_ss");
    String time = sdf.format(new Date());
    File targetPath = new File("target", "screenshots");

    int lineNumber = 0;

    for (StackTraceElement stackTrace : failure.getStackTrace()) {
        if (stackTrace.getClassName().equals(this.getClass().getName())) {
            lineNumber = stackTrace.getLineNumber();
            break;
        }//  ww  w . j  a  v  a  2  s  . c  om
    }

    targetPath.mkdirs();
    Selenium selenium = getSelenium();
    String fileBaseName = methodName + "_" + className + ".java_" + lineNumber + "-" + time;

    selenium.windowMaximize();

    try {
        // save html to have a minimum feedback if jenkins firefox not up
        File fileNameHTML = new File(new File("target", "errorshtmlsnap"), fileBaseName + ".html");
        FileUtils.writeStringToFile(fileNameHTML, selenium.getHtmlSource());
    } catch (IOException e) {
        System.out.print(e.getMessage());
        e.printStackTrace();
    }

    File fileName = new File(targetPath, fileBaseName + ".png");

    selenium.captureEntirePageScreenshot(fileName.getAbsolutePath(), "background=#FFFFFF");

    return fileName.getAbsolutePath();
}

From source file:comm.lib.downloader.log.Log.java

/**
 * Building Message//  w  w w .j  av a 2  s  .c o m
 *
 * @param msg The message you would like logged.
 * @return Message String
 */
protected static String buildMessage(TYPE type, String tag, String msg, Throwable thr) {
    //set the default log path
    if (TextUtils.isEmpty(path)) {
        setPath(logDirPath, logFileBaseName, logFileSuffix);
    }

    StackTraceElement caller = new Throwable().fillInStackTrace().getStackTrace()[2];

    boolean isLog2File = false;

    switch (policy) {
    case LOG_NONE_TO_FILE:
        isLog2File = false;
        break;
    case LOG_WARN_TO_FILE:
        if (type == TYPE.WARN) {
            isLog2File = true;
        } else {
            isLog2File = false;
        }
        break;
    case LOG_ERROR_TO_FILE:
        if (type == TYPE.ERROR) {
            isLog2File = true;
        } else {
            isLog2File = false;
        }
        break;
    case LOG_ALL_TO_FILE:
        isLog2File = true;
        break;
    default:
        break;
    }

    //The log will be shown in logcat.
    StringBuffer bufferlog = new StringBuffer();
    bufferlog.append(caller.getClassName());
    bufferlog.append(".");
    bufferlog.append(caller.getMethodName());
    bufferlog.append("( ");
    bufferlog.append(caller.getFileName());
    bufferlog.append(": ");
    bufferlog.append(caller.getLineNumber());
    bufferlog.append(") ");
    bufferlog.append(System.getProperty("line.separator"));
    bufferlog.append(msg);
    if (thr != null) {
        bufferlog.append(System.getProperty("line.separator"));
        bufferlog.append(android.util.Log.getStackTraceString(thr));
    }

    if (isLog2File) {
        //The log will be written in the log file.
        StringBuffer filelog = new StringBuffer();
        filelog.append(type.name());
        filelog.append("    ");
        filelog.append(tag);
        filelog.append("    ");
        filelog.append(bufferlog);

        Log2File.log2file(path, filelog.toString());
    }

    return bufferlog.toString();
}

From source file:org.sakaiproject.status.StatusServlet.java

protected void reportThreadStackTraces(HttpServletResponse response) throws Exception {
    PrintWriter pw = response.getWriter();

    for (Thread thread : findAllThreads()) {
        if (thread != null) {
            String stackTrace = "";
            try {
                StackTraceElement[] stack = thread.getStackTrace();
                for (StackTraceElement ste : stack) {
                    stackTrace += ste.getClassName() + "." + ste.getMethodName() + "();" + ste.getFileName()
                            + ":" + ste.getLineNumber() + " ";
                }//  w w  w .j ava2s. c o  m
            } catch (Exception e) {
                stackTrace += "-";
            }
            pw.print(thread.getThreadGroup().getName() + " " + thread.getId() + " " + stackTrace + "\n");
        }
    }
}

From source file:org.apache.lens.cube.parse.TestCubeRewriter.java

static void compareContains(String expected, String actual) {
    if (expected == null && actual == null) {
        return;//  w ww  . j  a  va2 s  . co m
    } else if (expected == null) {
        fail();
    } else if (actual == null) {
        fail("Rewritten query is null");
    }
    String expectedTrimmed = expected.replaceAll("\\W", "");
    String actualTrimmed = actual.replaceAll("\\W", "");

    if (!actualTrimmed.toLowerCase().contains(expectedTrimmed.toLowerCase())) {
        String method = null;
        for (StackTraceElement trace : Thread.currentThread().getStackTrace()) {
            if (trace.getMethodName().startsWith("test")) {
                method = trace.getMethodName() + ":" + trace.getLineNumber();
            }
        }

        System.err.println(
                "__FAILED__ " + method + "\n\tExpected: " + expected + "\n\t---------\n\tActual: " + actual);
    }
    assertTrue(actualTrimmed.toLowerCase().contains(expectedTrimmed.toLowerCase()),
            "Expected:" + expected + "Actual:" + actual);
}

From source file:com.clustercontrol.commons.util.JpaTransactionManager.java

/**
 * ?/*from  w ww.j a  va 2  s  . c  o m*/
 */
public void close() {
    if (!nestedEm && em != null) {
        if (em.isOpen()) {
            try {
                List<JpaTransactionCallback> callbacks = getCallbacks();

                if (!isCallbacked()) {
                    for (JpaTransactionCallback callback : callbacks) {
                        if (m_log.isDebugEnabled()) {
                            m_log.debug("executing callback preClose : " + callback.getClass().getName());
                        }
                        try {
                            setCallbacked();

                            callback.preClose();
                        } catch (Throwable t) {
                            m_log.warn("callback execution failure : " + callback.getClass().getName(), t);
                        } finally {
                            unsetCallbacked();
                        }
                    }
                }

                // commit or rollback???close?????????(rollback)?
                // ???connection????????
                EntityTransaction tx = em.getTransaction();
                if (tx.isActive()) {
                    if (m_log.isDebugEnabled()) {
                        StackTraceElement[] eList = Thread.currentThread().getStackTrace();
                        StringBuilder trace = new StringBuilder();
                        for (StackTraceElement e : eList) {
                            if (trace.length() > 0) {
                                trace.append("\n");
                            }
                            trace.append(String.format("%s.%s(%s:%d)", e.getClassName(), e.getMethodName(),
                                    e.getFileName(), e.getLineNumber()));
                        }
                        m_log.debug(
                                "closing uncompleted transaction. this transaction will be rollbacked before closing : "
                                        + trace);
                    }
                    tx.rollback();
                }

                em.close();
                HinemosSessionContext.instance().setProperty(JpaTransactionManager.EM, null);

                // postClose???innerTransaction????????callback???
                for (JpaTransactionCallback callback : callbacks) {
                    if (m_log.isDebugEnabled()) {
                        m_log.debug("executing callback postClose : " + callback.getClass().getName());
                    }
                    try {
                        callback.postClose();
                    } catch (Throwable t) {
                        m_log.warn("callback execution failure : " + callback.getClass().getName(), t);
                    }
                }
            } finally {
                HinemosSessionContext.instance().setProperty(JpaTransactionManager.EM, null);
            }
        }
        HinemosSessionContext.instance().setProperty(EM, null);
    }
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

private static String getCallingMethod() {
    StackTraceElement[] trace = Thread.currentThread().getStackTrace();
    StackTraceElement element = trace[3];
    return String.format("%s.%s:%d", element.getClassName(), element.getMethodName(), element.getLineNumber());
}