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:com.clustercontrol.commons.util.JpaTransactionManager.java

/**
 * ?/*from   ww w.  j av a  2 s  .co 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:mondrian.test.DiffRepository.java

/**
 * Returns the name of the current testcase by looking up the call
 * stack for a method whose name starts with "test", for example
 * "testFoo"./*from  w  w  w. ja va 2s.  c om*/
 *
 * @param fail Whether to fail if no method is found
 * @return Name of current testcase, or null if not found
 */
public String getCurrentTestCaseName(boolean fail) {
    // check thread-local first
    String testCaseName = CurrentTestCaseName.get();
    if (testCaseName != null) {
        return testCaseName;
    }

    // Clever, this. Dump the stack and look up it for a method which
    // looks like a testcase name, e.g. "testFoo".
    final StackTraceElement[] stackTrace;
    //noinspection ThrowableInstanceNeverThrown
    Throwable runtimeException = new Throwable();
    runtimeException.fillInStackTrace();
    stackTrace = runtimeException.getStackTrace();
    for (StackTraceElement stackTraceElement : stackTrace) {
        final String methodName = stackTraceElement.getMethodName();
        if (methodName.startsWith("test")) {
            return methodName;
        }
    }
    if (fail) {
        throw new RuntimeException("no testcase on current callstack");
    } else {
        return null;
    }
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

private static String getCallingMethod() {
    StackTraceElement[] trace = Thread.currentThread().getStackTrace();
    StackTraceElement element = trace[3];
    return String.format("%s.%s:%d", element.getClassName(), element.getMethodName(), element.getLineNumber());
}

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  .  ja  v a  2  s .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: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 w  w w.jav  a2s .  com*/
    }
    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);//from   w w w  .  ja v  a  2 s  . co  m
    }
    throw nex;
}

From source file:org.codehaus.plexus.archiver.zip.ZipArchiverTest.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//w  w  w  . j a v a2 s . c om
                .println("Cannot execute test: " + e.getMethodName() + " on " + System.getProperty("os.name"));
        return;
    }

    File tmpDir = null;
    try {
        tmpDir = File.createTempFile("zip-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<String, PlexusIoResourceAttributes> attributesByPath = PlexusIoResourceAttributeUtils
                    .getFileAttributesByPath(tmpDir);
            for (String path : executablePaths) {
                PlexusIoResourceAttributes attrs = attributesByPath.get(path);
                if (attrs == null) {
                    attrs = 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 = attributesByPath.get(path);
                if (attrs == null) {
                    attrs = 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 = attributesByPath.get(path);
                if (attrs == null) {
                    attrs = attributesByPath.get(new File(tmpDir, path).getAbsolutePath());
                }

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

        File zipFile = getTestFile("target/output/zip-with-modes.zip");

        ZipArchiver archiver = getZipArchiver(zipFile);

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

        assertTrue(zipFile.exists());

        File zipFile2 = getTestFile("target/output/zip-with-modes-L2.zip");

        archiver = getZipArchiver();
        archiver.setDestFile(zipFile2);

        archiver.addArchivedFileSet(zipFile);
        archiver.createArchive();

        ZipFile zf = new ZipFile(zipFile2);

        for (String path : executablePaths) {
            ZipArchiveEntry ze = zf.getEntry(path);

            int mode = ze.getUnixMode() & UnixStat.PERM_MASK;

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

        for (String path : confPaths) {
            ZipArchiveEntry ze = zf.getEntry(path);

            int mode = ze.getUnixMode() & UnixStat.PERM_MASK;

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

        for (String path : logPaths) {
            ZipArchiveEntry ze = zf.getEntry(path);

            int mode = ze.getUnixMode() & 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: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/*  w  w w.j a v a  2s.  com*/
 */
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:minium.script.rhinojs.RhinoEngine.java

protected StackTraceElement[] process(StackTraceElement[] stackTrace) {
    List<StackTraceElement> processed = Lists.newArrayList();
    for (StackTraceElement element : stackTrace) {
        if (element.getClassName().startsWith("org.mozilla.javascript.gen") && element.getLineNumber() != -1) {
            String fileName = null;
            File file = new File(element.getFileName());
            if (file.exists() && file.isFile()) {
                fileName = file.getAbsolutePath();
            }//  w  ww. j  ava  2 s  . c  o  m
            if (fileName == null)
                fileName = element.getFileName();
            processed.add(new StackTraceElement(element.getClassName(), element.getMethodName(), fileName,
                    element.getLineNumber()));
        }
    }
    return processed.toArray(new StackTraceElement[processed.size()]);
}