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.gradle.internal.featurelifecycle.ScriptUsageLocationReporter.java

private void reportStackTraceElement(StackTraceElement stackTraceElement, StringBuilder target) {
    ScriptSource scriptSource = scripts.get(stackTraceElement.getFileName());
    target.append(StringUtils.capitalize(scriptSource.getDisplayName()));
    if (stackTraceElement.getLineNumber() > 0) {
        target.append(": line ");
        target.append(stackTraceElement.getLineNumber());
    }//from  w  w w  .  j  a  va2s .c  om
}

From source file:org.jumpmind.symmetric.util.SnapshotUtil.java

public static File createSnapshot(ISymmetricEngine engine) {

    String dirName = engine.getEngineName().replaceAll(" ", "-") + "-"
            + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

    IParameterService parameterService = engine.getParameterService();
    File tmpDir = new File(parameterService.getTempDirectory(), dirName);
    tmpDir.mkdirs();//w w  w. java2s  .  c  om

    File logDir = null;

    String parameterizedLogDir = parameterService.getString("server.log.dir");
    if (isNotBlank(parameterizedLogDir)) {
        logDir = new File(parameterizedLogDir);
    }

    if (logDir != null && logDir.exists()) {
        log.info("Using server.log.dir setting as the location of the log files");
    } else {
        logDir = new File("logs");

        if (!logDir.exists()) {
            File file = findSymmetricLogFile();
            if (file != null) {
                logDir = file.getParentFile();
            }
        }

        if (!logDir.exists()) {
            logDir = new File("../logs");
        }

        if (!logDir.exists()) {
            logDir = new File("target");
        }

        if (logDir.exists()) {
            File[] files = logDir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.getName().toLowerCase().endsWith(".log")) {
                        try {
                            FileUtils.copyFileToDirectory(file, tmpDir);
                        } catch (IOException e) {
                            log.warn("Failed to copy " + file.getName() + " to the snapshot directory", e);
                        }
                    }
                }
            }
        }

    }

    ITriggerRouterService triggerRouterService = engine.getTriggerRouterService();
    List<TriggerHistory> triggerHistories = triggerRouterService.getActiveTriggerHistories();
    TreeSet<Table> tables = new TreeSet<Table>();
    for (TriggerHistory triggerHistory : triggerHistories) {
        Table table = engine.getDatabasePlatform().getTableFromCache(triggerHistory.getSourceCatalogName(),
                triggerHistory.getSourceSchemaName(), triggerHistory.getSourceTableName(), false);
        if (table != null && !table.getName().toUpperCase()
                .startsWith(engine.getSymmetricDialect().getTablePrefix().toUpperCase())) {
            tables.add(table);
        }
    }

    List<Trigger> triggers = triggerRouterService.getTriggers(true);
    for (Trigger trigger : triggers) {
        Table table = engine.getDatabasePlatform().getTableFromCache(trigger.getSourceCatalogName(),
                trigger.getSourceSchemaName(), trigger.getSourceTableName(), false);
        if (table != null) {
            tables.add(table);
        }
    }

    FileWriter fwriter = null;
    try {
        fwriter = new FileWriter(new File(tmpDir, "config-export.csv"));
        engine.getDataExtractorService().extractConfigurationStandalone(engine.getNodeService().findIdentity(),
                fwriter, TableConstants.SYM_NODE, TableConstants.SYM_NODE_SECURITY,
                TableConstants.SYM_NODE_IDENTITY, TableConstants.SYM_NODE_HOST,
                TableConstants.SYM_NODE_CHANNEL_CTL, TableConstants.SYM_CONSOLE_USER);
    } catch (IOException e) {
        log.warn("Failed to export symmetric configuration", e);
    } finally {
        IOUtils.closeQuietly(fwriter);
    }

    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(new File(tmpDir, "table-definitions.xml"));
        DbExport export = new DbExport(engine.getDatabasePlatform());
        export.setFormat(Format.XML);
        export.setNoData(true);
        export.exportTables(fos, tables.toArray(new Table[tables.size()]));
    } catch (IOException e) {
        log.warn("Failed to export table definitions", e);
    } finally {
        IOUtils.closeQuietly(fos);
    }

    String tablePrefix = engine.getTablePrefix();

    DbExport export = new DbExport(engine.getDatabasePlatform());
    export.setFormat(Format.CSV);
    export.setNoCreateInfo(true);

    extract(export, new File(tmpDir, "identity.csv"),
            TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_IDENTITY));

    extract(export, new File(tmpDir, "node.csv"),
            TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE));

    extract(export, new File(tmpDir, "nodesecurity.csv"),
            TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_SECURITY));

    extract(export, new File(tmpDir, "nodehost.csv"),
            TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_HOST));

    extract(export, new File(tmpDir, "triggerhist.csv"),
            TableConstants.getTableName(tablePrefix, TableConstants.SYM_TRIGGER_HIST));

    extract(export, new File(tmpDir, "lock.csv"),
            TableConstants.getTableName(tablePrefix, TableConstants.SYM_LOCK));

    extract(export, new File(tmpDir, "nodecommunication.csv"),
            TableConstants.getTableName(tablePrefix, TableConstants.SYM_NODE_COMMUNICATION));

    extract(export, 5000, new File(tmpDir, "outgoingbatch.csv"),
            TableConstants.getTableName(tablePrefix, TableConstants.SYM_OUTGOING_BATCH));

    extract(export, 5000, new File(tmpDir, "incomingbatch.csv"),
            TableConstants.getTableName(tablePrefix, TableConstants.SYM_INCOMING_BATCH));

    final int THREAD_INDENT_SPACE = 50;
    fwriter = null;
    try {
        fwriter = new FileWriter(new File(tmpDir, "threads.txt"));
        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        long[] threadIds = threadBean.getAllThreadIds();
        for (long l : threadIds) {
            ThreadInfo info = threadBean.getThreadInfo(l, 100);
            if (info != null) {
                String threadName = info.getThreadName();
                fwriter.append(StringUtils.rightPad(threadName, THREAD_INDENT_SPACE));
                StackTraceElement[] trace = info.getStackTrace();
                boolean first = true;
                for (StackTraceElement stackTraceElement : trace) {
                    if (!first) {
                        fwriter.append(StringUtils.rightPad("", THREAD_INDENT_SPACE));
                    } else {
                        first = false;
                    }
                    fwriter.append(stackTraceElement.getClassName());
                    fwriter.append(".");
                    fwriter.append(stackTraceElement.getMethodName());
                    fwriter.append("()");
                    int lineNumber = stackTraceElement.getLineNumber();
                    if (lineNumber > 0) {
                        fwriter.append(": ");
                        fwriter.append(Integer.toString(stackTraceElement.getLineNumber()));
                    }
                    fwriter.append("\n");
                }
                fwriter.append("\n");
            }
        }
    } catch (IOException e) {
        log.warn("Failed to export thread information", e);
    } finally {
        IOUtils.closeQuietly(fwriter);
    }

    fos = null;
    try {
        fos = new FileOutputStream(new File(tmpDir, "parameters.properties"));
        Properties effectiveParameters = engine.getParameterService().getAllParameters();
        SortedProperties parameters = new SortedProperties();
        parameters.putAll(effectiveParameters);
        parameters.remove("db.password");
        parameters.store(fos, "parameters.properties");
    } catch (IOException e) {
        log.warn("Failed to export parameter information", e);
    } finally {
        IOUtils.closeQuietly(fos);
    }

    fos = null;
    try {
        fos = new FileOutputStream(new File(tmpDir, "parameters-changed.properties"));
        Properties defaultParameters = new Properties();
        InputStream in = SnapshotUtil.class.getResourceAsStream("/symmetric-default.properties");
        defaultParameters.load(in);
        IOUtils.closeQuietly(in);
        in = SnapshotUtil.class.getResourceAsStream("/symmetric-console-default.properties");
        if (in != null) {
            defaultParameters.load(in);
            IOUtils.closeQuietly(in);
        }
        Properties effectiveParameters = engine.getParameterService().getAllParameters();
        Properties changedParameters = new SortedProperties();
        Map<String, ParameterMetaData> parameters = ParameterConstants.getParameterMetaData();
        for (String key : parameters.keySet()) {
            String defaultValue = defaultParameters.getProperty((String) key);
            String currentValue = effectiveParameters.getProperty((String) key);
            if (defaultValue == null && currentValue != null
                    || (defaultValue != null && !defaultValue.equals(currentValue))) {
                changedParameters.put(key, currentValue == null ? "" : currentValue);
            }
        }
        changedParameters.remove("db.password");
        changedParameters.store(fos, "parameters-changed.properties");
    } catch (IOException e) {
        log.warn("Failed to export parameters-changed information", e);
    } finally {
        IOUtils.closeQuietly(fos);
    }

    writeRuntimeStats(engine, tmpDir);
    writeJobsStats(engine, tmpDir);

    if ("true".equals(System.getProperty(SystemConstants.SYSPROP_STANDALONE_WEB))) {
        writeDirectoryListing(engine, tmpDir);
    }

    fos = null;
    try {
        fos = new FileOutputStream(new File(tmpDir, "system.properties"));
        SortedProperties props = new SortedProperties();
        props.putAll(System.getProperties());
        props.store(fos, "system.properties");
    } catch (IOException e) {
        log.warn("Failed to export thread information", e);
    } finally {
        IOUtils.closeQuietly(fos);
    }

    try {
        File jarFile = new File(getSnapshotDirectory(engine), tmpDir.getName() + ".zip");
        JarBuilder builder = new JarBuilder(tmpDir, jarFile, new File[] { tmpDir }, Version.version());
        builder.build();
        FileUtils.deleteDirectory(tmpDir);
        return jarFile;
    } catch (IOException e) {
        throw new IoException("Failed to package snapshot files into archive", e);
    }
}

From source file:airbrake.Backtrace.java

private String toBacktrace(final StackTraceElement element) {
    return toBacktrace(element.getClassName(), element.getFileName(), element.getLineNumber(),
            element.getMethodName());//  ww  w.j  a v a  2s.co m
}

From source file:com.lazy.gank.logging.Logcat.java

/**
 * @param stackTraceElement/*from w  ww . j a va 2  s.c  o  m*/
 * @param type
 * @param objectMsg
 * @param tagArgs
 */
private static void printLog(final StackTraceElement stackTraceElement, int type, Object objectMsg,
        @Nullable String... tagArgs) {
    String msg;
    if (m_cLogCatShowLogType == OPERATION_BIT) {
        return;
    }

    String fileName = stackTraceElement.getFileName();
    String methodName = stackTraceElement.getMethodName();
    int lineNumber = stackTraceElement.getLineNumber();

    StringBuilder tagBuilder = new StringBuilder();
    tagBuilder.append(TAG);
    if (tagArgs == null) {
        tagBuilder.append(TAG_SEPARATOR);
        tagBuilder.append(fileName);
    } else {
        for (String tagArg : tagArgs) {
            tagBuilder.append(TAG_SEPARATOR);
            tagBuilder.append(tagArg);
        }
    }

    methodName = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);

    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[ (").append(fileName).append(":").append(lineNumber).append(")#").append(methodName)
            .append(" ] ");

    if (objectMsg == null) {
        msg = "Log with null Object";
    } else {
        msg = objectMsg.toString();
    }
    if (msg != null && type != SHOW_JSON_LOG) {
        stringBuilder.append(msg);
    }

    String logStr = stringBuilder.toString();

    switch (type) {
    case SHOW_VERBOSE_LOG:
        Log.v(tagBuilder.toString(), logStr);
        break;
    case SHOW_DEBUG_LOG:
        Log.d(tagBuilder.toString(), logStr);
        break;
    case SHOW_INFO_LOG:
        Log.i(tagBuilder.toString(), logStr);
        break;
    case SHOW_WARN_LOG:
        Log.w(tagBuilder.toString(), logStr);
        break;
    case SHOW_ERROR_LOG:
        Log.e(tagBuilder.toString(), logStr);
        break;
    case SHOW_JSON_LOG: {
        if (TextUtils.isEmpty(msg)) {
            Log.d(tagBuilder.toString(), "Empty or Null json content");
            return;
        }

        String message = null;

        try {
            if (msg.startsWith("{")) {
                JSONObject jsonObject = new JSONObject(msg);
                message = jsonObject.toString(JSON_INDENT);
            } else if (msg.startsWith("[")) {
                JSONArray jsonArray = new JSONArray(msg);
                message = jsonArray.toString(JSON_INDENT);
            }
        } catch (JSONException e) {
            e("JSONException/" + tagBuilder.toString(), e.getCause().getMessage() + LINE_SEPARATOR + msg);
            return;
        }

        printLine(JSON + tagBuilder.toString(), true);
        message = logStr + LINE_SEPARATOR + message;
        String[] lines = message.split(LINE_SEPARATOR);
        StringBuilder jsonContent = new StringBuilder();
        for (String line : lines) {
            jsonContent.append(" ").append(line).append(LINE_SEPARATOR);
        }
        Log.d(JSON + tagBuilder.toString(), jsonContent.toString());
        printLine(JSON + tagBuilder.toString(), false);
    }
        break;
    }

}

From source file:org.coinspark.core.CSLogger.java

public String line(String Message, CSLevel Level, int depth) {
    String result = "";

    if (sdf != null) {
        result += sdf.format(new Date()) + "\t";
    }//from w  w  w.  ja  v  a  2 s .  c om
    result += Level.getAbbr() + "\t";
    result += Message;

    if (depth > 0) {
        result += "\t";
        StackTraceElement ste = Thread.currentThread().getStackTrace()[depth];
        result += "[" + ste.getClassName() + "." + ste.getMethodName() + ", line " + ste.getLineNumber() + "]";
    }

    return result;
}

From source file:net.ymate.platform.log.AbstractLogger.java

/**
 * ??// ww  w .  j  a va  2 s.co  m
 *
 * @return ??className.methodName:lineNumber?NO_STACK_TRACE:-1
 */
protected String __doMakeCallerInfo() {
    StackTraceElement[] _stacks = new Throwable().getStackTrace();
    // ???
    if (__depth >= 0 && _stacks.length > 1 + __depth) {
        StackTraceElement _element = _stacks[1 + __depth];
        return StringUtils.substringBeforeLast(_element.getClassName(), ".").concat(".")
                .concat(_element.getMethodName()).concat(":")
                .concat(_element.getLineNumber() + StringUtils.EMPTY);
    }
    return "NO_STACK_TRACE:-1";
}

From source file:org.sonatype.nexus.mock.SeleniumTest.java

/**
 * Takes a screenshot of the browser and saves it to the target/screenshots directory. The exact name of the file is
 * based on the currently executing test class and method name plus the line number of the source code that called
 * this method./*from   www.j  a v  a  2  s . c  o m*/
 * 
 * @throws java.io.IOException If the screenshot could not be taken.
 */
protected void takeScreenshot() throws IOException {
    StackTraceElement ste = new Exception().getStackTrace()[1];
    takeScreenshot("line-" + ste.getLineNumber());
}

From source file:com.altoros.layout.JSONLayout.java

/**
 * Converts LoggingEvent Throwable to JSON object
 * @param json//from  w w w.  ja va  2s  .c  o  m
 * @param event
 * @throws JSONException
 */
protected void writeThrowable(JSONObject json, LoggingEvent event) throws JSONException {
    ThrowableInformation ti = event.getThrowableInformation();
    if (ti != null) {
        Throwable t = ti.getThrowable();
        JSONObject throwable = new JSONObject();

        throwable.put("message", t.getMessage());
        throwable.put("className", t.getClass().getCanonicalName());
        List<JSONObject> traceObjects = new ArrayList<JSONObject>();
        for (StackTraceElement ste : t.getStackTrace()) {
            JSONObject element = new JSONObject();
            element.put("class", ste.getClassName());
            element.put("method", ste.getMethodName());
            element.put("line", ste.getLineNumber());
            element.put("file", ste.getFileName());
            traceObjects.add(element);
        }

        json.put("stackTrace", traceObjects);
        json.put("throwable", throwable);
    }
}

From source file:org.uiautomation.ios.communication.FailedWebDriverLikeResponse.java

private JSONArray serializeStackTrace(StackTraceElement[] els) throws JSONException {
    JSONArray stacktace = new JSONArray();
    for (StackTraceElement el : els) {
        JSONObject stckEl = new JSONObject();
        stckEl.put("fileName", el.getFileName());
        stckEl.put("className", el.getClassName());
        stckEl.put("methodName", el.getMethodName());
        stckEl.put("lineNumber", el.getLineNumber());
        stacktace.put(stckEl);//from  w w  w  . j av a2s  . c om
    }
    return stacktace;
}

From source file:jext2.JextReentrantReadWriteLock.java

private String[] getElementsThatRequestedLock(StackTraceElement[] stack) {
    LinkedList<String> interresting = new LinkedList<String>();

    for (StackTraceElement element : stack) {
        if (element.getClassName().contains("jext2")
                && !element.getClassName().contains("JextReentrantReadWriteLock")) {
            interresting.add(element.getFileName() + ":" + element.getLineNumber());
        }/*w  ww.  j ava 2s.c  o m*/
    }
    return interresting.toArray(new String[0]);
}