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:io.teak.sdk.Raven.java

public void reportException(Throwable t) {
    if (t == null) {
        return;//  ww w  .  ja v a  2 s  . c  o m
    }

    HashMap<String, Object> additions = new HashMap<>();
    ArrayList<Object> exceptions = new ArrayList<>();
    HashMap<String, Object> exception = new HashMap<>();

    exception.put("type", t.getClass().getSimpleName());
    exception.put("value", t.getMessage());
    exception.put("module", t.getClass().getPackage().getName());

    HashMap<String, Object> stacktrace = new HashMap<>();
    ArrayList<Object> stackFrames = new ArrayList<>();

    StackTraceElement[] steArray = t.getStackTrace();
    for (int i = steArray.length - 1; i >= 0; i--) {
        StackTraceElement ste = steArray[i];
        HashMap<String, Object> frame = new HashMap<>();

        frame.put("filename", ste.getFileName());

        String method = ste.getMethodName();
        if (method.length() != 0) {
            frame.put("function", method);
        }

        int lineno = ste.getLineNumber();
        if (!ste.isNativeMethod() && lineno >= 0) {
            frame.put("lineno", lineno);
        }

        String module = ste.getClassName();
        frame.put("module", module);

        boolean in_app = true;
        if (module.startsWith("android.") || module.startsWith("java.") || module.startsWith("dalvik.")
                || module.startsWith("com.android.")) {
            in_app = false;
        }

        frame.put("in_app", in_app);

        stackFrames.add(frame);
    }
    stacktrace.put("frames", stackFrames);

    exception.put("stacktrace", stacktrace);

    exceptions.add(exception);
    additions.put("exception", exceptions);

    try {
        Report report = new Report(t.getMessage(), Level.ERROR, additions);
        report.sendToService();
    } catch (Exception e) {
        Log.e(LOG_TAG, "Unable to report Teak SDK exception. " + Log.getStackTraceString(t) + "\n"
                + Log.getStackTraceString(e));
    }
}

From source file:org.openflamingo.remote.thrift.thriftfs.ThriftHandlerBase.java

/**
 * Return a list of threads that currently exist with their stack traces
 *//*from  ww  w  .  ja v  a  2s .c  o  m*/
public List<ThreadStackTrace> getThreadDump(RequestContext ctx) {
    List<ThreadStackTrace> dump = new ArrayList<ThreadStackTrace>();

    Map<Thread, StackTraceElement[]> traces = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> entry : traces.entrySet()) {
        final Thread t = entry.getKey();
        final StackTraceElement[] frames = entry.getValue();

        ThreadStackTrace tst = new ThreadStackTrace();
        tst.threadName = t.getName();
        tst.threadStringRepresentation = String.valueOf(t);
        tst.isDaemon = t.isDaemon();
        tst.stackTrace = new ArrayList<StackTraceElement>();
        for (StackTraceElement ste : frames) {
            StackTraceElement tFrame = new StackTraceElement();
            tFrame.className = ste.getClassName();
            tFrame.fileName = ste.getFileName();
            tFrame.lineNumber = ste.getLineNumber();
            tFrame.methodName = ste.getMethodName();
            tFrame.isNativeMethod = ste.isNativeMethod();
            tFrame.stringRepresentation = String.valueOf(ste);
            tst.stackTrace.add(tFrame);
        }
        dump.add(tst);
    }
    return dump;
}

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

public HttpResponse replayResponse() throws ClientServicesException {
    try {//from   w w  w  .j a  v  a2  s .co  m
        Node r = getReader().next();

        NamedNodeMap nnm = r.getAttributes();

        String code = nnm.getNamedItem("statusCode").getTextContent();
        String reason = nnm.getNamedItem("statusReason").getTextContent();

        Node headers = (Node) DOMUtil.evaluateXPath(r, "./headers").getSingleNode();
        Node data = (Node) DOMUtil.evaluateXPath(r, "./data").getSingleNode();
        String entity = null;
        if (data != null) {
            if (data.getFirstChild() == null)
                entity = "";
            else
                entity = ((CharacterData) data.getFirstChild()).getData();
        }
        Iterator<Node> hIt = (Iterator<Node>) DOMUtil.evaluateXPath(headers, "./header").getNodeIterator();
        ArrayList<Header> allHeaders = new ArrayList<Header>();

        while (hIt.hasNext()) {
            Node headerNode = hIt.next();
            String name = ((Node) DOMUtil.evaluateXPath(headerNode, "./name").getSingleNode()).getTextContent();
            String value = ((Node) DOMUtil.evaluateXPath(headerNode, "./value").getSingleNode())
                    .getTextContent();
            allHeaders.add(new BasicHeader(name, value));
        }

        return buildResponse(allHeaders.toArray(new Header[allHeaders.size()]), Integer.valueOf(code), reason,
                entity);

    } catch (FileNotFoundException e) {
        StackTraceElement trace = getStackTraceElement();
        String fullClassName = trace.getClassName();
        String methodName = trace.getMethodName();
        String endpointName = getEndpointName();
        throw new MockingException(e,
                "Mocking file missing for test: " + fullClassName + "." + methodName + "/" + endpointName);
    } catch (Exception e) {
        throw new MockingException(e, "Corrupted Mocking file, please regenerate: " + getPath());
    }
}

From source file:org.openmrs.module.privilegehelper.PrivilegeLogger.java

/**
 * Inspects the stack trace to find a place where the privilege was checked
 * /* w  ww. jav a2 s  .  c o m*/
 * @return the class.method or <code>null</code> if it cannot be found
 */
private StackTraceInfo inspectStackTrace() {
    final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    boolean requiredPrivilege = false;
    for (int i = 0; i < stackTrace.length; i++) {
        final StackTraceElement unrelatedElement = stackTrace[i];

        if (UserContext.class.getName().equals(unrelatedElement.getClassName())
                && "hasPrivilege".equals(unrelatedElement.getMethodName())) {

            for (int j = i + 1; j < stackTrace.length; j++) {
                final StackTraceElement element = stackTrace[j];

                if (element.getFileName() != null && element.getFileName().endsWith("_jsp")) {
                    String jsp = element.getFileName();
                    int indexOfView = jsp.indexOf("view");
                    if (indexOfView > 0) {
                        jsp = jsp.substring(indexOfView);
                    }
                    jsp = jsp.replace(".", "/");
                    jsp = jsp.replace("_", ".");

                    return new StackTraceInfo(jsp, requiredPrivilege);
                }

                if (!element.getClassName().startsWith("org.openmrs")) {
                    continue;
                }

                //Determine if it is a required privilege or a simple check
                if (RequireTag.class.getName().equals(element.getClassName())) {
                    requiredPrivilege = true;
                    continue;
                }
                if (PrivilegeTag.class.getName().equals(element.getClassName())) {
                    requiredPrivilege = false;
                    continue;
                }
                if (AuthorizationAdvice.class.getName().equals(element.getClassName())) {
                    requiredPrivilege = true;
                    continue;
                }
                if (Context.class.getName().equals(element.getClassName())) {
                    if ("requirePrivilege".equals(element.getMethodName())) {
                        requiredPrivilege = true;
                    }
                    continue;
                }

                try {
                    final Class<?> clazz = OpenmrsClassLoader.getInstance().loadClass(element.getClassName());

                    if (clazz.isAnnotationPresent(Controller.class)) {
                        String url = "";

                        final RequestMapping clazzRequestMapping = clazz.getAnnotation(RequestMapping.class);
                        if (clazzRequestMapping != null) {
                            url = clazzRequestMapping.value()[0];
                        }

                        final Method[] methods = clazz.getMethods();
                        for (Method method : methods) {
                            if (method.getName().equals(element.getMethodName())) {
                                final RequestMapping requestMapping = method
                                        .getAnnotation(RequestMapping.class);
                                if (requestMapping != null) {
                                    url += requestMapping.value()[0];
                                }
                                break;
                            }
                        }

                        if (url.isEmpty()) {
                            return new StackTraceInfo(element.toString(), requiredPrivilege);
                        } else {
                            return new StackTraceInfo(element.toString() + ", URL: " + url, requiredPrivilege);
                        }
                    }
                } catch (ClassNotFoundException e) {
                }

                return new StackTraceInfo(element.toString(), requiredPrivilege);
            }
        }
    }
    return null;
}

From source file:org.apache.log4j.layout.Log4j1XmlLayout.java

private void formatTo(final LogEvent event, final StringBuilder buf) {
    // We yield to the \r\n heresy.

    buf.append("<log4j:event logger=\"");
    buf.append(Transform.escapeHtmlTags(event.getLoggerName()));
    buf.append("\" timestamp=\"");
    buf.append(event.getTimeMillis());/*  w  w w. j  av a  2 s . c  o m*/
    buf.append("\" level=\"");
    buf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
    buf.append("\" thread=\"");
    buf.append(Transform.escapeHtmlTags(event.getThreadName()));
    buf.append("\">\r\n");

    buf.append("<log4j:message><![CDATA[");
    // Append the rendered message. Also make sure to escape any existing CDATA sections.
    Transform.appendEscapingCData(buf, event.getMessage().getFormattedMessage());
    buf.append("]]></log4j:message>\r\n");

    List<String> ndc = event.getContextStack().asList();
    if (!ndc.isEmpty()) {
        buf.append("<log4j:NDC><![CDATA[");
        Transform.appendEscapingCData(buf, StringUtils.join(ndc, ' '));
        buf.append("]]></log4j:NDC>\r\n");
    }

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    Throwable thrown = event.getThrown();
    if (thrown != null) {
        buf.append("<log4j:throwable><![CDATA[");
        buf.append(thrown.toString());
        buf.append("\r\n");
        for (StackTraceElement element : thrown.getStackTrace()) {
            Transform.appendEscapingCData(buf, "\tat " + element.toString());
            buf.append("\r\n");
        }
        buf.append("]]></log4j:throwable>\r\n");
    }

    if (locationInfo) {
        StackTraceElement source = event.getSource();
        if (source != null) {
            buf.append("<log4j:locationInfo class=\"");
            buf.append(Transform.escapeHtmlTags(source.getClassName()));
            buf.append("\" method=\"");
            buf.append(Transform.escapeHtmlTags(source.getMethodName()));
            buf.append("\" file=\"");
            buf.append(Transform.escapeHtmlTags(source.getFileName()));
            buf.append("\" line=\"");
            buf.append(source.getLineNumber());
            buf.append("\"/>\r\n");
        }
    }

    if (properties) {
        Map<String, String> contextMap = event.getContextMap();
        if (!contextMap.isEmpty()) {
            buf.append("<log4j:properties>\r\n");
            Object[] keys = contextMap.keySet().toArray();
            Arrays.sort(keys);
            for (Object key1 : keys) {
                String key = key1.toString();
                String val = contextMap.get(key);
                if (val != null) {
                    buf.append("<log4j:data name=\"");
                    buf.append(Transform.escapeHtmlTags(key));
                    buf.append("\" value=\"");
                    buf.append(Transform.escapeHtmlTags(val));
                    buf.append("\"/>\r\n");
                }
            }
            buf.append("</log4j:properties>\r\n");
        }
    }

    buf.append("</log4j:event>\r\n\r\n");
}

From source file:org.eclipse.wb.internal.core.editor.UndoManager.java

private void scheduleRefresh_onBufferChange() {
    final int bufferChangeCount = ++m_bufferChangeCount;
    Runnable runnable = new Runnable() {
        public void run() {
            if (isStillInSave()) {
                Display.getDefault().timerExec(1, this);
                return;
            }/*w  w w.j a v  a  2 s.  c  om*/
            if (bufferChangeCount == m_bufferChangeCount) {
                refreshDesignerEditor();
            }
        }

        /**
         * Save operation may run event loops, so wait for finishing "doSave()" to reparse when save
         * is complete. This allows also avoid deadlock in case if we will join to wait for finishing
         * auto build job.
         */
        private boolean isStillInSave() {
            String editorClassName = "org.eclipse.wb.internal.core.editor.multi.DesignerEditor";
            StackTraceElement[] elements = new Exception().getStackTrace();
            for (StackTraceElement element : elements) {
                if (element.getClassName().equals(editorClassName)) {
                    if (element.getMethodName().equals("doSave")) {
                        return true;
                    }
                }
            }
            return false;
        }
    };
    Display.getDefault().asyncExec(runnable);
}

From source file:com.taobao.adfs.util.Utilities.java

/**
 * not support more override method, ASM is a better solution.
 * refer: http://stackoverflow.com/questions/4024587/get-callers-method-not-name
 *//*from w  ww .j  a  va2 s . co  m*/
public static Method getCaller(boolean staticMethod) throws IOException {
    StackTraceElement caller = Thread.currentThread().getStackTrace()[3];
    Class<?> clazz = ClassCache.getWithIOException(caller.getClassName());
    for (Method method : clazz.getDeclaredMethods()) {
        if (!method.getName().equals(caller.getMethodName()))
            continue;
        if (Modifier.isStatic(method.getModifiers()) != staticMethod)
            continue;
        return method;
    }
    throw new IOException("fail to get caller");
}

From source file:Main.java

public static String getCompressedStackTrace(Throwable t, int startAt, int limit) {
    try {/*  ww w. j  a  va2 s . co m*/
        StackTraceElement[] stackTrace = t.getStackTrace();
        if (stackTrace.length < startAt) {
            return "";
        }
        StringBuilder sb = new StringBuilder("");
        for (int i = startAt; i < stackTrace.length && i < startAt + limit; i++) {
            StackTraceElement element = stackTrace[i];
            String classname = element.getClassName();
            String cnShort;
            boolean showLineNumber = true;
            boolean breakAfter = false;
            if (classname.startsWith("com.vuze.android.remote.")) {
                cnShort = classname.substring(24, classname.length());
            } else if (classname.equals("android.os.Handler")) {
                showLineNumber = false;
                cnShort = "Handler";
            } else if (classname.equals("android.os.Looper")) {
                showLineNumber = false;
                cnShort = "Looper";
                breakAfter = true;
            } else if (classname.length() < 9) { // include full if something like aa.ab.ac
                cnShort = classname;
            } else {
                int len = classname.length();
                int start = len > 14 ? len - 14 : 0;

                int pos = classname.indexOf('.', start);
                if (pos >= 0) {
                    start = pos + 1;
                }
                cnShort = classname.substring(start, len);
            }
            if (i != startAt) {
                sb.append(", ");
            }
            sb.append(cnShort);
            sb.append('.');
            sb.append(element.getMethodName());
            if (showLineNumber) {
                sb.append(':');
                sb.append(element.getLineNumber());
            }
            if (breakAfter) {
                break;
            }
        }
        Throwable cause = t.getCause();
        if (cause != null) {
            sb.append("\n|Cause ");
            sb.append(cause.getClass().getSimpleName());
            if (cause instanceof Resources.NotFoundException || cause instanceof RuntimeException) {
                sb.append(' ');
                sb.append(cause.getMessage());
            }
            sb.append(' ');
            sb.append(getCompressedStackTrace(cause, 0, 9));
        }
        return sb.toString();
    } catch (Throwable derp) {
        return "derp " + derp.getClass().getSimpleName();
    }
}

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  ww. java2 s . c om*/
            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.chenxin.authority.common.logback.DBAppender.java

void bindCallerDataWithPreparedStatement(PreparedStatement stmt, StackTraceElement[] callerDataArray)
        throws SQLException {
    StackTraceElement callerData = callerDataArray[0];
    if (callerData != null) {
        stmt.setString(CALLER_FILENAME_INDEX, callerData.getFileName());
        stmt.setString(CALLER_CLASS_INDEX, callerData.getClassName());
        stmt.setString(CALLER_METHOD_INDEX, callerData.getMethodName());
        stmt.setString(CALLER_LINE_INDEX, Integer.toString(callerData.getLineNumber()));
    }/* ww w  .j  ava2  s . co  m*/
}