Example usage for java.lang StackTraceElement getMethodName

List of usage examples for java.lang StackTraceElement getMethodName

Introduction

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

Prototype

public String getMethodName() 

Source Link

Document

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

Usage

From source file:info.magnolia.testframework.htmlunit.AbstractMagnoliaHtmlUnitTest.java

/**
 * Need to pass a StackTraceElement to determine the
 * current method, because we can't safely guess at what depth of the stack this method was called.
 * We're keeping this method separate from openPage() for the same reason: if a test/util method
 * calls the openPage method instead of the actual test, the stack won't reflect the "current test method"
 * properly./*www  . java2s  . c  o m*/
 */
protected void saveToFile(Page page, StackTraceElement stackTraceElement) throws IOException {
    final WebResponse res = page.getWebResponse();
    InputStream input = res.getContentAsStream();
    final byte[] body = IOUtils.toByteArray(input);
    // TODO : configure the output directory / get it from system properties ?
    final String path = "target/" + stackTraceElement.getClassName() + "-" + stackTraceElement.getMethodName()
            + "-" + stackTraceElement.getLineNumber() + ".out";
    IOUtils.write(body, new FileOutputStream(path));
}

From source file:com.jk.framework.util.FakeRunnable.java

/**
 * Prints the stack trace.//  w  w w .  jav a 2s  .c o m
 */
public static void printStackTrace() {
    final Throwable t = new Throwable();
    final StackTraceElement trace[] = t.getStackTrace();
    for (final StackTraceElement element : trace) {
        System.err.println(element.getClassName() + "." + element.getMethodName());
    }

}

From source file:org.seedstack.seed.core.api.SeedException.java

private boolean isInPrintStackTrace() {
    for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) {
        if (JAVA_LANG_THROWABLE.equals(stackTraceElement.getClassName())
                && PRINT_STACK_TRACE.equals(stackTraceElement.getMethodName())) {
            return true;
        }/*from   www  . j  av a2  s . c o m*/
    }

    return false;
}

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

/**
 * @param traceContext/*  w  w w .  j  a  v  a  2s . 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:com.gargoylesoftware.htmlunit.SimpleWebTestCase.java

/**
 * Finds from the call stack the active running JUnit test case
 * @return the test case method/* w ww.j a  v  a  2 s .c  o m*/
 * @throws RuntimeException if no method could be found
 */
private Method findRunningJUnitTestMethod() {
    final Class<?> cl = getClass();
    final Class<?>[] args = new Class[] {};

    // search the initial junit test
    final Throwable t = new Exception();
    for (int i = t.getStackTrace().length - 1; i >= 0; i--) {
        final StackTraceElement element = t.getStackTrace()[i];
        if (element.getClassName().equals(cl.getName())) {
            try {
                final Method m = cl.getMethod(element.getMethodName(), args);
                if (isPublicTestMethod(m)) {
                    return m;
                }
            } catch (final Exception e) {
                // can't access, ignore it
            }
        }
    }

    throw new RuntimeException("No JUnit test case method found in call stack");
}

From source file:org.nuxeo.binary.metadata.test.MetadataReaderTest.java

protected String getCurrentMethodName(RuntimeException e) {
    StackTraceElement currentElement = e.getStackTrace()[0];
    return currentElement.getMethodName();
}

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 w  w  .  j  a v  a2s  .com
    }
}

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

/**
 * Building Message//from  w w  w  .  j  a  v a 2s.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(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.micromata.genome.util.runtime.debug.PoorMansStackTraceProfiler.java

/**
 * Ignore stack trace.//www  . j  a v a2s  .  c  om
 *
 * @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:com.rb.ofbiz.test.utils.logging.LoggingCommandProcessor.java

/**
 * Log the current Command.// ww w  . jav  a 2  s.c o  m
 *
 * @param commandName
 *        commandName to be logged
 * @param args
 *        arguments to be logged
 * @param result
 *        the result to be logged
 * @param cmdStartMillis
 *        time in milliseconds when execution started
 */
void doLogging(String commandName, String[] args, String result, long cmdStartMillis) {
    LoggingBean currentCommand = LoggingCommandProcessor.presetLoggingBean(commandName, args, result,
            cmdStartMillis, System.currentTimeMillis());
    currentCommand.setExcludeFromLogging(isCommandExcludedFromLogging(commandName));
    currentCommand.setCallingClass(
            getRealCallingClassWithLineNumberAsString(getCurrentCallingClassAsStackTraceElement()));
    currentCommand.setWaitInvolved(isWaitInvolved());
    String sourceMethodName = "unknown";
    StackTraceElement classOrNull = getCurrentCallingClassAsStackTraceElement();
    if (null != classOrNull) {
        sourceMethodName = classOrNull.getMethodName();
    }
    currentCommand.setSourceMethod(sourceMethodName);
    loggingEventsQueue.add(currentCommand);
}