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.shopgun.android.utils.lifecycle.LifecycleFragmentv4.java

protected void printMethod(boolean print) {
    if (print) {/*from  w ww  . j a  v  a2 s.  co  m*/
        StackTraceElement ste = Thread.currentThread().getStackTrace()[3];
        //            String text = ste.getMethodName() + "(" + ste.getFileName() + ":" + ste.getLineNumber() + ")";
        Log.d(getClass().getSimpleName(), ste.getMethodName());
    }
}

From source file:io.coala.log.CoalaLog4jLogger.java

/**
 * @return/*ww  w  .ja  va  2 s .c  o m*/
 */
protected String getMethodAffix() {
    int i = 4;
    StackTraceElement elem = Thread.currentThread().getStackTrace()[i];
    while (isLoggingPackage(elem.getClassName()))
        elem = Thread.currentThread().getStackTrace()[++i];
    return String.format(METHOD_AFFIX_FORMAT, elem.getClassName(), elem.getMethodName(), elem.getFileName(),
            elem.getLineNumber());
}

From source file:org.apache.hupa.server.InMemoryIMAPStoreCache.java

private Session createSession(final User user) {
    Properties props = new Properties();
    Settings settings = user.getSettings();

    props.setProperty("mail.mime.decodetext.strict", "false");
    if (settings.getImapSecure()) {
        props.setProperty("mail.store.protocol", "imaps");
        props.setProperty("mail.imaps.connectionpoolsize", connectionPoolSize + "");
        props.setProperty("mail.imaps.connectionpooltimeout", timeout + "");
        if (trustSSL) {
            props.setProperty("mail.imaps.ssl.trust", settings.getImapServer());
        }/*  www . ja v  a 2  s . c o  m*/
    } else {
        props.setProperty("mail.imap.connectionpoolsize", connectionPoolSize + "");
        props.setProperty("mail.imap.connectionpooltimeout", timeout + "");
    }

    if (settings.getSmtpSecure()) {
        if (settings.getSmtpPort() == 587) {
            props.setProperty("mail.smtp.starttls.enable", "true");
            props.setProperty("mail.transport.protocol.rfc822", "smtp");
        } else {
            props.setProperty("mail.transport.protocol.rfc822", "smtps");
            props.setProperty("mail.smtps.ssl.enable", "true");
            if (trustSSL) {
                props.setProperty("mail.smtps.ssl.trust", settings.getSmtpServer());
            }
        }
    } else {
        props.setProperty("mail.transport.protocol.rfc822", "smtp");
    }

    props.setProperty("mail.smtp.host", settings.getSmtpServer());
    props.setProperty("mail.smtps.host", settings.getSmtpServer());
    props.setProperty("mail.smtp.port", settings.getSmtpPort() + "");
    props.setProperty("mail.smtps.port", settings.getSmtpPort() + "");

    Authenticator auth = null;
    if (settings.getSmtpAuth() && user.getPassword() != null && user.getName() != null) {
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtps.auth", "true");
        auth = new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                String userId = user.getId();
                StackTraceElement[] sElms = Thread.currentThread().getStackTrace();
                for (StackTraceElement e : sElms) {
                    if (e.getClassName().equals(InMemoryIMAPStoreCache.class.getName())
                            && e.getMethodName().equals("get")) {
                        // We try with the id part the second time (unix imap/smtp auth compatible)
                        if (userId.matches(".*@.*")) {
                            userId = userId.replaceFirst("@.*", "");
                            user.setId(userId);
                            break;
                        } else {
                            return null;
                        }
                    }
                }
                return new PasswordAuthentication(userId, user.getPassword());
            }
        };
    }

    Session ses = Session.getInstance(props, auth);
    ses.setDebug(debug && logger.isDebugEnabled());
    logger.debug("Created session " + user.getName() + "\n" + settings + "\n"
            + props.toString().replaceAll(",", ",\n "));
    return ses;
}

From source file:com.michelin.cio.hudson.plugins.clearcaseucmbaseline.ClearToolUcmBaseline.java

/**
 * Always throws an {@link UnsupportedOperationException}.
 * /*w w  w  .j a  va  2  s . c o  m*/
 * @param ste a {@link StackTraceElement} from which the name of the method
 *            calling this one will be gathered (must NOT be {@code null}
 */
private void unsupportedMethod(StackTraceElement ste) {
    throw new UnsupportedOperationException(ClearCaseUcmBaselineSCM.class.getName() + " does not support the "
            + ste.getMethodName() + " method.");
}

From source file:org.vulpe.controller.struts.interceptor.VulpeExceptionMappingInterceptor.java

/**
 *
 * @param invocation//from  w w  w .  jav  a2s. c o  m
 * @param exception
 * @return
 */
protected String treatExceptionMessage(final ActionInvocation invocation, final Throwable exception) {
    final VulpeStrutsController<?, ?> action = (VulpeStrutsController<?, ?>) invocation.getAction();
    final Throwable cause = getCause(exception);
    String message = cause.getMessage();
    String key = exception.getClass().getName();
    if (cause instanceof JspException) {
        key = cause.getClass().getName();
    } else if (cause instanceof SQLException) {
        key = cause.getClass().getName();
    }
    message = action.vulpe.controller().text(key);
    final String contactAdministratorMessageKey = "vulpe.error.contact.system.administrator";
    message += action.vulpe.controller().text(contactAdministratorMessageKey);
    if (isDebug(action)) {
        final String errorOccurrenceDebugKey = "vulpe.error.occurrence.debug";
        message += action.vulpe.controller().text(errorOccurrenceDebugKey);
        if (exception instanceof NullPointerException) {
            final StackTraceElement ste = exception.getStackTrace()[0];
            final String fileName = ste.getFileName().replace(".java", "");
            final String methodName = ste.getMethodName();
            final int lineNumber = ste.getLineNumber();
            message += action.vulpe.controller().text(key + ".debug", fileName, methodName, lineNumber);
        } else {
            message += "<i>" + (exception instanceof VulpeValidationException ? "entity" : cause.getMessage())
                    + "</i>";
        }
    }
    return message;
}

From source file:org.opentestsystem.shared.docs.RequestLoggingInterceptor.java

/**
 * NOTE: this is a brittle example of walking up the stack to find
 * an annotated method to determine how to treat the API doc captured in this
 * Intercepter. The use of annotations provides a lightweight mechanism of doing just that.
 *
 * @return the rank if found (or the ApiDocExample.DEFAULT_RANK if not)
 *///from w w w .  jav  a 2 s  . c o m
private int getRankOfApiDoc() {
    StackTraceElement[] stack = Thread.currentThread().getStackTrace();
    // default to DEFAULT_RANK which will capture the doc, but put it at the bottom if no annotation is found.
    int rank = ApiDocExample.DEFAULT_RANK;
    // loop up the stack to find the annotation
    for (int i = 0; i < stack.length; i++) {
        StackTraceElement ste = stack[i];
        // shortcut up the stack: once we get to the MocMvc call, we're in business: start interrogating the methods
        if (ste.getClassName().equals(MockMvc.class.getName())) {
            for (int j = i; j < stack.length; j++) {
                StackTraceElement theOne = stack[j];
                try {
                    Class<?> clazz = Class.forName(theOne.getClassName());
                    // following JUnit convention, the root test will have no args
                    Method theMethod = clazz.getMethod(theOne.getMethodName(), (Class[]) null);
                    // find the ApiDocExample if it exists
                    ApiDocExample example = theMethod.getAnnotation(ApiDocExample.class);
                    if (example != null) {
                        rank = example.rank();
                        // once we find an example annotation, break out of loops.
                        break;
                    }
                } catch (ClassNotFoundException | NoSuchMethodException e) {
                    // getMethod failed to find a no arg method, continue down the stack.
                    continue;
                }
            }
            break;
        }
    }
    return rank;
}

From source file:com.bstek.dorado.view.resolver.ViewServiceResolver.java

/**
 * @param jsonBuilder//from ww w.ja va  2  s.c  o  m
 * @param e
 */
protected void outputException(JsonBuilder jsonBuilder, Throwable throwable) {
    while (throwable.getCause() != null) {
        throwable = throwable.getCause();
    }

    String message = throwable.getMessage();
    if (message == null) {
        message = throwable.getClass().getSimpleName();
    }

    try {
        jsonBuilder.object(); // TODO: ?JSONBuilder?
        jsonBuilder.key("exceptionType").value("JavaException").key("message").value(message).key("stackTrace");
        jsonBuilder.array();
        StackTraceElement[] stackTrace = throwable.getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            jsonBuilder.value(stackTraceElement.getClassName() + '.' + stackTraceElement.getMethodName() + '('
                    + stackTraceElement.getFileName() + ':' + stackTraceElement.getLineNumber() + ')');
        }
        jsonBuilder.endArray();
        jsonBuilder.endObject();
    } catch (Exception e) {
        // ignore e!!!
        throwable.printStackTrace();
    }
}

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

private StackTraceElement getStackTraceElement() {
    StackTraceElement last = null;
    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    for (StackTraceElement trace : stackTraceElements) {
        try {/*from   w w w. jav  a 2 s .c o  m*/
            if (Class.forName(trace.getClassName()).getMethod(trace.getMethodName())
                    .isAnnotationPresent(Test.class))
                last = trace;
            if (Class.forName(trace.getClassName()).getMethod(trace.getMethodName())
                    .isAnnotationPresent(After.class))
                last = trace;
            if (Class.forName(trace.getClassName()).getMethod(trace.getMethodName())
                    .isAnnotationPresent(Before.class))
                last = trace;
            if (Class.forName(trace.getClassName()).getMethod(trace.getMethodName())
                    .isAnnotationPresent(AfterClass.class))
                last = trace;
            if (Class.forName(trace.getClassName()).getMethod(trace.getMethodName())
                    .isAnnotationPresent(BeforeClass.class))
                last = trace;
        } catch (Exception e) {
        }
    }
    return last;
}

From source file:net.logstash.logback.composite.loggingevent.CallerDataJsonProvider.java

@Override
public void writeTo(JsonGenerator generator, ILoggingEvent event) throws IOException {
    StackTraceElement callerData = extractCallerData(event);
    if (callerData == null) {
        return;/* w  w  w  .j  a v  a  2 s.c  o m*/
    }
    if (getFieldName() != null) {
        generator.writeObjectFieldStart(getFieldName());
    }
    JsonWritingUtils.writeStringField(generator, classFieldName, callerData.getClassName());
    JsonWritingUtils.writeStringField(generator, methodFieldName, callerData.getMethodName());
    JsonWritingUtils.writeStringField(generator, fileFieldName, callerData.getFileName());
    JsonWritingUtils.writeNumberField(generator, lineFieldName, callerData.getLineNumber());
    if (getFieldName() != null) {
        generator.writeEndObject();
    }
}

From source file:com.liferay.document.library.webdav.test.BaseWebDAVTestCase.java

public Tuple service(String method, String path, Map<String, String> headers, byte[] data) {

    WebDAVServlet webDAVServlet = new WebDAVServlet();

    String requestURI = _CONTEXT_PATH + _SERVLET_PATH + _PATH_INFO_PREFACE + path;

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method, requestURI);

    mockHttpServletRequest.setContextPath(_CONTEXT_PATH);
    mockHttpServletRequest.setServletPath(_SERVLET_PATH);
    mockHttpServletRequest.setPathInfo(_PATH_INFO_PREFACE + path);

    try {/*from  ww w .j a va2  s.co  m*/
        mockHttpServletRequest.setRemoteUser(String.valueOf(TestPropsValues.getUserId()));
    } catch (Exception e) {
        Assert.fail("User ID cannot be initialized");
    }

    if (headers == null) {
        headers = new HashMap<>();
    }

    headers.put(HttpHeaders.USER_AGENT, getUserAgent());

    try {
        throw new Exception();
    } catch (Exception e) {
        StackTraceElement[] stackTraceElements = e.getStackTrace();

        for (StackTraceElement stackTraceElement : stackTraceElements) {
            String methodName = stackTraceElement.getMethodName();

            if (methodName.equals("setUp") || methodName.equals("tearDown") || methodName.startsWith("test")) {

                String testName = StringUtil.extractLast(stackTraceElement.getClassName(), CharPool.PERIOD);

                testName = StringUtil.removeSubstrings(testName, "WebDAV", "Test");

                headers.put("X-Litmus", testName + ": (" + stackTraceElement.getMethodName() + ":"
                        + stackTraceElement.getLineNumber() + ")");

                break;
            }
        }
    }

    if (data != null) {
        mockHttpServletRequest.setContent(data);

        String contentType = headers.remove(HttpHeaders.CONTENT_TYPE);

        if (contentType != null) {
            mockHttpServletRequest.setContentType(contentType);
        } else {
            mockHttpServletRequest.setContentType(ContentTypes.TEXT_PLAIN);
        }
    }

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();

        mockHttpServletRequest.addHeader(key, value);
    }

    try {
        MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

        webDAVServlet.service(mockHttpServletRequest, mockHttpServletResponse);

        int statusCode = mockHttpServletResponse.getStatus();
        byte[] responseBody = mockHttpServletResponse.getContentAsByteArray();

        Map<String, String> responseHeaders = new HashMap<>();

        for (String name : mockHttpServletResponse.getHeaderNames()) {
            responseHeaders.put(name, mockHttpServletResponse.getHeader(name));
        }

        return new Tuple(statusCode, responseBody, responseHeaders);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}