Example usage for java.lang StackTraceElement getFileName

List of usage examples for java.lang StackTraceElement getFileName

Introduction

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

Prototype

public String getFileName() 

Source Link

Document

Returns the name of the source file containing the execution point represented by this stack trace element.

Usage

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);// w w  w. j av a  2  s.  c  o 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: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  ww .ja  va 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:comm.lib.downloader.log.Log.java

/**
 * Building Message//from  w  w  w  .j av a 2s.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() + " ";
                }/*  www. j  a va2s  .c o  m*/
            } catch (Exception e) {
                stackTrace += "-";
            }
            pw.print(thread.getThreadGroup().getName() + " " + thread.getId() + " " + stackTrace + "\n");
        }
    }
}

From source file:op.tools.SYSTools.java

public static String getThrowableAsHTML(Throwable exc) {
    String html = "";
    StackTraceElement[] stacktrace = exc.getStackTrace();

    html += SYSConst.html_h1("mail.errormail.attachment.line1");
    html += SYSConst.html_h2(exc.getClass().getName());
    html += SYSConst.html_paragraph(exc.getMessage());

    if (OPDE.getMainframe().getCurrentResident() != null) {
        html += SYSConst.html_h3("ResID: " + OPDE.getMainframe().getCurrentResident().getRID());
    }//from w  w w . j a  v a2 s .  c o  m

    html += SYSConst.html_h3(OPDE.getMainframe().getCurrentVisiblePanel().getInternalClassID());

    String table = SYSConst.html_table_th("mail.errormail.attachment.tab.col1")
            + SYSConst.html_table_th("mail.errormail.attachment.tab.col2")
            + SYSConst.html_table_th("mail.errormail.attachment.tab.col3")
            + SYSConst.html_table_th("mail.errormail.attachment.tab.col4");

    for (int exception = 0; exception < stacktrace.length; exception++) {
        StackTraceElement element = stacktrace[exception];
        table += SYSConst.html_table_tr(SYSConst.html_table_td(element.getMethodName())
                + SYSConst.html_table_td(Integer.toString(element.getLineNumber()))
                + SYSConst.html_table_td(element.getClassName())
                + SYSConst.html_table_td(element.getFileName()));
    }

    html += SYSConst.html_table(table, "1");

    // Possible Cause
    if (exc.getCause() != null) {
        html += SYSConst.html_h3("Caused by: " + exc.getCause().getMessage());
        StackTraceElement[] stacktrace1 = exc.getCause().getStackTrace();
        String table1 = SYSConst.html_table_th("mail.errormail.attachment.tab.col1")
                + SYSConst.html_table_th("mail.errormail.attachment.tab.col2")
                + SYSConst.html_table_th("mail.errormail.attachment.tab.col3")
                + SYSConst.html_table_th("mail.errormail.attachment.tab.col4");

        for (int exception = 0; exception < stacktrace1.length; exception++) {
            StackTraceElement element = stacktrace1[exception];
            table1 += SYSConst.html_table_tr(SYSConst.html_table_td(element.getMethodName())
                    + SYSConst.html_table_td(Integer.toString(element.getLineNumber()))
                    + SYSConst.html_table_td(element.getClassName())
                    + SYSConst.html_table_td(element.getFileName()));
        }

        html += SYSConst.html_table(table1, "1");
    }

    return html;
}

From source file:org.eluder.logback.ext.jackson.JacksonEncoder.java

protected void writeCallerData(JsonWriter.ObjectWriter<JsonWriter> writer, ILoggingEvent event)
        throws IOException {
    if (event.hasCallerData()) {
        StackTraceElement callerData = event.getCallerData()[0];
        JsonWriter.ObjectWriter<JsonWriter.ObjectWriter<JsonWriter>> ow = writer
                .writeObject(fieldNames.getCallerData(), isActive(fieldNames.getCallerData()));
        ow.writeStringField(fieldNames.getCallerClass(), callerData.getClassName(),
                isActive(fieldNames.getCallerClass()));
        ow.writeStringField(fieldNames.getCallerMethod(), callerData.getMethodName(),
                isActive(fieldNames.getCallerMethod()));
        ow.writeStringField(fieldNames.getCallerFile(), callerData.getFileName(),
                isActive(fieldNames.getCallerFile()));
        ow.writeNumberField(fieldNames.getCallerLine(), callerData.getLineNumber(),
                isActive(fieldNames.getCallerLine()));
        ow.done();//  w ww .j  a  v  a  2 s . c o  m
    }
}

From source file:com.coolstore.common.SLog.java

/**
 * Building Message/*from   w ww  .j  a  va2 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(" : ");
    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:com.clustercontrol.commons.util.JpaTransactionManager.java

/**
 * ?/*from w w w  . j a  v a  2s  .  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:org.sakaiproject.status.StatusServlet.java

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

    for (Thread thread : findAllThreads()) {
        if (thread != null) {
            String threadLocation = "";
            try {
                StackTraceElement ste = thread.getStackTrace()[0];
                StackTraceElement ste2 = thread.getStackTrace()[1];
                threadLocation = ste.getClassName() + "." + ste.getMethodName() + "()," + ste.getFileName()
                        + ":" + ste.getLineNumber() + "," + ste2.getClassName() + "." + ste2.getMethodName()
                        + "()," + ste2.getFileName() + ":" + ste2.getLineNumber();
            } catch (Exception e) {
                threadLocation = "?,?,?,?";
            }/*from w  w w.j  av  a  2s  .c om*/
            pw.print(thread.getThreadGroup().getName() + "," + thread.getId() + "," + thread.getName() + ","
                    + thread.getPriority() + "," + thread.getState().name() + ","
                    + (thread.isAlive() ? "" : "notalive") + "," + (thread.isDaemon() ? "daemon" : "") + ","
                    + (thread.isInterrupted() ? "interrupted" : "") + "," + threadLocation + "\n");
        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.util.ExceptionInformation.java

public ExceptionInformation(HttpServletRequest request, Throwable ex) {
    StringBuilder tempBuilder = new StringBuilder();

    StringBuilder exceptionInfo = headerAppend(ex);

    // user/*from   ww  w  . jav a  2  s  .c  o m*/
    this.requestBean = userInfoContextAppend(request, exceptionInfo);

    // mapping
    mappingContextAppend(request, exceptionInfo);

    // requestContext
    requestContextAppend(request, tempBuilder);
    this.requestContext = tempBuilder.toString();
    exceptionInfo.append("\n[RequestContext] \n");
    exceptionInfo.append(tempBuilder);
    exceptionInfo.append("\n\n");
    tempBuilder.setLength(0);

    // sessionContext
    exceptionInfo.append("\n[SessionContext]\n");
    sessionContextAppend(request, tempBuilder);
    this.sessionContext = tempBuilder.toString();
    exceptionInfo.append(tempBuilder);
    exceptionInfo.append("\n\n");
    tempBuilder.setLength(0);

    // stackTrace
    stackTrace2StringAppend(ex.getStackTrace(), tempBuilder);
    this.stackTrace = tempBuilder.toString();
    exceptionInfo.append(tempBuilder);

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    ex.printStackTrace(pw);
    String formattedST = sw.toString();
    this.formattedStackTrace = formattedST;

    ActionMapping mapping = this.getActionMapping();
    if (mapping != null) {
        StackTraceElement element = getStackTraceElementForActionMapping(request, mapping, ex.getStackTrace());
        if (element != null) {
            this.actionErrorFile = element.getFileName();
            this.actionErrorLine = element.getLineNumber();
        }
    }
    this.exceptionInfo = exceptionInfo.toString();

    if (ex.getClass().getName().equals("org.apache.jasper.JasperException")) {
        String message = ex.getLocalizedMessage();
        if (message.contains("\n")) {
            String[] name = message.split("\n");
            final Pattern lastIntPattern = Pattern.compile("([0-9]+)$");
            Matcher matcher = lastIntPattern.matcher(name[0]);
            if (matcher.find()) {
                jspExceptionLine = matcher.group(1);
                jspExceptionMessage = name[0];
                setJspExceptionSourceBefore(new ArrayList<JSPLine>());
                setJspExceptionSourceAfter(new ArrayList<JSPLine>());
                int state = 0;
                for (String s : Arrays.copyOfRange(name, 2, name.length - 3)) {
                    int i = s.indexOf(":");
                    JSPLine line = new JSPLine(s.substring(0, i).toString(),
                            s.substring(i + 1, s.length()).toString());
                    switch (state) {
                    case 0:
                        if (s.startsWith(jspExceptionLine)) {

                            setJspExceptionSourceLine(line);
                            state = 1;
                        } else {
                            getJspExceptionSourceBefore().add(line);
                        }
                        break;
                    case 1:
                        getJspExceptionSourceAfter().add(line);
                    default:
                        break;
                    }
                }
            }
        }
    }
}