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:com.coolstore.common.SLog.java

/**
 * Building Message//  w w  w .  java 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(" : ");
    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:de.micromata.genome.tpsb.CommonTestBuilder.java

protected T failImpl(AssertionFailedException ex) {
    ex.setTestBuilder(this);
    StackTraceElement el = AssertUtils.getStackAbove(this.getClass());
    if (el != null) {
        String line = StringUtils.trim(AssertUtils.getCodeLine(el));
        ex.setClassName(el.getClassName());
        ex.setMethodName(el.getMethodName());
        ex.setLineNo(el.getLineNumber());
        ex.setCodeLine(line);//from ww  w. ja  v a 2  s.  co  m
    }
    throw ex;
}

From source file:de.micromata.genome.tpsb.CommonTestBuilder.java

protected T failImpl(Exception ex) {
    AssertionFailedException nex = new AssertionFailedException(ex);
    nex.setTestBuilder(this);
    StackTraceElement el = AssertUtils.getStackAbove(this.getClass());
    if (el != null) {
        String line = StringUtils.trim(AssertUtils.getCodeLine(el));
        nex.setClassName(el.getClassName());
        nex.setMethodName(el.getMethodName());
        nex.setLineNo(el.getLineNumber());
        nex.setCodeLine(line);/*  w w  w. j  a  v  a  2s.  c om*/
    }
    throw nex;
}

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 = "?,?,?,?";
            }/* ww w. j  a  v a 2 s.  co  m*/
            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:com.rvantwisk.cnctools.controllers.CNCToolsController.java

/**
 * Handle exception and show a strack trace, at least to inform the user that something was wrong
 * This is also a last resort, if you can handle the exception in the dialog, please do so and instruct the user!
 *
 * @param exception/*from w w w  .  j a  v  a  2s  . c o  m*/
 */
public void handleException(Exception exception) {
    logger.error("generateGCode: General Exception", exception);
    final FXMLDialog dialog = screens.errorDialog();
    ErrorController controller = dialog.getController();
    StringBuilder sb = new StringBuilder();

    sb.append(exception.toString()).append("\n");
    for (StackTraceElement trace : exception.getStackTrace()) {
        if (trace.getClassName().startsWith("com.rvantwisk")) {
            sb.append(trace.getClassName()).append(":").append(trace.getMethodName()).append(":")
                    .append(trace.getLineNumber()).append("\n");
        }
    }
    controller.setMessage(sb.toString());
    dialog.showAndWait();
}

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();/*from  w  ww. j  ava  2  s.c om*/
    }
}

From source file:com.liferay.document.library.webdav.test.BaseWebDAVTestCase.java

public Tuple service(String method, String path, Map<String, String> headers, byte[] data) {

    WebDAVServlet webDAVServlet = new WebDAVServlet();

    String requestURI = _CONTEXT_PATH + _SERVLET_PATH + _PATH_INFO_PREFACE + path;

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method, requestURI);

    mockHttpServletRequest.setContextPath(_CONTEXT_PATH);
    mockHttpServletRequest.setServletPath(_SERVLET_PATH);
    mockHttpServletRequest.setPathInfo(_PATH_INFO_PREFACE + path);

    try {//w  w  w.j a v  a  2  s  .c om
        mockHttpServletRequest.setRemoteUser(String.valueOf(TestPropsValues.getUserId()));
    } catch (Exception e) {
        Assert.fail("User ID cannot be initialized");
    }

    if (headers == null) {
        headers = new HashMap<>();
    }

    headers.put(HttpHeaders.USER_AGENT, getUserAgent());

    try {
        throw new Exception();
    } catch (Exception e) {
        StackTraceElement[] stackTraceElements = e.getStackTrace();

        for (StackTraceElement stackTraceElement : stackTraceElements) {
            String methodName = stackTraceElement.getMethodName();

            if (methodName.equals("setUp") || methodName.equals("tearDown") || methodName.startsWith("test")) {

                String testName = StringUtil.extractLast(stackTraceElement.getClassName(), CharPool.PERIOD);

                testName = StringUtil.removeSubstrings(testName, "WebDAV", "Test");

                headers.put("X-Litmus", testName + ": (" + stackTraceElement.getMethodName() + ":"
                        + stackTraceElement.getLineNumber() + ")");

                break;
            }
        }
    }

    if (data != null) {
        mockHttpServletRequest.setContent(data);

        String contentType = headers.remove(HttpHeaders.CONTENT_TYPE);

        if (contentType != null) {
            mockHttpServletRequest.setContentType(contentType);
        } else {
            mockHttpServletRequest.setContentType(ContentTypes.TEXT_PLAIN);
        }
    }

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();

        mockHttpServletRequest.addHeader(key, value);
    }

    try {
        MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

        webDAVServlet.service(mockHttpServletRequest, mockHttpServletResponse);

        int statusCode = mockHttpServletResponse.getStatus();
        byte[] responseBody = mockHttpServletResponse.getContentAsByteArray();

        Map<String, String> responseHeaders = new HashMap<>();

        for (String name : mockHttpServletResponse.getHeaderNames()) {
            responseHeaders.put(name, mockHttpServletResponse.getHeader(name));
        }

        return new Tuple(statusCode, responseBody, responseHeaders);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

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  .  j  a v  a2 s. com
    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;
                    }
                }
            }
        }
    }
}

From source file:com.taobao.itest.spring.aop.LogInterceptor.java

public Object invoke(MethodInvocation invocation) throws Throwable {
    Object object = invocation.getThis();
    Method method = invocation.getMethod();
    Object[] args = invocation.getArguments();

    if (!log.isDebugEnabled() || !matches(method.getName()))
        return invocation.proceed();

    StackTraceElement[] stes = new Throwable().getStackTrace();
    StackTraceElement testSte = null;
    for (int i = 0; i < stes.length; i++) {
        if (stes[i].getClassName().endsWith("Test")) {
            testSte = stes[i];/*  w w  w  . j  a v a2  s. com*/
            break;
        }
    }

    if (testSte == null)
        return invocation.proceed();

    boolean isTestMethod = testSte.getMethodName().startsWith("test");
    if (testSte == null || !isTestMethod)
        return invocation.proceed();
    String callerClassSimpleName = testSte.getClassName()
            .substring(testSte.getClassName().lastIndexOf(".") + 1);
    if (!callerClassSimpleName.endsWith("Test"))
        return invocation.proceed();
    String callerMethodName = testSte.getMethodName();
    int lineNumber = testSte.getLineNumber();
    String callerInfo = callerClassSimpleName + "." + callerMethodName
            + (lineNumber >= 0 ? "(" + lineNumber + ")" : "(Unknown Source)");
    String invokeClassSimpleName = ClassUtils.getShortClassName(object.getClass());
    String invokeInfo = invokeClassSimpleName + "." + method.getName();
    String baseInfo = callerInfo + "  |" + invokeInfo + " ";
    if (logInvokeParams) {
        log.debug(baseInfo + " invoked with params:");
        for (int i = 0; i < args.length; i++) {
            log.debug("param " + (i + 1) + ": ");
            println(args[i]);
        }
    }
    Object result = null;
    try {
        result = invocation.proceed();
    } catch (Exception e) {
        log.debug(baseInfo + " throw exception: ");
        log.debug(e.getMessage());
        throw e;
    }
    if (logInvokeResult) {
        log.debug(baseInfo + " invoked result is: ");
        println(result);
    }

    return result;
}