Example usage for java.lang StackTraceElement getLineNumber

List of usage examples for java.lang StackTraceElement getLineNumber

Introduction

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

Prototype

public int getLineNumber() 

Source Link

Document

Returns the line number of the source line containing the execution point represented by this stack trace element.

Usage

From source file:org.ubicompforall.cityexplorer.CityExplorer.java

/***
 * Debug method to include the filename, line-number and method of the caller
 *//*from w  w  w. j ava 2  s . c  o  m*/
public static void debug(int d, String msg) {

    if (DEBUG >= d) {
        StackTraceElement[] st = Thread.currentThread().getStackTrace();
        int stackLevel = 2;
        while (stackLevel < st.length - 1 && (st[stackLevel].getMethodName().equals("debug")
                || st[stackLevel].getMethodName().matches("access\\$\\d+"))) {
            //|| st[stackLevel].getMethodName().matches("run")
            stackLevel++;
        }
        StackTraceElement e = st[stackLevel];
        if (d < 0) { //error
            Log.e(C, e.getMethodName() + ": " + msg + " at (" + e.getFileName() + ":" + e.getLineNumber()
                    + ")");
        } else { //debug
            Log.d(C, e.getMethodName() + ": " + msg + " at (" + e.getFileName() + ":" + e.getLineNumber()
                    + ")");
        } //if debug, else error
    } // if verbose enough

}

From source file:play.modules.pdf.PDF.java

/**
  * Render a specific template// w  ww. j av a  2s  .  c o m
  *
  * @param templateName The template name
  * @param args         The template data
  */
public static void renderTemplateAsPDF(OutputStream out, MultiPDFDocuments docs, Object... args) {
    Scope.RenderArgs templateBinding = Scope.RenderArgs.current();

    try {
        // play <= v1.2.3
        Class<?> clazz = Class
                .forName("play.classloading.enhancers.LocalvariablesNamesEnhancer.LocalVariablesNamesTracer");
        Method method = clazz.getMethod("getAllLocalVariableNames", Object.class);
        for (Object o : args) {
            List<String> names = (List<String>) method.invoke(null, o);
            for (String name : names) {
                templateBinding.put(name, o);
            }
        }
    } catch (ClassNotFoundException e) {
        // play <= v1.2.3
        String[] names = LVEnhancerRuntime.getParamNames().varargs;
        if (args != null && args.length > 0 && names == null)
            throw new UnexpectedException("no varargs names while args.length > 0 !");
        for (int i = 0; i < args.length; i++) {
            templateBinding.put(names[i], args[i]);
        }
    } catch (Exception e) {
        throw new UnexpectedException(e);
    }

    templateBinding.put("session", Scope.Session.current());
    templateBinding.put("request", Http.Request.current());
    templateBinding.put("flash", Scope.Flash.current());
    templateBinding.put("params", Scope.Params.current());
    try {
        templateBinding.put("errors", Validation.errors());
    } catch (Exception ex) {
        throw new UnexpectedException(ex);
    }
    try {
        if (out == null) {
            // we're rendering to the current Response object
            throw new RenderPDFTemplate(docs, templateBinding.data);
        } else {
            RenderPDFTemplate renderer = new RenderPDFTemplate(docs, templateBinding.data);
            renderer.writePDF(out, Http.Request.current(), Http.Response.current());
        }
    } catch (TemplateNotFoundException ex) {
        if (ex.isSourceAvailable()) {
            throw ex;
        }
        StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex);
        if (element != null) {
            throw new TemplateNotFoundException(ex.getPath(),
                    Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber());
        } else {
            throw ex;
        }
    }
}

From source file:com.momock.util.Logger.java

static String getLog(String level, String msg) {
    Throwable t = new Throwable();
    StackTraceElement trace = t.getStackTrace()[2];
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
    if (remoteLogger != null) {
        remoteLogger.log(level, msg, trace.getFileName() + "(" + trace.getLineNumber() + ")");
    }//from w  ww. j  a  va  2  s. c om
    return "[" + level + "] " + sdf.format(new Date()) + " in " + trace.getFileName() + "("
            + trace.getLineNumber() + ") >" + msg;
}

From source file:kilim.Fiber.java

static void ds() {
    for (StackTraceElement ste : new Exception().getStackTrace()) {
        String cl = ste.getClassName();
        String meth = ste.getMethodName();
        if (cl.startsWith("kilim.Worker") || meth.equals("go") || meth.equals("ds"))
            continue;
        String line = ste.getLineNumber() < 0 ? "" : ":" + ste.getLineNumber();
        log.info('\t' + cl + '.' + ste.getMethodName() + '(' + ste.getFileName() + line + ')');
    }//from  w w  w  .  j a  v a2  s  .c  o  m
}

From source file:org.kuali.coeus.sys.impl.validation.ErrorReporterImpl.java

public static String getMethodPath(int fromLevel, int toLevel) {
    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    //increase the levels to avoid including the method that called this.
    fromLevel = fromLevel + 1;//from  w  w w. ja  va 2  s.  co m
    toLevel = toLevel + 1;

    if (fromLevel <= 0) {
        throw new IllegalArgumentException("invalid fromLevel (" + fromLevel + " < 0)");
    }
    if (fromLevel > toLevel) {
        throw new IllegalArgumentException(
                "invalid levels (fromLevel " + fromLevel + " > toLevel " + toLevel + ")");
    }
    if (toLevel >= stackTraceElements.length) {
        throw new IllegalArgumentException(
                "invalid toLevel (" + toLevel + " >= " + stackTraceElements.length + ")");
    }

    StringBuffer result = new StringBuffer();
    int elementIndex = 0;
    for (StackTraceElement element : stackTraceElements) {
        if (elementIndex >= fromLevel && elementIndex >= toLevel) {
            if (result.length() > 0) {
                result.append(" from ");
            }
            result.append(element.getClassName()).append(".");
            result.append(element.getMethodName()).append("(");
            result.append(element.getFileName()).append(":");
            result.append(element.getLineNumber()).append(")");
        }
        elementIndex++;
    }
    return result.toString();

}

From source file:AIR.Common.DB.AbstractDLL.java

private static void logQuery(String query) {
    _logger.info("Query : " + query);
    if (_logger.isDebugEnabled()) {
        try {/*from   w  ww. j a v a2s  .  c o m*/
            StringBuilder traceBackMessage = new StringBuilder("Query traceback:\r\n");
            StackTraceElement[] trace = Thread.currentThread().getStackTrace();
            for (int i = 2; i < 9 && i < trace.length; i++) {
                StackTraceElement t = trace[i];
                traceBackMessage.append(String.format("    %s.%s (%d)\r\n", t.getClassName(), t.getMethodName(),
                        t.getLineNumber()));
            }
            _logger.debug(traceBackMessage.toString());
        } catch (Throwable t) {
            // Ignore!!
        }
    }
}

From source file:com.moss.greenshell.wizard.catastrophe.PostMortemScreen.java

public static void submitErrorReport(final Throwable cause, final ErrorReportDecorator... decorators)
        throws Exception {

    List<ErrorReportChunk> chunks = new LinkedList<ErrorReportChunk>();

    try {//from   w  w w . j  a v a 2s. c o m
        if (cause instanceof InternalErrorException) {
            InternalErrorException ie = (InternalErrorException) cause;
            ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                    ie.id().getBytes("UTF8"));
            chunks.add(chunk);
        } else if (cause instanceof SOAPFaultException) {
            SOAPFaultException soapFault = (SOAPFaultException) cause;
            String content = soapFault.getFault().getFirstChild().getTextContent();
            String prefix = "Internal Service Error Occurred: ";
            if (content.startsWith(prefix)) {
                String id = content.substring(prefix.length());
                ErrorReportChunk chunk = new ErrorReportChunk("internal-error-id", "text/plain",
                        id.getBytes("UTF8"));
                chunks.add(chunk);
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }

    // STACK TRACE
    ByteArrayOutputStream stackBytes = new ByteArrayOutputStream();
    PrintStream stackPrintStream = new PrintStream(stackBytes);
    cause.printStackTrace(stackPrintStream);
    stackPrintStream.close();
    stackBytes.close();

    ErrorReportChunk chunk = new ErrorReportChunk("stack trace", "text/plain", stackBytes.toByteArray());
    chunks.add(chunk);

    // THREAD DUMP

    ByteArrayOutputStream dumpBytes = new ByteArrayOutputStream();
    PrintStream out = new PrintStream(dumpBytes);
    Map<Thread, StackTraceElement[]> traceMap = Thread.getAllStackTraces();
    for (Map.Entry<Thread, StackTraceElement[]> next : traceMap.entrySet()) {
        out.println();
        out.println(next.getKey().getName());
        for (StackTraceElement line : next.getValue()) {
            String className = emptyIfNull(line.getClassName());
            String methodName = emptyIfNull(line.getMethodName());
            String fileName = emptyIfNull(line.getFileName());

            out.println("    " + className + "." + methodName + " (" + fileName + " line "
                    + line.getLineNumber() + ")");
        }
    }
    out.flush();
    out.close();
    ErrorReportChunk stackDump = new ErrorReportChunk("thread dump", "text/plain", dumpBytes.toByteArray());
    chunks.add(stackDump);

    // SYSTEM PROPERTIES
    ByteArrayOutputStream propsBytes = new ByteArrayOutputStream();
    PrintStream propsOut = new PrintStream(propsBytes);
    for (Map.Entry<Object, Object> next : System.getProperties().entrySet()) {
        propsOut.println(" " + next.getKey() + "=" + next.getValue());
    }
    propsOut.flush();
    propsOut.close();
    chunks.add(new ErrorReportChunk("system properties", "text/plain", propsBytes.toByteArray()));

    // LOCAL CLOCK
    chunks.add(new ErrorReportChunk("local clock", "text/plain", new DateTime().toString().getBytes()));

    // NETWORKING
    StringBuffer networking = new StringBuffer();
    Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
    while (ifaces.hasMoreElements()) {
        NetworkInterface iface = ifaces.nextElement();
        networking.append("INTERFACE: " + iface.getName() + " (" + iface.getDisplayName() + ")\n");
        Enumeration<InetAddress> addresses = iface.getInetAddresses();
        while (addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            networking.append("  Address:" + address.getHostAddress() + "\n");
            networking.append("      Cannonical Host Name: " + address.getCanonicalHostName() + "\n");
            networking.append("                 Host Name: " + address.getHostName() + "\n");
        }
    }
    chunks.add(new ErrorReportChunk("network configuration", "text/plain", networking.toString().getBytes()));

    // DECORATORS
    if (decorators != null) {
        for (ErrorReportDecorator decorator : decorators) {
            chunks.addAll(decorator.makeChunks(cause));
        }
    }
    ErrorReport report = new ErrorReport(chunks);
    Reporter reporter = new Reporter();
    ReportId id = reporter.submitReport(report);
}

From source file:org.mule.config.ExceptionHelper.java

public static String getExceptionStack(Throwable t) {
    StringBuffer buf = new StringBuffer();
    // get exception stack
    List exceptions = getExceptionsAsList(t);

    int i = 1;/*from ww w  .  j a  v a  2  s.  co  m*/
    for (Iterator iterator = exceptions.iterator(); iterator.hasNext(); i++) {
        if (i > exceptionThreshold && exceptionThreshold > 0) {
            buf.append("(").append(exceptions.size() - i + 1).append(" more...)");
            break;
        }
        Throwable throwable = (Throwable) iterator.next();
        ExceptionReader er = getExceptionReader(throwable);
        buf.append(i).append(". ").append(er.getMessage(throwable)).append(" (");
        buf.append(throwable.getClass().getName()).append(")\n");
        if (verbose && throwable.getStackTrace().length > 0) {
            StackTraceElement e = throwable.getStackTrace()[0];
            buf.append("  ").append(e.getClassName()).append(":").append(e.getLineNumber()).append(" (")
                    .append(getJavaDocUrl(throwable.getClass())).append(")\n");
        }
    }
    return buf.toString();
}

From source file:com.code19.library.L.java

private static String[] wrapperContent(String tag, Object... objects) {
    if (TextUtils.isEmpty(tag)) {
        tag = TAG;//from  w w  w. ja va 2  s  .c  o  m
    }
    StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    StackTraceElement targetElement = stackTrace[5];
    String className = targetElement.getClassName();
    String[] classNameInfo = className.split("\\.");
    if (classNameInfo.length > 0) {
        className = classNameInfo[classNameInfo.length - 1] + ".java";
    }
    String methodName = targetElement.getMethodName();
    int lineNumber = targetElement.getLineNumber();
    if (lineNumber < 0) {
        lineNumber = 0;
    }
    String methodNameShort = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
    String msg = (objects == null) ? "Log with null object" : getObjectsString(objects);
    String headString = "[(" + className + ":" + lineNumber + ")#" + methodNameShort + " ] ";
    return new String[] { tag, msg, headString };
}

From source file:org.apache.jorphan.util.JOrphanUtils.java

/**
 * Display currently running threads on system.out
 * This may be expensive to run./*ww  w. j  a  v a 2 s  .co  m*/
 * Mainly designed for use at the end of a non-GUI test to check for threads that might prevent the JVM from exiting.
 *
 * @param includeDaemons whether to include daemon threads or not.
 */
public static void displayThreads(boolean includeDaemons) {
    Map<Thread, StackTraceElement[]> m = Thread.getAllStackTraces();
    String lineSeparator = System.getProperty("line.separator");
    StringBuilder builder = new StringBuilder();
    for (Map.Entry<Thread, StackTraceElement[]> e : m.entrySet()) {
        boolean daemon = e.getKey().isDaemon();
        if (includeDaemons || !daemon) {
            builder.setLength(0);
            StackTraceElement[] ste = e.getValue();
            for (StackTraceElement stackTraceElement : ste) {
                int lineNumber = stackTraceElement.getLineNumber();
                builder.append(stackTraceElement.getClassName() + "#" + stackTraceElement.getMethodName()
                        + (lineNumber >= 0 ? " at line:" + stackTraceElement.getLineNumber() : "")
                        + lineSeparator);
            }
            System.out.println(e.getKey().toString() + ((daemon ? " (daemon)" : "")) + ", stackTrace:"
                    + builder.toString());
        }
    }
}