Example usage for java.io LineNumberReader getLineNumber

List of usage examples for java.io LineNumberReader getLineNumber

Introduction

In this page you can find the example usage for java.io LineNumberReader getLineNumber.

Prototype

public int getLineNumber() 

Source Link

Document

Get the current line number.

Usage

From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java

public void executeScriptList(File list) throws IOException {
    if (list.isFile()) {
        LineNumberReader lnr = new LineNumberReader(new FileReader(list));
        String line;/*from w  w  w. j ava 2 s.c  o m*/
        File file;

        while ((line = lnr.readLine()) != null) {
            String[] parts = line.trim().split("#");

            if (parts.length > 0 && !parts[0].startsWith("#") && parts[0].length() > 0) {
                line = parts[0];

                if (line.endsWith("/**")) {
                    line = line.substring(0, line.length() - 3);
                } else if (line.endsWith("/*")) {
                    line = line.substring(0, line.length() - 2);
                }

                file = new File(SCRIPT_FOLDER, line);

                if (file.isDirectory() && parts[0].endsWith("/**")) {
                    this.executeAllScriptsInDirectory(file, true, 32);
                } else if (file.isDirectory() && parts[0].endsWith("/*")) {
                    this.executeAllScriptsInDirectory(file);
                } else if (file.isFile()) {
                    try {
                        this.executeScript(file);
                    } catch (ScriptException e) {
                        reportScriptFileError(file, e);
                    }
                } else {
                    log.warn("Failed loading: (" + file.getCanonicalPath() + ") @ " + list.getName() + ":"
                            + lnr.getLineNumber() + " - Reason: doesnt exists or is not a file.");
                }
            }
        }
        lnr.close();
    } else {
        throw new IllegalArgumentException(
                "Argument must be an file containing a list of scripts to be loaded");
    }
}

From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.java

public void executeScriptList(File list) throws IOException {
    if (list.isFile()) {
        LineNumberReader lnr = new LineNumberReader(new FileReader(list));
        String line;//from   ww w  .  j  ava  2  s . c  o  m
        File file;

        while ((line = lnr.readLine()) != null) {
            String[] parts = line.trim().split("#");

            if (parts.length > 0 && !parts[0].startsWith("#") && parts[0].length() > 0) {
                line = parts[0];

                if (line.endsWith("/**")) {
                    line = line.substring(0, line.length() - 3);
                } else if (line.endsWith("/*")) {
                    line = line.substring(0, line.length() - 2);
                }

                file = new File(SCRIPT_FOLDER, line);

                if (file.isDirectory() && parts[0].endsWith("/**")) {
                    this.executeAllScriptsInDirectory(file, true, 32);
                } else if (file.isDirectory() && parts[0].endsWith("/*")) {
                    this.executeAllScriptsInDirectory(file);
                } else if (file.isFile()) {
                    try {
                        this.executeScript(file);
                    } catch (ScriptException e) {
                        reportScriptFileError(file, e);
                    }
                } else {
                    _log.warn("Failed loading: (" + file.getCanonicalPath() + ") @ " + list.getName() + ":"
                            + lnr.getLineNumber() + " - Reason: doesnt exists or is not a file.");
                }
            }
        }
        lnr.close();
    } else {
        throw new IllegalArgumentException(
                "Argument must be an file containing a list of scripts to be loaded");
    }
}

From source file:org.ngrinder.perftest.service.PerfTestService.java

/**
 * get the data point interval of report data. Use dataPointCount / imgWidth as the interval. if interval is 1, it
 * means we will get all point from report. If interval is 2, it means we will get 1 point from every 2 data.
 *
 * @param testId   test id//from   w  w  w .j a va  2 s  .  com
 * @param dataType data type
 * @param imgWidth image width
 * @return interval interval value
 */
public int getReportDataInterval(long testId, String dataType, int imgWidth) {
    int pointCount = Math.max(imgWidth, MAX_POINT_COUNT);
    File reportFolder = config.getHome().getPerfTestReportDirectory(String.valueOf(testId));
    int interval = 0;
    File targetFile = new File(reportFolder, dataType + DATA_FILE_EXTENSION);
    if (!targetFile.exists()) {
        LOGGER.warn("Report {} for test {} does not exist.", dataType, testId);
        return 0;
    }
    LineNumberReader lnr = null;

    FileInputStream in = null;
    InputStreamReader isr = null;
    try {
        in = new FileInputStream(targetFile);
        isr = new InputStreamReader(in);
        lnr = new LineNumberReader(isr);
        lnr.skip(targetFile.length());
        int lineNumber = lnr.getLineNumber() + 1;
        interval = Math.max(lineNumber / pointCount, 1);
    } catch (Exception e) {
        LOGGER.error("Failed to get report data for {}", dataType, e);
    } finally {
        IOUtils.closeQuietly(lnr);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(in);
    }

    return interval;
}

From source file:massbank.BatchJobWorker.java

/**
 * Ytt@C???iHTML`?j//from  ww  w. j a  v a  2 s . c  o  m
 * @param time NGXg 
 * @param resultFile t@C
 * @param htmlFile YtpHTMLt@C
 */
private void createHtmlFile(String time, File resultFile, File htmlFile) {
    NumberFormat nf = NumberFormat.getNumberInstance();
    LineNumberReader in = null;
    PrintWriter out = null;
    try {
        in = new LineNumberReader(new FileReader(resultFile));
        out = new PrintWriter(new BufferedWriter(new FileWriter(htmlFile)));

        // wb_?[?o
        String reqIonStr = "Both";
        try {
            if (Integer.parseInt(this.ion) > 0) {
                reqIonStr = "Positive";
            } else if (Integer.parseInt(this.ion) < 0) {
                reqIonStr = "Negative";
            }
        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
        out.println("<html>");
        out.println("<head><title>MassBank Batch Service Results</title></head>");
        out.println("<body>");
        out.println(
                "<h1><a href=\"http://www.massbank.jp/\" target=\"_blank\">MassBank</a> Batch Service Results</h1>");
        out.println("<hr>");
        out.println("<h2>Request Date : " + time + "<h2>");
        out.println("Instrument Type : " + this.inst + "<br>");
        out.println("Ion Mode : " + reqIonStr + "<br>");
        out.println("<br><hr>");

        // ?o
        String line;
        long queryCnt = 0;
        boolean readName = false;
        boolean readHit = false;
        boolean readNum = false;
        while ((line = in.readLine()) != null) {
            if (in.getLineNumber() < 4) {
                continue;
            }
            if (!readName) {
                queryCnt++;
                out.println("<h2>Query " + nf.format(queryCnt) + "</h2><br>");
                out.println("Name: " + line.trim() + "<br>");
                readName = true;
            } else if (!readHit) {
                out.println("Hit: " + nf.format(Integer.parseInt(line.trim())) + "<br>");
                readHit = true;
            } else if (!readNum) {
                out.println("<table border=\"1\">");
                out.println("<tr><td colspan=\"6\">Top " + line.trim() + " List</td></tr>");
                out.println(
                        "<tr><th>Accession</th><th>Title</th><th>Formula</th><th>Ion</th><th>Score</th><th>Hit</th></tr>");
                readNum = true;
            } else {
                if (!line.trim().equals("")) {
                    String[] data = formatLine(line);
                    String acc = data[0];
                    String title = data[1];
                    String formula = data[2];
                    String ion = data[3];
                    String score = data[4];
                    String hit = data[5];

                    out.println("<tr>");
                    out.println("<td><a href=\"http://www.massbank.jp/jsp/FwdRecord.jsp?id=" + acc
                            + "\" target=\"_blank\">" + acc + "</td>");
                    out.println("<td>" + title + "</td>");
                    out.println("<td>" + formula + "</td>");
                    out.println("<td>" + ion + "</td>");
                    out.println("<td>" + score + "</td>");
                    out.println("<td align=\"right\">" + hit + "</td>");
                    out.println("</tr>");
                } else {
                    out.println("</table>");
                    out.println("<hr>");
                    readName = false;
                    readHit = false;
                    readNum = false;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
        }
        if (out != null) {
            out.flush();
            out.close();
        }
    }
}

From source file:org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeReader.java

public void read(final File polyFile) throws IOException {
    LineNumberReader reader = null;
    try {//  w  w  w  . j a v a2s .  c o m
        reader = new LineNumberReader(new FileReader(polyFile));

        while (reader.ready()) {
            final String line = reader.readLine();
            if (line == null)
                break;

            final String trimmedLine = line.trim().replaceAll(" \\(h\\)", "\\(h\\)"); //$NON-NLS-1$ //$NON-NLS-2$
            final String[] tokens = trimmedLine.split(" +"); //$NON-NLS-1$
            if (tokens.length < 8)
                continue;

            /* Determine if this is a good line: good lines are lines whos first token is a number */
            final BigDecimal station;
            try {
                station = new BigDecimal(tokens[0]);
            } catch (final NumberFormatException nfe) {
                /* Just ignore this line */
                continue;
            }

            try {
                final String description = tokens[1];
                // final String whatIsN = tokens[2];
                final char type = tokens[3].charAt(0);

                final int order = Integer.parseInt(tokens[4]);
                final double rangeMin = Double.parseDouble(tokens[5].replace('D', 'E'));
                final double rangeMax = Double.parseDouble(tokens[6].replace('D', 'E'));

                if (tokens.length < 7 + order + 1) {
                    /* A good line but bad content. Give user a hint that something might be wrong. */
                    m_log.log(false,
                            Messages.getString(
                                    "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.22"), //$NON-NLS-1$
                            polyFile.getName(), reader.getLineNumber());
                    continue;
                }

                final List<Double> coefficients = new ArrayList<>(order);
                for (int i = 7; i < 7 + order + 1; i++) {
                    final double coeff = Double.parseDouble(tokens[i].replace('D', 'E'));
                    coefficients.add(coeff);
                }

                final Double[] doubles = coefficients.toArray(new Double[coefficients.size()]);
                final double[] coeffDoubles = ArrayUtils.toPrimitive(doubles);

                final String domainId;
                final String rangeId = IWspmTuhhQIntervallConstants.DICT_PHENOMENON_WATERLEVEL;
                switch (type) {
                case 'Q':
                    domainId = IWspmTuhhQIntervallConstants.DICT_PHENOMENON_RUNOFF;
                    break;
                case 'A':
                    domainId = IWspmTuhhQIntervallConstants.DICT_PHENOMENON_AREA;
                    break;
                case 'a':
                    domainId = IWspmTuhhQIntervallConstants.DICT_PHENOMENON_ALPHA;
                    break;

                default:
                    m_log.log(false,
                            Messages.getString(
                                    "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.23"), //$NON-NLS-1$
                            station);
                    continue;
                }

                /* find feature for station */
                final QIntervallResult qresult = m_intervalIndex.get(station);
                if (qresult == null)
                    m_log.log(false,
                            Messages.getString(
                                    "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.24"), //$NON-NLS-1$
                            station, line);
                else {
                    /* create new polynome */
                    final IPolynomial1D poly1d = qresult.createPolynomial();

                    poly1d.setName(description);
                    poly1d.setDescription(description);
                    poly1d.setCoefficients(coeffDoubles);
                    poly1d.setRange(rangeMin, rangeMax);

                    poly1d.setDomainPhenomenon(domainId);
                    poly1d.setRangePhenomenon(rangeId);
                }
            } catch (final NumberFormatException nfe) {
                /* A good line but bad content. Give user a hint that something might be wrong. */
                m_log.log(false,
                        Messages.getString(
                                "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.25"), //$NON-NLS-1$
                        polyFile.getName(), reader.getLineNumber(), nfe.getLocalizedMessage());
            } catch (final Exception e) {
                // should never happen
                m_log.log(e,
                        Messages.getString(
                                "org.kalypso.model.wspm.tuhh.schema.simulation.PolynomeProcessor.25"), //$NON-NLS-1$
                        polyFile.getName(), reader.getLineNumber(), e.getLocalizedMessage());
            }
        }
        reader.close();
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:org.talend.designer.runprocess.java.JavaProcessor.java

/**
 * yzhang Comment method "updateGraphicalNodeBreaking".
 * /* ww  w . j ava2 s.  c  o  m*/
 * @param breakpoint
 */
private void updateGraphicalNodeBreaking(IJavaBreakpoint breakpoint, boolean removed) {
    try {
        Integer breakLineNumber = (Integer) breakpoint.getMarker().getAttribute(IMarker.LINE_NUMBER);
        if (breakLineNumber == null || breakLineNumber == -1) {
            return;
        }
        IFile codeFile = this.getCodeProject().getFile(this.getSrcCodePath());
        if (!codeFile.exists()) {
            JDIDebugModel.removeJavaBreakpointListener(this);
            return;
        }
        LineNumberReader lineReader = new LineNumberReader(new InputStreamReader(codeFile.getContents()));
        String content = null;
        while (lineReader.getLineNumber() < breakLineNumber - 3) {
            content = lineReader.readLine();
            if (content == null) {
                return;
            }
        }
        int startIndex = content.indexOf("[") + 1; //$NON-NLS-1$
        int endIndex = content.indexOf(" main ] start"); //$NON-NLS-1$
        if (startIndex != -1 && endIndex != -1) {
            String nodeUniqueName = content.substring(startIndex, endIndex);
            List<? extends INode> breakpointNodes = CorePlugin.getContext().getBreakpointNodes(process);
            List<? extends INode> graphicalNodes = process.getGraphicalNodes();
            if (graphicalNodes == null) {
                return;
            }
            for (INode node : graphicalNodes) {
                if (node.getUniqueName().equals(nodeUniqueName) && removed && breakpointNodes.contains(node)) {
                    CorePlugin.getContext().removeBreakpoint(process, node);
                    if (node instanceof Node) {
                        final INode currentNode = node;
                        Display.getDefault().syncExec(new Runnable() {

                            @Override
                            public void run() {
                                ((Node) currentNode).removeStatus(Process.BREAKPOINT_STATUS);

                            }

                        });
                    }
                } else if (node.getUniqueName().equals(nodeUniqueName) && !removed
                        && !breakpointNodes.contains(node)) {
                    CorePlugin.getContext().addBreakpoint(process, node);
                    if (node instanceof Node) {
                        final INode currentNode = node;
                        Display.getDefault().syncExec(new Runnable() {

                            @Override
                            public void run() {
                                ((Node) currentNode).addStatus(Process.BREAKPOINT_STATUS);

                            }

                        });
                    }
                }
            }

        }

    } catch (CoreException e) {
        RuntimeExceptionHandler.process(e);
    } catch (IOException e) {
        RuntimeExceptionHandler.process(e);
    }
}

From source file:com.thoughtworks.go.server.database.MigrateHsqldbToH2.java

private void replayScript(File scriptFile) throws SQLException, IOException {
    if (!scriptFile.exists()) {
        return;/*from   w  ww.ja  v a  2  s . c om*/
    }

    System.out.println("Migrating hsql file: " + scriptFile.getName());
    Connection con = source.getConnection();
    Statement stmt = con.createStatement();
    stmt.executeUpdate("SET REFERENTIAL_INTEGRITY FALSE");
    LineNumberReader reader = new LineNumberReader(new FileReader(scriptFile));
    String line;
    while ((line = reader.readLine()) != null) {
        try {
            String table = null;
            Matcher matcher = createTable.matcher(line);
            if (matcher.find()) {
                table = matcher.group(2).trim();
            }

            if (line.equals("CREATE SCHEMA PUBLIC AUTHORIZATION DBA")) {
                continue;
            }
            if (line.equals("CREATE SCHEMA CRUISE AUTHORIZATION DBA")) {
                continue;
            }
            if (line.startsWith("CREATE USER SA PASSWORD")) {
                continue;
            }
            if (line.contains("BUILDEVENT VARCHAR(255)")) {
                line = line.replace("BUILDEVENT VARCHAR(255)", "BUILDEVENT LONGVARCHAR");
            }
            if (line.contains("COMMENT VARCHAR(4000)")) {
                line = line.replace("COMMENT VARCHAR(4000)", "COMMENT LONGVARCHAR");
            }
            if (line.contains("CREATE MEMORY TABLE")) {
                line = line.replace("CREATE MEMORY TABLE", "CREATE CACHED TABLE");
            }
            if (table != null && table.equals("MATERIALPROPERTIES") && line.contains("VALUE VARCHAR(255),")) {
                line = line.replace("VALUE VARCHAR(255),", "VALUE LONGVARCHAR,");
            }
            if (line.startsWith("GRANT DBA TO SA")) {
                continue;
            }
            if (line.startsWith("CONNECT USER")) {
                continue;
            }
            if (line.contains("DISCONNECT")) {
                continue;
            }
            if (line.contains("AUTOCOMMIT")) {
                continue;
            }
            stmt.executeUpdate(line);
            if (reader.getLineNumber() % LINES_PER_DOT == 0) {
                System.out.print(".");
                System.out.flush();
            }
            if (reader.getLineNumber() % (80 * LINES_PER_DOT) == 0) {
                System.out.println();
            }

        } catch (SQLException e) {
            bomb("Error executing : " + line, e);
        }
    }
    stmt.executeUpdate("SET REFERENTIAL_INTEGRITY TRUE");
    stmt.executeUpdate("CHECKPOINT SYNC");
    System.out.println("\nDone.");
    reader.close();
    stmt.close();
    con.close();
}

From source file:org.kalypso.model.wspm.core.imports.DA50Importer.java

/**
 * @param srsName/*from   w  w  w .  j av a  2  s.c o m*/
 *          The coordinate system code.
 */
private static DA50Entry[] readDA50(final LineNumberReader lnr, final String srsName)
        throws IOException, CoreException {
    final List<DA50Entry> result = new ArrayList<>();

    final MultiStatus logStatus = new MultiStatus(KalypsoModelWspmCorePlugin.getID(), 0,
            Messages.getString("org.kalypso.model.wspm.core.imports.DA50Importer.2"), null); //$NON-NLS-1$

    while (lnr.ready()) {
        final String line = lnr.readLine();
        if (line == null) {
            break;
        }

        try {

            if (line.length() < 60 || !line.startsWith("50")) //$NON-NLS-1$
            {
                continue;
            }

            // Station auslesen und mit 0en auffllen, sonst klappt das umrechnen in m nicht immer
            // CString help_str = str.Mid( 9,9 );
            // help_str.TrimRight();
            // help_str = help_str + CString( '0', 9 - help_str.GetLength() );
            final String stationString = line.substring(9, 18).trim();
            final StringBuffer stationBuf = new StringBuffer(stationString);
            for (int i = stationString.length() - 9; i < 0; i++) {
                stationBuf.append('0');
            }

            // int temp = 0;
            // sscanf( help_str, "%d", &temp );
            // double station = (double)temp / 1000000;
            final double station = Double.parseDouble(stationBuf.toString()) / 1000000;

            // logstream << "Geokoordinaten gefunden fr Station: " << station << std::endl;

            // logstream << "Querprofil mit gleicher Station gefunden" << std::endl;

            // double rw_start, rw_end,hw_start,hw_end;
            // __int64 rh_wert;

            // help_str=str.Mid(21-1,10);

            final String rwStartString = line.substring(20, 30);
            final String hwStartString = line.substring(30, 40);
            final String rwEndString = line.substring(40, 50);
            final String hwEndString = line.substring(50, 60);

            final double rwStart = Double.parseDouble(rwStartString) / 1000.0;
            final double hwStart = Double.parseDouble(hwStartString) / 1000.0;
            final double rwEnd = Double.parseDouble(rwEndString) / 1000.0;
            final double hwEnd = Double.parseDouble(hwEndString) / 1000.0;

            final GM_Point start = WspmGeometryUtilities.pointFromRwHw(rwStart, hwStart, Double.NaN, srsName,
                    null);
            final GM_Point end = WspmGeometryUtilities.pointFromRwHw(rwEnd, hwEnd, Double.NaN, srsName, null);

            result.add(new DA50Entry(station, start, end));
        } catch (final Exception e) {
            final IStatus status = StatusUtilities.statusFromThrowable(e, Messages
                    .getString("org.kalypso.model.wspm.core.imports.DA50Importer.4", lnr.getLineNumber())); //$NON-NLS-1$
            logStatus.add(status);
        }
    }

    if (!logStatus.isOK())
        throw new CoreException(logStatus);

    return result.toArray(new DA50Entry[result.size()]);
}

From source file:org.jumpmind.metl.core.runtime.component.XmlReader.java

void processFiles(List<String> files, Message inputMessage, ISendMessageCallback callback,
        boolean unitOfWorkLastMessage) throws XmlPullParserException, IOException {
    IDirectory directory = getResourceReference();
    XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
    for (String file : files) {
        ArrayList<String> outboundPayload = new ArrayList<String>();
        log(LogLevel.INFO, "Reading %s", file);
        Map<String, Serializable> headers = new HashMap<>();
        headers.put("source.file.path", file);
        LineNumberReader lineNumberReader = null;
        InputStream parserIs = null;
        try {//from www . j  av a2s .  co  m
            String filePath = resolveParamsAndHeaders(file, inputMessage);
            parserIs = directory.getInputStream(filePath, mustExist);
            if (parserIs != null) {
                InputStreamReader reader = new InputStreamReader(directory.getInputStream(filePath, mustExist),
                        encoding);
                parser.setInput(parserIs, encoding);
                lineNumberReader = new LineNumberReader(reader);
                lineNumberReader.setLineNumber(1);
                int startCol = 0;
                int startLine = 1;
                int prevEndLine = 1;
                int prevEndCol = 0;
                int eventType = parser.getEventType();
                String line = null;
                while (eventType != XmlPullParser.END_DOCUMENT) {
                    switch (eventType) {
                    case XmlPullParser.START_TAG:
                        if (StringUtils.isBlank(readTag)) {
                            readTag = parser.getName();
                            info("Read tag was not set, defaulting to root tag: " + readTag);
                        }
                        if (parser.getName().equals(readTag)) {
                            startCol = prevEndCol;
                            startLine = prevEndLine;
                        }
                        prevEndCol = parser.getColumnNumber();
                        prevEndLine = parser.getLineNumber();
                        break;
                    case XmlPullParser.END_TAG:
                        prevEndCol = parser.getColumnNumber();
                        prevEndLine = parser.getLineNumber();
                        if (parser.getName().equals(readTag)) {
                            StringBuilder xml = new StringBuilder();

                            forward(startLine, lineNumberReader);

                            int linesToRead = parser.getLineNumber() - lineNumberReader.getLineNumber();
                            if (lineNumberReader.getLineNumber() > startLine) {
                                startCol = 0;
                            }
                            line = lineNumberReader.readLine();

                            while (linesToRead >= 0 && line != null) {
                                if (startCol > 0) {
                                    if (line.length() > startCol) {
                                        xml.append(line.substring(startCol)).append("\n");
                                    }
                                    startCol = 0;
                                } else if (linesToRead == 0) {
                                    if (line.length() > parser.getColumnNumber()) {
                                        xml.append(line.substring(0, parser.getColumnNumber()));
                                    } else {
                                        xml.append(line).append("\n");
                                    }
                                } else {
                                    xml.append(line).append("\n");
                                }

                                linesToRead--;
                                if (linesToRead >= 0) {
                                    line = lineNumberReader.readLine();
                                }
                            }
                            getComponentStatistics().incrementNumberEntitiesProcessed(threadNumber);
                            outboundPayload.add(xml.toString());
                            if (outboundPayload.size() == readTagsPerMessage) {
                                callback.sendTextMessage(headers, outboundPayload);
                                outboundPayload = new ArrayList<String>();
                            }
                            startCol = 0;
                        }
                        break;
                    }
                    eventType = parser.next();
                }
            } else {
                info("File %s didn't exist, but Must Exist setting was false.  Continuing", file);
            }
        } finally {
            closeQuietly(lineNumberReader);
            closeQuietly(parserIs);
        }

        if (outboundPayload.size() > 0) {
            callback.sendTextMessage(headers, outboundPayload);
        }
    }
}

From source file:net.rptools.maptool.launcher.MapToolLauncher.java

/**
 * Reads from a file named mt.cfg in the same directory to get the following
 * options. Each option is placed on a single line followed by an equal sign
 * ('=') and then the appropriate value. The default values are coded below.
 * //from  www .  j  a  va 2s .c  om
 * All memory sizes are in megabytes.
 */
private boolean readCfgFile() {
    boolean rv = false;

    // Set the defaults in the map.  As lines are read from the config file, overwrite the
    // map entries with the new values.  When we're done, we can look at the map entries
    // in an appropriate order and ensure dependencies are handled correctly as well as
    // convert values to the proper data types.
    final Map<String, String> values = new HashMap<String, String>(10);
    values.put("MAXMEM", Integer.toString(maxMemVal)); //$NON-NLS-1$
    values.put("MINMEM", Integer.toString(minMemVal)); //$NON-NLS-1$
    values.put("STACKSIZE", Integer.toString(stackSizeVal)); //$NON-NLS-1$
    values.put("PROMPT", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    final List<String> errors = new ArrayList<String>();
    if (cfgFile.isFile() && cfgFile.length() > 0) {
        rv = true; // Assume that something was found.

        LineNumberReader lnbr = null;
        try {
            lnbr = new LineNumberReader(new BufferedReader(new FileReader(cfgFile)));
            try {
                String line = lnbr.readLine();
                while (line != null) {
                    line = line.trim();
                    if (!line.startsWith("#") && !line.isEmpty()) { //$NON-NLS-1$
                        final String[] arg = line.split("=", 2); // Only apply first delimiter //$NON-NLS-1$
                        if (arg.length == 2) {
                            values.put(arg[0].toUpperCase().trim(), arg[1].trim());
                        } else {
                            errors.add(CopiedFromOtherJars.getText("msg.error.configBadFormat", cfgFile, //$NON-NLS-1$
                                    lnbr.getLineNumber(), line));
                        }
                    }
                    line = lnbr.readLine();
                }
            } catch (final IOException ex) {
                logMsg(Level.SEVERE, "Error reading configuration file: {0}", "msg.error.configIOError", //$NON-NLS-1$
                        cfgFile); //$NON-NLS-2$
            }
        } catch (final FileNotFoundException ex) {
            // This shouldn't happen since we specifically used cfgFile.isFIle(), above, and that can't be true
            // unless the file actually exists.
            logMsg(Level.SEVERE, "Configuration file {0} not found.", "msg.error.configFileNotFound", cfgFile); //$NON-NLS-1$ $NON-NLS-2$
        } finally {
            try {
                lnbr.close();
            } catch (final IOException ex) {
                logMsg(Level.SEVERE, "Error closing configuration file {0}.", "msg.error.configClosing", //$NON-NLS-1$
                        cfgFile); //$NON-NLS-2$
            }
        }
    } else {
        logMsg(Level.INFO, "Configuration file not found; using built-in defaults", "msg.error.configNotFound", //$NON-NLS-1$
                cfgFile); //$NON-NLS-2$
    }
    // Build a list of all XML files in the same directory as the launcher.  This list of
    // filenames will be used to validate the LOGGING parameter from the configuration file.
    File logging = new File(currentDir, "logging"); //$NON-NLS-1$
    if (!logging.isDirectory()) {
        logging = currentDir;
    }
    logConfigs = buildLoggingFileList(logging);

    // Now process the records just read in (or the defaults).  Errors are accumulated into 'errors'.
    parseCfgValues(values, errors);
    if (!errors.isEmpty()) {
        errors.add(0, CopiedFromOtherJars.getText("msg.info.configFeedback")); //$NON-NLS-1$
        CopiedFromOtherJars.showFeedback(ERROR_MESSAGE, errors.toArray());
    }
    // Keep track of the original values.  When we go to save the configuration file, we
    // only write to it if something has changed.
    originalSettings = values;

    // Update UI fields for these three values.
    assignMinMem();
    assignMaxMem();
    assignStackSize();

    updateStrings();
    return rv;
}