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.zywx.wbpalmstar.engine.EBrowserView.java

protected void printThreadStackTrace() {
    StackTraceElement[] stak = Thread.currentThread().getStackTrace();
    String s = "";
    int len = stak.length;
    for (int i = 0; i < len; ++i) {
        StackTraceElement one = stak[i];
        String className = one.getClassName();
        String methodName = one.getMethodName();
        int line = one.getLineNumber();
        String x = s + className + "." + methodName + " [" + line + "]";
        x.charAt(0);/*from  w  w  w  .  ja v a2s  .  com*/
        if (i == 0 || i == 1 || i == 2) {
            s += " ";
        }
    }
}

From source file:com.ichi2.libanki.Collection.java

/**
 * Logging/*from  w w  w.  j  a va 2 s  . co  m*/
 * ***********************************************************
 */

public void log(Object... args) {
    if (!mDebugLog) {
        return;
    }
    StackTraceElement trace = Thread.currentThread().getStackTrace()[3];
    // Overwrite any args that need special handling for an appropriate string representation
    for (int i = 0; i < args.length; i++) {
        if (args[i] instanceof long[]) {
            args[i] = Arrays.toString((long[]) args[i]);
        }
    }
    String s = String.format("[%s] %s:%s(): %s", Utils.intNow(), trace.getFileName(), trace.getMethodName(),
            TextUtils.join(",  ", args));
    mLogHnd.println(s);
    Timber.d(s);
}

From source file:edu.isi.wings.ontapi.jena.KBAPIJena.java

private boolean checkNulls(Object... vars) {
    for (Object var : vars) {
        if (var == null) {
            StackTraceElement[] stack = Thread.currentThread().getStackTrace();
            StackTraceElement method = stack[2];
            StackTraceElement caller = stack[3];
            String warnstr = method.getMethodName() + ": " + Arrays.toString(vars);
            warnstr += ", called from " + caller.getFileName() + ":" + caller.getLineNumber();
            Logger.getLogger(this.getClass()).warn(warnstr);
            return false;
        }//from   ww w. ja  v  a 2 s. co  m
    }
    return true;
}

From source file:org.sakaiproject.portal.charon.SkinnableCharonPortal.java

private void logXEntry() {
    Exception e = new Exception();
    StackTraceElement se = e.getStackTrace()[1];
    M_log.info("Log marker " + se.getMethodName() + ":" + se.getFileName() + ":" + se.getLineNumber());
}

From source file:org.wso2.carbon.repository.core.EmbeddedRepository.java

private void endDBQueryLog(int level) {
    if (dbQueryLog.isDebugEnabled()) {
        StackTraceElement traceElement = Thread.currentThread().getStackTrace()[level];
        String methodName = traceElement.getMethodName();

        if (!statEnabledOperations.isEmpty() && statEnabledOperations.contains(methodName)) {
            if (traceElement.getClassName().equals(this.getClass().getCanonicalName())) {
                StatisticsRecord statisticsRecord = DBQueryStatisticsLog.getStatisticsRecord();
                if (statisticsRecord.decrement() == 0) {
                    final StatisticsRecord clone = new StatisticsRecord(statisticsRecord);
                    Runnable runnable = new Runnable() {
                        public void run() {
                            if (clone.getTableRecords().length > 0) {
                                dbQueryLog.debug("");
                                dbQueryLog.debug("---------------------------------------------------");
                                dbQueryLog.debug("Registry Operation: " + clone.getOperation());
                                dbQueryLog.debug("");
                                for (String record : clone.getTableRecords()) {
                                    dbQueryLog.debug("Tables Accessed: " + record);
                                }//from  w  w  w  . j  av a 2 s.  co  m
                                if (Boolean.toString(true).equals(System
                                        .getProperty("carbon.registry.statistics.output. queries.executed"))) {
                                    dbQueryLog.debug("");
                                    StringBuffer sb = new StringBuffer();
                                    for (String query : clone.getQueries()) {
                                        sb.append("\n").append(query);
                                    }
                                    dbQueryLog.debug("Queries Executed:" + sb.toString());
                                }
                                dbQueryLog.debug("---------------------------------------------------");
                                dbQueryLog.debug("");
                            }
                        }
                    };

                    if (executor != null) {
                        executor.submit(runnable);
                    } else {
                        initializeStatisticsLogging();
                        executor.submit(runnable);
                    }

                    DBQueryStatisticsLog.clearStatisticsRecord();
                }
            }
        }
    }
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * Creates an UnhandledException dialog.
 * @param message the string/*from   www.j  a v  a 2s. c om*/
 */
/*public static void showUnhandledException(final String message)
{
UnhandledExceptionDialog dlg = instance.new UnhandledExceptionDialog(message);
dlg.setVisible(true);
throw new RuntimeException(message);
}*/

protected static boolean doesContain(final Throwable e, final String className, final String methodName) {
    for (StackTraceElement ste : e.getStackTrace()) {
        if (ste.getClassName().equals(className)
                && (methodName == null || ste.getMethodName().equals(methodName))) {
            return true;
        }
    }
    return false;
}

From source file:com.gargoylesoftware.htmlunit.general.ElementPropertiesTest.java

private void testString(final String string) throws Exception {
    final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_ + "<html><head><script>\n"
            + "  var ieMethods = ['abort', 'add', 'addBehavior', 'AddChannel', 'AddDesktopComponent', "
            + "'addElement', 'AddFavorite', 'addFilter', 'addImport', 'AddInPrivateSubscription', 'addPageRule', "
            + "'addReadRequest', 'addRule', 'AddSearchProvider', 'AddService', 'AddToFavoritesBar', 'alert', "
            + "'appendChild', 'appendData', 'applyElement', 'assign', 'attachEvent', 'AutoCompleteSaveForm', "
            + "'AutoScan', 'back', 'blur', 'bubbleEvent', 'ChooseColorDlg', 'clear', 'clearAttributes', "
            + "'clearData', 'clearInterval', 'clearRequest', 'clearTimeout', 'click', 'cloneNode', 'close', "
            + "'collapse', 'compareEndPoints', 'componentFromPoint', 'confirm', 'contains', "
            + "'ContentDiscoveryReset', 'createAttribute', 'createCaption', 'createComment', "
            + "'createControlRange', 'createDocumentFragment', 'createElement', 'createEventObject', "
            + "'createPopup', 'createRange', 'createRangeCollection', 'createStyleSheet', 'createTextNode', "
            + "'createTextRange', 'createTFoot', 'createTHead', 'deleteCaption', 'deleteCell', 'deleteData', "
            + "'deleteRow', 'deleteTFoot', 'deleteTHead', 'detachEvent', 'doImport', 'doReadRequest', 'doScroll', "
            + "'dragDrop', 'duplicate', 'elementFromPoint', 'empty', 'execCommand', 'execScript', 'expand', "
            + "'findText', 'fireEvent', 'firstPage', 'focus', 'forward', 'getAdjacentText', "
            + "'getAllResponseHeaders', 'getAttribute', 'getAttributeNode', 'getBookmark', "
            + "'getBoundingClientRect', 'getCharset', 'getClientRects', 'getData', 'getElementById', "
            + "'getElementsByName', 'getElementsByTagName', 'getExpression', 'getItem', 'getNamedItem', "
            + "'getResponseHeader', 'go', 'hasAttribute', 'hasChildNodes', 'hasFeature', 'hasFocus', 'hide', "
            + "'ImportExportFavorites', 'inRange', 'insertAdjacentElement', 'insertAdjacentHTML', "
            + "'insertAdjacentText', 'insertBefore', 'insertCell', 'insertData', 'insertRow', 'isEqual', "
            + "'IsSearchProviderInstalled', 'IsServiceInstalled', 'IsSubscribed', 'item', 'Item', 'javaEnabled', "
            + "'key', 'lastPage', 'mergeAttributes', 'move', 'moveBy', 'moveEnd', 'moveRow', 'moveStart', "
            + "'moveTo', 'moveToBookmark', 'moveToElementText', 'moveToPoint', 'namedItem', 'namedRecordset', "
            + "'navigate', 'NavigateAndFind', 'nextPage', 'normalize', 'open', 'parentElement', 'pasteHTML', "
            + "'postMessage', 'previousPage', 'print', 'prompt', 'queryCommandEnabled', 'queryCommandIndeterm', "
            + "'queryCommandState', 'queryCommandSupported', 'queryCommandValue', 'querySelector', "
            + "'querySelectorAll', 'raiseEvent', 'recalc', 'refresh', 'releaseCapture', 'reload', 'remove', "
            + "'removeAttribute', 'removeAttributeNode', 'removeBehavior', 'removeChild', 'removeExpression', "
            + "'removeImport', 'removeItem', 'removeNamedItem', 'removeNode', 'removeRule', 'replace', "
            + "'replaceAdjacentText', 'replaceChild', 'replaceData', 'replaceNode', 'reset', 'resizeBy', "
            + "'resizeTo', 'scroll', 'scrollBy', 'scrollIntoView', 'scrollTo', 'select', 'send', 'setActive', "
            + "'setAttribute', 'setAttributeNode', 'setCapture', 'setContextMenu', 'setData', 'setEndPoint', "
            + "'setExpression', 'setInterval', 'setItem', 'setNamedItem', 'setRequestHeader', 'setTimeout', "
            + "'show', 'ShowBrowserUI', 'showHelp', 'showModalDialog', 'showModelessDialog', 'splitText', "
            + "'start', 'stop', 'submit', 'substringData', 'swapNode', 'tags', 'taintEnabled', 'toStaticHTML', "
            + "'updateSettings', 'urns', 'write', 'writeln'];\n"

            + "  function test(event) {\n" + "    var xmlDocument = createXmlDocument();\n"
            + "    var element = xmlDocument.createElement('wakwak');\n"
            + "    var unknown = document.createElement('harhar');\n"
            + "    var div = document.createElement('div');\n" + "    process(" + string + ");\n" + "  }\n"
            + "\n" + "  /*\n" + "   * Alerts all properties (including functions) of the specified object.\n"
            + "   *\n" + "   * @param object the object to write the property of\n"
            + "   * @param parent the direct parent of the object (or child of that parent), can be null.\n"
            + "   *        The parent is used to exclude any inherited properties.\n" + "   */\n"
            + "  function process(object, parent) {\n" + "    var all = [];\n"
            + "    for (var property in object) {\n" + "      try {\n"
            + "        if (parent == null || !(property in parent)) {\n"
            + "          if (typeof object[property] == 'function')\n"
            + "            all.push(property + '()');\n" + "          else\n"
            + "            all.push(property);\n" + "        }\n" + "      } catch(e) {\n" + "        try{\n"
            + "          if (typeof object[property] == 'function')\n"
            + "            all.push(property + '()');\n" + "          else\n"
            + "            all.push(property);\n" + "        } catch (e) {\n"
            + "          all.push(property.toString());\n" + "        }\n" + "      }\n" + "    }\n"
            + "    if (document.all) {\n" + "      for (var index in ieMethods) {\n"
            + "        var method = ieMethods[index];\n" + "        try {\n"
            + "          if (object[method] !== undefined && (parent == null || parent[method] === undefined)) {\n"
            + "            all.push(method + '()');\n" + "          }\n" + "        } catch(e) {\n"
            + "           all.push(method + '()');\n" + "        }\n" + "      }\n" + "    }\n"
            + "    all.sort(sortFunction);\n" + "    alert(all);\n" + "  }\n"
            + "  function sortFunction(s1, s2) {\n"
            + "    return s1.toLowerCase() > s2.toLowerCase() ? 1 : -1;\n" + "  }\n"
            + "  function createXmlDocument() {\n"
            + "    if (document.implementation && document.implementation.createDocument)\n"
            + "      return document.implementation.createDocument('', '', null);\n"
            + "    else if (window.ActiveXObject)\n" + "      return new ActiveXObject('Microsoft.XMLDOM');\n"
            + "  }\n" + "</script></head><body onload='test(event)'>\n" + "</body></html>";

    if (BROWSER_VERSION_ == null) {
        BROWSER_VERSION_ = getBrowserVersion();
    }/*from  w ww .  j a v  a2 s. c o m*/
    final String expected = getExpectedAlerts().length == 0 ? "" : getExpectedAlerts()[0];
    String actual;

    ComparisonFailure failure = null;
    try {
        loadPageWithAlerts2(html);
        actual = expected;
    } catch (final ComparisonFailure c) {
        failure = c;
        actual = c.getActual();
        actual = actual.substring(1, actual.length() - 1);
    }

    final List<String> realProperties = stringAsArray(expected);
    final List<String> simulatedProperties = stringAsArray(actual);

    final List<String> erroredProperties = new ArrayList<>(simulatedProperties);
    erroredProperties.removeAll(realProperties);

    final List<String> implementedProperties = new ArrayList<>(simulatedProperties);
    implementedProperties.retainAll(realProperties);

    IMPLEMENTED_COUNT_ += implementedProperties.size();
    TOTAL_COUNT_ += realProperties.size();

    String methodName = null;
    for (final StackTraceElement e : new Exception().getStackTrace()) {
        if (e.getClassName().equals(getClass().getName())) {
            methodName = e.getMethodName();
        } else {
            break;
        }
    }

    htmlDetails(methodName, HTML_, realProperties, implementedProperties, erroredProperties);

    DATASET_.addValue(implementedProperties.size(), "Implemented", methodName);
    DATASET_.addValue(realProperties.size(),
            getBrowserVersion().getNickname().replace("FF", "Firefox ").replace("IE", "Internet Explorer "),
            methodName);
    DATASET_.addValue(erroredProperties.size(), "Should not be implemented", methodName);

    if (failure != null) {
        throw failure;
    }
}

From source file:org.wso2.carbon.registry.core.jdbc.EmbeddedRegistry.java

private void beginDBQueryLog(int level) {
    if (dbQueryLog.isDebugEnabled()) {
        StackTraceElement traceElement = Thread.currentThread().getStackTrace()[level];
        String methodName = traceElement.getMethodName();
        if (!statEnabledOperations.isEmpty() && statEnabledOperations.contains(methodName)) {
            if (traceElement.getClassName().equals(this.getClass().getCanonicalName())) {
                StatisticsRecord statisticsRecord = DBQueryStatisticsLog.getStatisticsRecord();
                if (statisticsRecord.increment() == 0) {
                    DBQueryStatisticsLog.clearStatisticsRecord();
                    statisticsRecord = DBQueryStatisticsLog.getStatisticsRecord();
                    statisticsRecord.increment();
                    statisticsRecord.setOperation(methodName);
                }/*from  ww  w.  ja  v a2s  .c o  m*/
            }
        }
    }
}

From source file:org.wso2.carbon.registry.core.jdbc.EmbeddedRegistry.java

private void endDBQueryLog(int level) {
    if (dbQueryLog.isDebugEnabled()) {
        StackTraceElement traceElement = Thread.currentThread().getStackTrace()[level];
        String methodName = traceElement.getMethodName();
        if (!statEnabledOperations.isEmpty() && statEnabledOperations.contains(methodName)) {
            if (traceElement.getClassName().equals(this.getClass().getCanonicalName())) {
                StatisticsRecord statisticsRecord = DBQueryStatisticsLog.getStatisticsRecord();
                if (statisticsRecord.decrement() == 0) {
                    final StatisticsRecord clone = new StatisticsRecord(statisticsRecord);
                    Runnable runnable = new Runnable() {
                        public void run() {
                            if (clone.getTableRecords().length > 0) {
                                dbQueryLog.debug("");
                                dbQueryLog.debug("---------------------------------------------------");
                                dbQueryLog.debug("Registry Operation: " + clone.getOperation());
                                dbQueryLog.debug("");
                                for (String record : clone.getTableRecords()) {
                                    dbQueryLog.debug("Tables Accessed: " + record);
                                }//ww w .  j a v a2  s.co  m
                                if (Boolean.toString(true).equals(System.getProperty(
                                        "carbon.registry.statistics.output." + "queries.executed"))) {
                                    dbQueryLog.debug("");
                                    StringBuffer sb = new StringBuffer();
                                    for (String query : clone.getQueries()) {
                                        sb.append("\n").append(query);
                                    }
                                    dbQueryLog.debug("Queries Executed:" + sb.toString());
                                }
                                dbQueryLog.debug("---------------------------------------------------");
                                dbQueryLog.debug("");
                            }
                        }
                    };
                    if (executor != null) {
                        executor.submit(runnable);
                    } else {
                        initializeStatisticsLogging();
                        executor.submit(runnable);
                    }
                    DBQueryStatisticsLog.clearStatisticsRecord();
                }
            }
        }
    }
}

From source file:org.geoserver.security.GeoServerSecurityManager.java

/**
 * Method to dump master password to a file
 * /*from   w  ww .  j a v a2s  . co  m*/
 * The file name is the shared secret between the administrator and GeoServer.
 * 
 * The method inspects the stack trace to check for an authorized calling method.
 * The authenticated principal has to be an administrator
 * 
 * If authorization fails, a warning is written in the log and the return
 * code is <code>false</code>. On success, the return code is <code>true</code>. 
 * 
 * @param file
 * @return
 * @throws IOException
 */
public boolean dumpMasterPassword(File file) throws IOException {

    if (checkAuthenticationForAdminRole() == false) {
        LOGGER.warning("Unautorized user tries to dump master password");
        return false;
    }

    String[][] allowedMethods = new String[][] {
            { "org.geoserver.security.GeoServerSecurityManagerTest", "testMasterPasswordDump" },
            { "org.geoserver.security.web.passwd.MasterPasswordInfoPage", "dumpMasterPassword" } };

    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();

    boolean isAllowed = false;
    int countMethodsToCheck = 10;
    // since different sdks have a different stack trace the 
    // first 10 elements are checked
    for (int i = 0; i < countMethodsToCheck; i++) {
        StackTraceElement element = stackTraceElements[i];
        for (String[] methodEntry : allowedMethods) {
            if (methodEntry[0].equals(element.getClassName())
                    && methodEntry[1].equals(element.getMethodName())) {
                isAllowed = true;
                break;
            }
        }
    }
    if (!isAllowed) {
        LOGGER.warning("Dump master password is called by an unautorized method");
        for (int i = 0; i < countMethodsToCheck; i++) {
            StackTraceElement element = stackTraceElements[i];
            LOGGER.warning(element.getClassName() + " : " + element.getMethodName());
        }
        return false;
    }

    String message = "The current master password is: ";
    writeMasterPasswordInfo(file, message, getMasterPassword());
    return true;
}