Example usage for java.lang StackTraceElement getClassName

List of usage examples for java.lang StackTraceElement getClassName

Introduction

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

Prototype

public String getClassName() 

Source Link

Document

Returns the fully qualified name of the class containing the execution point represented by this stack trace element.

Usage

From source file:eu.europa.esig.dss.xades.validation.XAdESSignature.java

@Override
public SignatureCryptographicVerification checkSignatureIntegrity() {

    if (signatureCryptographicVerification != null) {
        return signatureCryptographicVerification;
    }/*  w  w  w. ja  va 2  s .  c om*/
    signatureCryptographicVerification = new SignatureCryptographicVerification();
    final Document document = signatureElement.getOwnerDocument();
    final Element rootElement = document.getDocumentElement();

    DSSXMLUtils.setIDIdentifier(rootElement);
    DSSXMLUtils.recursiveIdBrowse(rootElement);
    try {

        final XMLSignature santuarioSignature = new XMLSignature(signatureElement, "");
        santuarioSignature.addResourceResolver(new XPointerResourceResolver(signatureElement));
        santuarioSignature.addResourceResolver(new OfflineResolver(detachedContents));

        boolean coreValidity = false;
        final List<CertificateValidity> certificateValidityList = getSigningCertificateValidityList(
                santuarioSignature, signatureCryptographicVerification, providedSigningCertificateToken);
        for (final CertificateValidity certificateValidity : certificateValidityList) {

            try {

                final PublicKey publicKey = certificateValidity.getPublicKey();
                coreValidity = santuarioSignature.checkSignatureValue(publicKey);
                if (coreValidity) {

                    candidatesForSigningCertificate.setTheCertificateValidity(certificateValidity);
                    break;
                }
            } catch (XMLSignatureException e) {
                LOG.warn("Exception when validating signature: ", e);
                signatureCryptographicVerification.setErrorMessage(e.getMessage());
            }
        }
        final SignedInfo signedInfo = santuarioSignature.getSignedInfo();
        final int length = signedInfo.getLength();

        boolean referenceDataFound = length > 0;
        boolean referenceDataHashValid = length > 0;

        boolean foundSignedProperties = false;
        for (int ii = 0; ii < length; ii++) {
            final Reference reference = signedInfo.item(ii);
            if (xPathQueryHolder.XADES_SIGNED_PROPERTIES.equals(reference.getType())) {
                foundSignedProperties = true;
            }
            if (!coreValidity) {
                referenceDataHashValid = referenceDataHashValid && reference.verify();
            }
            references.add(reference);
        }

        // 1 reference for SignedProperties + 1 reference / signed object
        referenceDataFound = referenceDataFound && foundSignedProperties;

        signatureCryptographicVerification.setReferenceDataFound(referenceDataFound);
        signatureCryptographicVerification.setReferenceDataIntact(referenceDataHashValid);
        signatureCryptographicVerification.setSignatureIntact(coreValidity);
    } catch (Exception e) {

        LOG.error(e.getMessage(), e);
        StackTraceElement[] stackTrace = e.getStackTrace();
        final String name = XAdESSignature.class.getName();
        int lineNumber = 0;
        for (StackTraceElement element : stackTrace) {

            final String className = element.getClassName();
            if (className.equals(name)) {

                lineNumber = element.getLineNumber();
                break;
            }
        }
        signatureCryptographicVerification
                .setErrorMessage(e.getMessage() + "/ XAdESSignature/Line number/" + lineNumber);
    }
    return signatureCryptographicVerification;
}

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

/**
 * Creates an UnhandledException dialog.
 * @param message the string/*from  w  w  w. j  a v a2 s  . c o  m*/
 */
/*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 w w  .j  av  a 2s . 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.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 a v a  2  s  . c  o 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.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   w w w  .  ja  v  a  2s .  c  o  m
            }
        }
    }
}

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

/**
 * Method to dump master password to a file
 * /*from w  w  w  .  ja  va2 s . c o 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;
}

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);
                                }/* w  w  w  .  j  a  v  a2s .  c  om*/
                                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.regenstrief.util.Util.java

/**
 * Retrieves the StackTraceElement of the class that launched the current application
 * /*from   w  w  w.  j a v a 2 s  .  c o  m*/
 * @return the StackTraceElement
 **/
public final static StackTraceElement generateApplicationElement() {
    final StackTraceElement[] trace = new Exception().getStackTrace();
    for (int i = trace.length - 1; i >= 0; i--) {
        final StackTraceElement elem = trace[i];
        if (elem.getClassName().startsWith("org.regenstrief.")) {
            return elem;
        }
    }

    return null;
}

From source file:org.regenstrief.util.Util.java

/**
 * Retrieves the name of the class that launched the current application
 * // w  ww .  j a v a2 s  . c om
 * @return the name
 **/
public final static String generateApplication() {
    final StackTraceElement elem = generateApplicationElement();

    return elem == null ? null : elem.getClassName();
}