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:org.apache.maven.surefire.its.fixture.MavenLauncher.java

String getTestMethodName() {
    // dirty. Im sure we can use junit4 rules to attach testname to thread instead
    StackTraceElement[] stackTrace = getStackTraceElements();
    StackTraceElement topInTestClass;
    topInTestClass = findTopElemenent(stackTrace, testCaseBeingRun);
    if (topInTestClass == null) {
        // Look in superclass...
        topInTestClass = findTopElemenent(stackTrace, testCaseBeingRun.getSuperclass());
    }//from ww w.j a  v  a2s. c o m
    if (topInTestClass != null) {
        return topInTestClass.getMethodName();
    }
    throw new IllegalStateException("Cannot find " + testCaseBeingRun.getName() + "in stacktrace");
}

From source file:org.codehaus.plexus.archiver.tar.TarArchiverTest.java

public void testCreateArchiveWithDetectedModes() throws Exception {

    String[] executablePaths = { "path/to/executable", "path/to/executable.bat" };

    String[] confPaths = { "path/to/etc/file", "path/to/etc/file2" };

    String[] logPaths = { "path/to/logs/log.txt" };

    int exeMode = 0777;
    int confMode = 0600;
    int logMode = 0640;

    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
        StackTraceElement e = new Throwable().getStackTrace()[0];
        System.out/*from  w  w  w  .  j  a  va 2 s . c o m*/
                .println("Cannot execute test: " + e.getMethodName() + " on " + System.getProperty("os.name"));
        return;
    }

    File tmpDir = null;
    try {
        tmpDir = File.createTempFile("tbz2-with-chmod.", ".dir");
        tmpDir.delete();

        tmpDir.mkdirs();

        for (String executablePath : executablePaths) {
            writeFile(tmpDir, executablePath, exeMode);
        }

        for (String confPath : confPaths) {
            writeFile(tmpDir, confPath, confMode);
        }

        for (String logPath : logPaths) {
            writeFile(tmpDir, logPath, logMode);
        }

        {
            Map attributesByPath = PlexusIoResourceAttributeUtils.getFileAttributesByPath(tmpDir);
            for (String path : executablePaths) {
                PlexusIoResourceAttributes attrs = (PlexusIoResourceAttributes) attributesByPath.get(path);
                if (attrs == null) {
                    attrs = (PlexusIoResourceAttributes) attributesByPath
                            .get(new File(tmpDir, path).getAbsolutePath());
                }

                assertNotNull(attrs);
                assertEquals("Wrong mode for: " + path + "; expected: " + exeMode, exeMode,
                        attrs.getOctalMode());
            }

            for (String path : confPaths) {
                PlexusIoResourceAttributes attrs = (PlexusIoResourceAttributes) attributesByPath.get(path);
                if (attrs == null) {
                    attrs = (PlexusIoResourceAttributes) attributesByPath
                            .get(new File(tmpDir, path).getAbsolutePath());
                }

                assertNotNull(attrs);
                assertEquals("Wrong mode for: " + path + "; expected: " + confMode, confMode,
                        attrs.getOctalMode());
            }

            for (String path : logPaths) {
                PlexusIoResourceAttributes attrs = (PlexusIoResourceAttributes) attributesByPath.get(path);
                if (attrs == null) {
                    attrs = (PlexusIoResourceAttributes) attributesByPath
                            .get(new File(tmpDir, path).getAbsolutePath());
                }

                assertNotNull(attrs);
                assertEquals("Wrong mode for: " + path + "; expected: " + logMode, logMode,
                        attrs.getOctalMode());
            }
        }

        File tarFile = getTestFile("target/output/tar-with-modes.tar");

        TarArchiver archiver = getPosixTarArchiver();
        archiver.setDestFile(tarFile);

        archiver.addDirectory(tmpDir);
        archiver.createArchive();

        assertTrue(tarFile.exists());

        File tarFile2 = getTestFile("target/output/tar-with-modes-L2.tar");

        archiver = getPosixTarArchiver();
        archiver.setDestFile(tarFile2);

        archiver.addArchivedFileSet(tarFile);
        archiver.createArchive();

        TarFile tf = new TarFile(tarFile2);

        Map<String, TarArchiveEntry> entriesByPath = new LinkedHashMap<String, TarArchiveEntry>();
        for (Enumeration e = tf.getEntries(); e.hasMoreElements();) {
            TarArchiveEntry te = (TarArchiveEntry) e.nextElement();
            entriesByPath.put(te.getName(), te);
        }

        for (String path : executablePaths) {
            TarArchiveEntry te = entriesByPath.get(path);

            int mode = te.getMode() & UnixStat.PERM_MASK;

            assertEquals("Wrong mode for: " + path + "; expected: " + exeMode, exeMode, mode);
        }

        for (String path : confPaths) {
            TarArchiveEntry te = entriesByPath.get(path);

            int mode = te.getMode() & UnixStat.PERM_MASK;

            assertEquals("Wrong mode for: " + path + "; expected: " + confMode, confMode, mode);
        }

        for (String path : logPaths) {
            TarArchiveEntry te = entriesByPath.get(path);

            int mode = te.getMode() & UnixStat.PERM_MASK;

            assertEquals("Wrong mode for: " + path + "; expected: " + logMode, logMode, mode);
        }
    } finally {
        if (tmpDir != null && tmpDir.exists()) {
            try {
                FileUtils.forceDelete(tmpDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.jretty.log.Jdk14Logger.java

/**
 * Fill in caller data if possible.//from ww w. j  ava2s  .  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:org.apache.lens.cube.parse.TestCubeRewriter.java

static void compareContains(String expected, String actual) {
    if (expected == null && actual == null) {
        return;//from  ww w .  jav  a 2  s  .c om
    } 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.coolstore.common.SLog.java

/**
 * Building Message/*w w  w  .  j  a  v  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(" : ");
    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:at.tugraz.ist.catroweb.BaseTest.java

private String getCalleeName() {
    StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    for (StackTraceElement item : stack) {
        String entry = item.toString();
        if (entry.matches("at.tugraz.ist.catroweb.*") && !entry.matches("at.tugraz.ist.catroweb.BaseTest.*")) {
            return item.getMethodName();
        }/* w  ww  . j  a va2s.c  om*/
    }
    return null;
}

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  ww .j  a v  a2  s  .c  o  m*/
            } catch (Exception e) {
                stackTrace += "-";
            }
            pw.print(thread.getThreadGroup().getName() + " " + thread.getId() + " " + stackTrace + "\n");
        }
    }
}

From source file:com.ibm.sbt.test.lib.MockSerializer.java

private String getPath() {
    StackTraceElement trace = getStackTraceElement();
    String basePath = System.getProperty("user.dir");
    String fullClassName = trace.getClassName().replace(".", File.separator);
    String className = fullClassName.substring(fullClassName.lastIndexOf(File.separatorChar));
    String packageName = fullClassName.substring(0, fullClassName.lastIndexOf(File.separatorChar));
    String methodName = trace.getMethodName();
    String endpointName = getEndpointName();
    String path = new StringBuilder(basePath).append(File.separator).append("src").append(File.separator)
            .append("test").append(File.separator).append("resources").append(File.separator)
            .append(packageName).append(File.separator).append("mockData").append(File.separator)
            .append(endpointName).append(className).append("_").append(methodName).append(".mock").toString();
    return path;/* w w w.  ja v  a2  s. c o m*/
}

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  w w.j  ava  2  s .  c om
        }

        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:net.sourceforge.fenixedu.presentationTier.util.ExceptionInformation.java

private final StackTraceElement getStackTraceElementForActionMapping(HttpServletRequest request,
        ActionMapping mapping, StackTraceElement[] elements) {
    Class<?> actionClass = actionClass(mapping.getType());
    setActionErrorClass(actionClass);/*from  ww w  . ja  va2  s  .  c om*/
    String methodName = DispatchAction.class.isAssignableFrom(actionClass)
            ? request.getParameter(mapping.getParameter())
            : "execute";
    setActionErrorMethod(methodName);
    for (StackTraceElement element : elements) {
        if (element.getClassName().equals(mapping.getType()) && element.getMethodName().equals(methodName)) {
            return element;
        }
    }
    return null;
}