Example usage for java.lang StackTraceElement getClassName

List of usage examples for java.lang StackTraceElement getClassName

Introduction

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

Prototype

public String getClassName() 

Source Link

Document

Returns the fully qualified name of the class containing the execution point represented by this stack trace element.

Usage

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

/**
 * Building Message//from  w  w  w  .  j a  v 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:de.xwic.appkit.core.trace.impl.TraceDataManager.java

/**
 * @param traceContext/*from  w  ww. ja  va2s .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.jretty.log.Jdk14Logger.java

/**
 * Fill in caller data if possible./*from  www . j  a v a 2s.  c o  m*/
 * 
 * @param record
 *            The record to update
 */
private final void fillCallerData(String callerFQCN, LogRecord record) {
    StackTraceElement[] steArray = new Throwable().getStackTrace();
    int selfIndex = -1;
    for (int i = 0; i < steArray.length; i++) {
        final String className = steArray[i].getClassName();
        if (className.equals(callerFQCN)) {
            selfIndex = i;
            break;
        }
    }

    int found = -1;
    for (int i = selfIndex + 1; i < steArray.length; i++) {
        final String className = steArray[i].getClassName();
        if (!(className.equals(callerFQCN))) {
            found = i;
            break;
        }
    }

    if (found != -1) {
        StackTraceElement ste = steArray[found];
        // setting the class name has the side effect of setting
        // the needToInferCaller variable to false.
        record.setSourceClassName(ste.getClassName());
        record.setSourceMethodName(ste.getMethodName());
    }
}

From source file:de.micromata.genome.util.runtime.debug.PoorMansStackTraceProfiler.java

/**
 * Ignore stack trace./*from   w  w w  .j  av  a 2s . co m*/
 *
 * @param se the se
 * @param depth the depth
 * @return true, if successful
 */
private boolean ignoreStackTrace(StackTraceElement se, int depth) {
    if (maxDepthStack != -1 && depth > maxDepthStack) {
        return true;
    }
    if (ignoreMatcher == null) {
        return false;
    }
    String fqname = se.getClassName() + "." + se.getMethodName();
    if (ignoreMatcher.match(fqname) == true) {
        return true;
    }
    return false;
}

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;
        }//from  ww w  .ja  v  a2  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:com.coolstore.common.SLog.java

/**
 * Building Message/*from ww w.  j a v  a2  s .  c  om*/
 *
 * @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.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 {/*from w  w  w.  j ava  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:com.redhat.rhn.common.localization.LocalizationService.java

private StackTraceElement getCallingMethod() {
    try {// w  w w.j a v  a2s . c o  m
        throw new RuntimeException("Stacktrace Dummy Exception");
    } catch (RuntimeException e) {
        try {
            final String prefix = this.getClass().getPackage().getName();
            for (StackTraceElement element : e.getStackTrace()) {
                if (!element.getClassName().startsWith(prefix)) {
                    return element;
                }
            }
        } catch (Throwable t) {
            // dont break - return nothing rather than stop
            return null;
        }
    }
    return null;
}

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];/*from w w  w .j av  a 2s. 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;
}

From source file:com.galeoconsulting.leonardinius.rest.service.ScriptRunner.java

private String getStackTrace(Throwable th) {
    if (th == null) {
        return "";
    }// w  w w.  jav  a  2 s.c  om

    List<StackTraceElement> elements = Lists.newArrayList();
    for (StackTraceElement st : th.getStackTrace()) {
        if (st.getClassName().equals(CLASS_NAME))
            break;
        elements.add(st);
    }

    return new StringBuilder(ExceptionUtils.getMessage(th)).append(" at ")
            .append(Joiner.on("\n ").skipNulls().join(elements)).toString();
}