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:org.novelang.outfit.shell.JavaShellTest.java

@SuppressWarnings({ "ThrowableInstanceNeverThrown" })
private String mayEvaluate() {

    for (final StackTraceElement element : new Exception().getStackTrace()) {
        if (element.getClassName().contains("org.apache.maven.surefire.Surefire")) {
            // Maven tests should work all time unless broken for good reason.
            return null;
        }/* w w w .j a va2  s  . c  o m*/
    }

    final String warning = "Not running as Maven test, nor couldn't find agent jar file"
            + " (check system properties). Skipping " + methodSupport.getTestName()
            + " because needed resources may be missing.";
    String message = warning;

    if (AgentFileInstaller.mayHaveValidInstance()) {
        try {
            AgentFileInstaller.getInstance().getJarFile();
            message = null;
        } catch (MissingResourceException ignore) {
        }
    }

    if (message == null) {
        return null;
    } else {
        return message;
    }

}

From source file:org.kuali.rice.krad.uif.util.CopyUtils.java

/**
 * Mix-in copy implementation for objects that implement the {@link Copyable} interface}
 * //from  w  w w.  j  av a 2s.c  om
 * @param <T> copyable type
 * @param obj The object to copy.
 * @return A deep copy of the object.
 */
@SuppressWarnings("unchecked")
public static <T> T copy(Copyable obj) {
    if (obj == null) {
        return null;
    }

    String cid = null;
    if (ViewLifecycle.isTrace()) {
        StackTraceElement[] trace = Thread.currentThread().getStackTrace();
        int i = 3;
        while (ComponentUtils.class.getName().equals(trace[i].getClassName()))
            i++;
        StackTraceElement caller = trace[i];
        cid = obj.getClass().getSimpleName() + ":" + caller.getClassName() + ":" + caller.getMethodName() + ":"
                + caller.getLineNumber();
        ProcessLogger.ntrace("deep-copy:", ":" + cid, 1000L, 500L);
    }

    return (T) getDeepCopy(obj);
}

From source file:jp.co.opentone.bsol.framework.web.view.action.ActionHandler.java

private void logServiceAbortException(ServiceAbortException e) {
    StackTraceElement[] elem = e.getStackTrace();
    if (elem != null && elem.length > 0) {
        try {/*from  ww w . j av a 2  s  .  c  om*/
            StackTraceElement element = elem[0];
            String format = "%s.%s:%d [%s]";
            log.warn(String.format(format, getSimpleClassName(element.getClassName()), element.getMethodName(),
                    element.getLineNumber(), e.getMessageCode()));
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }
}

From source file:org.apache.sqoop.manager.oracle.OraOopUtilities.java

public static boolean stackContainsClass(String className) {

    StackTraceElement[] stackTraceElements = (new Throwable()).getStackTrace();
    for (StackTraceElement stackTraceElement : stackTraceElements) {
        if (stackTraceElement.getClassName().equalsIgnoreCase(className)) {
            return true;
        }//from ww  w  .  jav  a 2 s  .  c  o m
    }

    return false;
}

From source file:org.amplafi.jawr.maven.JawrMojo.java

private void setupJawrConfig(ServletConfig config, ServletContext context, final Map<String, Object> attributes,
        final Response respData) {
    expect(config.getServletContext()).andReturn(context).anyTimes();
    expect(config.getServletName()).andReturn("maven-jawr-plugin").anyTimes();

    context.log(isA(String.class));
    expectLastCall().anyTimes();/*ww w  . ja v a 2s .  c  o  m*/

    expect(context.getResourcePaths(isA(String.class))).andAnswer(new IAnswer<Set>() {

        public Set<String> answer() throws Throwable {
            final Set<String> set = new HashSet<String>();

            // hack to disallow orphan bundles
            Exception e = new Exception();
            for (StackTraceElement trace : e.getStackTrace()) {
                if (trace.getClassName().endsWith("OrphanResourceBundlesMapper")) {
                    return set;
                }
            }

            String path = (String) EasyMock.getCurrentArguments()[0];
            File file = new File(getRootPath() + path);

            if (file.exists() && file.isDirectory()) {
                for (String one : file.list()) {
                    set.add(path + one);
                }
            }

            return set;
        }

    }).anyTimes();

    expect(context.getResourceAsStream(isA(String.class))).andAnswer(new IAnswer<InputStream>() {

        public InputStream answer() throws Throwable {
            String path = (String) EasyMock.getCurrentArguments()[0];
            File file = new File(getRootPath(), path);
            return new FileInputStream(file);
        }

    }).anyTimes();

    expect(context.getAttribute(isA(String.class))).andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            return attributes.get(EasyMock.getCurrentArguments()[0]);
        }

    }).anyTimes();

    context.setAttribute(isA(String.class), isA(Object.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            String key = (String) EasyMock.getCurrentArguments()[0];
            Object value = EasyMock.getCurrentArguments()[1];
            attributes.put(key, value);
            return null;
        }

    }).anyTimes();

    expect(config.getInitParameterNames()).andReturn(new Enumeration<String>() {

        public boolean hasMoreElements() {
            return false;
        }

        public String nextElement() {
            return null;
        }

    }).anyTimes();

    expect(config.getInitParameter(JawrConstant.TYPE_INIT_PARAMETER)).andAnswer(new IAnswer<String>() {
        public String answer() throws Throwable {
            return respData == null ? null : respData.getType();
        }
    }).anyTimes();

    expect(config.getInitParameter("configLocation")).andReturn(getConfigLocation()).anyTimes();
    expect(config.getInitParameter("configPropertiesSourceClass")).andReturn(null).anyTimes();
}

From source file:sf.net.experimaestro.utils.JSUtils.java

/**
 * @see org.mozilla.javascript.RhinoException#getScriptStack()
 * @param ex// www  .  j a  va 2s .com
 * @return A stack
 */
static public ScriptStackElement[] getScriptStackTrace(Throwable ex) {
    List<ScriptStackElement> list = new ArrayList<>();
    ScriptStackElement[][] interpreterStack = null;
    int interpreterStackIndex = 0;
    StackTraceElement[] stack = ex.getStackTrace();
    // Pattern to recover function name from java method name -
    // see Codegen.getBodyMethodName()
    // kudos to Marc Guillemot for coming up with this
    Pattern pattern = Pattern.compile("_c_(.*)_\\d+");
    for (StackTraceElement e : stack) {
        String fileName = e.getFileName();
        if (e.getMethodName().startsWith("_c_") && e.getLineNumber() > -1 && fileName != null
                && !fileName.endsWith(".java")) {
            String methodName = e.getMethodName();
            Matcher match = pattern.matcher(methodName);
            // the method representing the main script is always "_c_script_0" -
            // at least we hope so
            methodName = !"_c_script_0".equals(methodName) && match.find() ? match.group(1) : null;
            list.add(new ScriptStackElement(fileName, methodName, e.getLineNumber()));
        } else if ("org.mozilla.javascript.Interpreter".equals(e.getClassName())
                && "interpretLoop".equals(e.getMethodName()) && interpreterStack != null
                && interpreterStack.length > interpreterStackIndex) {
            for (ScriptStackElement elem : interpreterStack[interpreterStackIndex++]) {
                list.add(elem);
            }
        }
    }
    return list.toArray(new ScriptStackElement[list.size()]);

}

From source file:org.pepstock.jem.ant.tasks.AntBatchSecurityManager.java

/**
 * Scans the stack trace element to understand if setSecurity manager is allowed.
 * <br>//from ww  w  .  j a v a2s . c  o m
 * ONLY ANT engine can set security manager and it does with
 * <code>org.apache.tools.ant.types.Permissions</code> class.
 * <br>
 * if it arrives with <code>org.apache.tools.ant.types.Permissions$MySM</code> means that
 * ANT security manager delegates us to check but we can't do it.
 * <br>
 * If it tries to change it by a ANT task, is not allowed!
 * 
 * @return <code>true</code> if ANT is initializing the task otherwise o=always false.
 */
private boolean isAllowedSetSecurityManager() {
    StackTraceElement[] elements = Thread.getAllStackTraces().get(Thread.currentThread());
    boolean thisFound = false;
    for (StackTraceElement element : elements) {
        // before must be in the stack trace this class
        if (element.getClassName().equalsIgnoreCase(getClass().getName())) {
            thisFound = true;
            // checks if is called by Security manager of ANT
            // if yes, it's delegating... that means that some one try to set the security manager
            // and this is NOT allowed.
        } else if (element.getClassName().equalsIgnoreCase(ANT_SECURITY_MANAGER) && thisFound) {
            return false;
            // if it is called by the permission, that means teh ANT is intsalling own security
            // manager, MySM, and that's ALLOWED!!
        } else if (element.getClassName().equalsIgnoreCase(ANT_PERMISSIONS) && thisFound) {
            return true;
        }
    }
    return false;
}

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 ww  .j av a2 s . co  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: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 a  v a  2s .  c om
    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.jumpmind.symmetric.service.impl.AbstractService.java

protected boolean isCalledFromSymmetricAdminTool() {
    boolean adminTool = false;
    StackTraceElement[] trace = Thread.currentThread().getStackTrace();
    for (StackTraceElement stackTraceElement : trace) {
        adminTool |= stackTraceElement.getClassName().equals("org.jumpmind.symmetric.SymmetricAdmin");
    }/*from  w w w . j a  v  a  2  s .  com*/
    return adminTool;
}