Example usage for java.io LineNumberReader LineNumberReader

List of usage examples for java.io LineNumberReader LineNumberReader

Introduction

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

Prototype

public LineNumberReader(Reader in) 

Source Link

Document

Create a new line-numbering reader, using the default input-buffer size.

Usage

From source file:rega.genotype.ui.util.GenotypeLib.java

private static File getTreeEPS(File jobDir, File treeFile)
        throws IOException, InterruptedException, ApplicationException, FileNotFoundException {
    File epsFile = new File(treeFile.getPath().replace(".tre", ".eps"));
    if (epsFile.exists())
        return epsFile;

    Runtime runtime = Runtime.getRuntime();
    Process proc;/*w w  w  . j  a  va  2 s  . c o m*/
    int result;
    String cmd;

    cmd = Settings.treeGraphCommand + " -t " + treeFile.getAbsolutePath();
    System.err.println(cmd);
    proc = runtime.exec(cmd, null, jobDir);

    InputStream inputStream = proc.getInputStream();

    LineNumberReader reader = new LineNumberReader(new InputStreamReader(inputStream));

    Pattern taxaCountPattern = Pattern.compile("(\\d+) taxa read.");

    int taxa = 0;
    for (;;) {
        String s = reader.readLine();
        if (s == null)
            break;
        Matcher m = taxaCountPattern.matcher(s);

        if (m.find()) {
            taxa = Integer.valueOf(m.group(1)).intValue();
        }
    }

    if ((result = proc.waitFor()) != 0)
        throw new ApplicationException(cmd + " exited with error: " + result);

    proc.getErrorStream().close();
    proc.getInputStream().close();
    proc.getOutputStream().close();

    File tgfFile = new File(treeFile.getPath().replace(".tre", ".tgf"));
    File resizedTgfFile = new File(treeFile.getPath().replace(".tre", ".resized.tgf"));

    BufferedReader in = new BufferedReader(new FileReader(tgfFile));
    PrintStream out = new PrintStream(new FileOutputStream(resizedTgfFile));
    String line;
    while ((line = in.readLine()) != null) {
        line = line.replace("\\width{", "%\\width{");
        line = line.replace("\\height{", "%\\height{");
        line = line.replace("\\margin{", "%\\margin{");
        line = line.replace("\\style{r}{plain}", "%\\style{r}{plain}");
        line = line.replace("\\style{default}{plain}", "%\\style{default}{plain}");
        line = line.replaceAll("\\\\len\\{-", "\\\\len\\{");
        out.println(line);

        if (line.equals("\\begindef")) {
            out.println("\\paper{a2}");
            out.println("\\width{170}");
            out.println("\\height{" + (taxa * 8.6) + "}");
            out.println("\\margin{10}{10}{10}{10}");
            out.println("\\style{default}{plain}{13}");
            out.println("\\style{r}{plain}{13}");
        }
    }
    out.close();
    in.close();

    tgfFile.delete();
    resizedTgfFile.renameTo(tgfFile);

    cmd = Settings.treeGraphCommand + " -p " + tgfFile.getAbsolutePath();
    System.err.println(cmd);
    proc = runtime.exec(cmd, null, jobDir);
    if ((result = proc.waitFor()) != 0)
        throw new ApplicationException(cmd + " exited with error: " + result);

    proc.getErrorStream().close();
    proc.getInputStream().close();
    proc.getOutputStream().close();

    return epsFile;
}

From source file:com.thoughtworks.cruise.util.command.StreamPumper.java

public StreamPumper(InputStream in, StreamConsumer streamConsumer, String prefix, String encoding,
        Clock clock) {//from  ww w .j av a 2 s .  c  om
    this.streamConsumer = streamConsumer;
    this.prefix = prefix;
    this.clock = clock;
    this.lastHeard = System.currentTimeMillis();
    try {
        if (encoding == null) {
            this.in = new LineNumberReader(new InputStreamReader(in));
        } else {
            this.in = new LineNumberReader(new InputStreamReader(in, encoding));
        }
    } catch (UnsupportedEncodingException e) {
        bomb(format("Unable to use [%s] to decode stream.  The current charset is [%s]", encoding,
                defaultCharset()));
    }
}

From source file:com.puppycrawl.tools.checkstyle.checks.header.AbstractHeaderCheck.java

/**
 * Load header to check against from a Reader into readerLines.
 * @param headerReader delivers the header to check against
 * @throws IOException if/*from w  w w . j a  v a 2  s.c o m*/
 */
private void loadHeader(final Reader headerReader) throws IOException {
    final LineNumberReader lnr = new LineNumberReader(headerReader);
    readerLines.clear();
    while (true) {
        final String line = lnr.readLine();
        if (line == null) {
            break;
        }
        readerLines.add(line);
    }
    postProcessHeaderLines();
}

From source file:com.fujitsu.dc.common.ads.RollingAdsWriteFailureLog.java

/**
 * ?????ADS????.//from  w  ww . j a v a  2s.  c om
 * @param recordNum ?
 * @return ???
 * @throws AdsWriteFailureLogException ADS??????????
 */
public List<String> readAdsFailureLog(int recordNum) throws AdsWriteFailureLogException {
    try {
        if (null == this.reader) {
            reader = new LineNumberReader(new BufferedReader(new FileReader(this.rotatedAdsWriteFailureLog)));
        }
        List<String> logRecords = new ArrayList<String>();
        for (int i = 0; i < recordNum; i++) {
            String aRecord = reader.readLine();
            if (null == aRecord) {
                break;
            }
            logRecords.add(aRecord);
        }
        return logRecords;
    } catch (IOException e) {
        String messsage = String.format("Failed to read rotated adsWriteFailureLog. [%s]",
                rotatedAdsWriteFailureLog.getAbsolutePath());
        throw new AdsWriteFailureLogException(messsage, e);
    }
}

From source file:com.liferay.portal.scripting.ScriptingImpl.java

protected String getErrorMessage(String script, Exception e) {
    StringBundler sb = new StringBundler();

    sb.append(getErrorMessage(e));//w w w.  j  ava 2  s  .  c o m
    sb.append(StringPool.NEW_LINE);

    try {
        LineNumberReader lineNumberReader = new LineNumberReader(new UnsyncStringReader(script));

        while (true) {
            String line = lineNumberReader.readLine();

            if (line == null) {
                break;
            }

            sb.append("Line ");
            sb.append(lineNumberReader.getLineNumber());
            sb.append(": ");
            sb.append(line);
            sb.append(StringPool.NEW_LINE);
        }
    } catch (IOException ioe) {
        sb.setIndex(0);

        sb.append(getErrorMessage(e));
        sb.append(StringPool.NEW_LINE);
        sb.append(script);
    }

    return sb.toString();
}

From source file:nl.nn.adapterframework.webcontrol.FileViewerServlet.java

public static void showReaderContents(Reader reader, String filename, String type, HttpServletResponse response,
        String title) throws DomBuilderException, TransformerException, IOException {
    PrintWriter out = response.getWriter();
    if (type == null) {
        response.setContentType("text/html");
        out.println("resultType not specified");
        return;/*from   ww  w. j  a v a  2  s.c  o m*/
    }

    if (type.equalsIgnoreCase("html")) {
        response.setContentType("text/html");

        out.println("<html>");
        out.println("<head>");
        out.println("<title>" + AppConstants.getInstance().getResolvedProperty("instance.name.lc") + "@"
                + Misc.getHostname() + " - " + title + "</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\""
                + AppConstants.getInstance().getProperty(fvConfigKey + ".css") + "\">");
        out.println("</head>");
        out.println("<body>");

        LineNumberReader lnr = new LineNumberReader(reader);
        String line;
        while ((line = lnr.readLine()) != null) {
            out.println(makeConfiguredReplacements(XmlUtils.encodeChars(line)) + "<br/>");
        }

        out.println("</body>");
        out.println("</html>");
    }
    if (type.equalsIgnoreCase("text")) {
        response.setContentType("text/plain");
        String lastPart;
        try {
            File f = new File(filename);
            lastPart = f.getName();
        } catch (Throwable t) {
            lastPart = filename;
        }
        response.setHeader("Content-Disposition", "attachment; filename=\"" + lastPart + "\"");
        Misc.readerToWriter(reader, out);
    }
    if (type.equalsIgnoreCase("xml")) {
        response.setContentType("application/xml");
        String lastPart;
        try {
            File f = new File(filename);
            lastPart = f.getName();
        } catch (Throwable t) {
            lastPart = filename;
        }
        response.setHeader("Content-Disposition", "inline; filename=\"" + lastPart + "\"");
        LineNumberReader lnr;
        if (filename.indexOf("_xml.log") >= 0) {
            Reader fileReader = new EncapsulatingReader(reader, log4j_prefix, log4j_postfix, true);
            lnr = new LineNumberReader(fileReader);
        } else {
            if (filename.indexOf("-stats_") >= 0) {
                Reader fileReader = new EncapsulatingReader(reader, stats_prefix, stats_postfix, true);
                lnr = new LineNumberReader(fileReader);
            } else {
                lnr = new LineNumberReader(reader);
            }
        }
        String line;
        while ((line = lnr.readLine()) != null) {
            out.println(line + "\n");
        }
    }
    out.close();
}

From source file:net.sf.ginp.browser.FolderManagerImpl.java

/**
 *  Gets the picturesInDirectory attribute of the PicCollection object.
 *
 *@param  relPath  Description of the Parameter
 *@return          The picturesInDirectory value
 */// ww  w . j a  v  a  2  s .c  om
private String[] getPicturesInDirectory(final String root, final String relPath) {
    long duration = System.currentTimeMillis() - picCacheTimeout;

    if ((picCacheTimeout < 0) || (duration > MAX_CACHE)) {
        synchronized (picCache) {
            //Clearing a cache while doing a get can
            //cause hashmap to hang.  Hence all the synchronized blocks
            picCacheTimeout = System.currentTimeMillis();
            picCache.clear();
        }
    }

    synchronized (picCache) {
        if (picCache.get(root + relPath) != null) {
            String[] cached = (String[]) picCache.get(root + relPath);

            return cached;
        }
    }

    Vector pics = new Vector();

    try {
        File dir = new File(root + relPath);

        if (dir.isDirectory()) {
            String[] files = dir.list();

            for (int i = 0; i < files.length; i++) {
                File file = new File(root + relPath + "/" + files[i]);

                if ((!file.isDirectory()) && ((files[i].toLowerCase()).endsWith(".jpg")
                        || (files[i].toLowerCase()).endsWith(".jpeg"))) {
                    pics.add(files[i]);

                    if (log.isDebugEnabled()) {
                        log.debug("Adding picture file: " + files[i]);
                    }
                }
            }

            // Add Featured Pics
            File fl = new File(root + relPath + "ginpfolder.xml");

            if (fl.exists()) {
                FileReader fr = new FileReader(fl);
                LineNumberReader lr = new LineNumberReader(fr);
                StringBuffer sb = new StringBuffer();
                String temp;

                while ((temp = lr.readLine()) != null) {
                    sb.append(temp + "\n");
                }

                String featuredpicsXML = StringTool.getXMLTagContent("featuredpics", sb.toString());
                String[] picsXML = StringTool.splitToArray(featuredpicsXML, "<pic>");

                for (int i = 0; i < picsXML.length; i++) {
                    if (picsXML[i].indexOf("</pic>") != -1) {
                        temp = picsXML[i].substring(0, picsXML[i].indexOf("</pic>"));
                        fl = new File(root + relPath + temp);

                        if (fl.exists()) {
                            pics.add(temp);
                        }
                    }
                }
            }
        }
    } catch (IOException ex) {
        log.error(ex);
    }

    String[] retPictures = new String[pics.size()];

    for (int i = 0; i < pics.size(); i++) {
        retPictures[i] = (String) pics.get(i);
    }

    String[] sorted = sortPictures(retPictures);

    synchronized (picCache) {
        if (picCache.get(root + relPath) == null) {
            picCache.put(root + relPath, sorted);
        } else {
            return (String[]) picCache.get(root + relPath);
        }
    }

    // Only One Thread Per Directory Should Ever Get Here
    // (Unless it takes longer than 2 minutes to make)
    synchronized (MakeThumbs.class) {
        if ((mth == null) || ((mthThread != null) && !mthThread.isAlive())) {
            mth = new MakeThumbs();
            mthThread = new Thread(mth);
            mthThread.setDaemon(true);
            mthThread.setPriority(Thread.MIN_PRIORITY);
            mthThread.start();
        }
    }

    mth.addToQueue(root + relPath, sorted);

    return sorted;
}

From source file:org.intermine.install.properties.MinePropertiesLoader.java

/**
 * Write out the mine's user configuration properties file. This bases its format
 * on the file as it exists in the Intermine user home directory, writing lines verbatim
 * except for those where it has been supplied a property value. If no such file exists,
 * a standard template is used as the basis.
 * /*from  w w w. j a v  a2s. c om*/
 * @param mineName The name of the mine.
 * @param props The mine's user configuration properties.
 * 
 * @throws IOException if there is a problem performing the write.
 */
public static void saveProperties(String mineName, Properties props) throws IOException {
    File minePropertiesFile = getMinePropertiesFile(mineName);
    File mineBackupFile = null;

    Reader sourceReader;

    if (minePropertiesFile.exists()) {

        mineBackupFile = new File(minePropertiesFile.getParentFile(), minePropertiesFile.getName() + "~");

        if (mineBackupFile.exists()) {
            mineBackupFile.delete();
        }

        boolean ok = minePropertiesFile.renameTo(mineBackupFile);
        if (!ok) {
            throw new IOException("Failed to create backup file for " + minePropertiesFile.getAbsolutePath());
        }

        sourceReader = new FileReader(mineBackupFile);

    } else {
        if (intermineUserHome.exists()) {
            if (!intermineUserHome.isDirectory()) {
                throw new IOException(intermineUserHome.getAbsolutePath() + " is not a directory.");
            }
        } else {
            boolean ok = intermineUserHome.mkdir();
            if (!ok) {
                throw new IOException("Failed to create directory " + intermineUserHome.getAbsolutePath());
            }
        }

        InputStream in = MinePropertiesLoader.class.getResourceAsStream(PROPERTIES_TEMPLATE);
        if (in == null) {
            throw new FileNotFoundException(PROPERTIES_TEMPLATE);
        }
        sourceReader = new InputStreamReader(in);
    }

    LineNumberReader reader = new LineNumberReader(sourceReader);
    try {
        PrintWriter writer = new PrintWriter(new FileWriter(minePropertiesFile));
        try {
            String line;
            while ((line = reader.readLine()) != null) {
                Matcher m = PROPERTY_PATTERN.matcher(line);
                if (m.matches()) {
                    String key = m.group(1);
                    if (props.containsKey(key)) {
                        writer.print(key);
                        writer.print('=');
                        writer.println(props.get(key));
                    } else {
                        writer.println(line);
                    }
                } else {
                    writer.println(line);
                }
            }
        } finally {
            writer.close();
        }
    } finally {
        reader.close();
    }
}

From source file:stroom.streamstore.server.fs.ManualCheckStreamPerformance.java

public long readLargeFileTest() throws IOException {
    try (OutputStream os = getOutputStream()) {
        for (int i = 0; i < testSize; i++) {
            os.write("some data that may compress quite well TEST\n".getBytes(StreamUtil.DEFAULT_CHARSET));
            os.write(("some other information TEST\n" + i).getBytes(StreamUtil.DEFAULT_CHARSET));
            os.write("concurrent testing TEST\n".getBytes(StreamUtil.DEFAULT_CHARSET));
            os.write("TEST TEST TEST\n".getBytes(StreamUtil.DEFAULT_CHARSET));
            os.write("JAMES BETTY TEST\n".getBytes(StreamUtil.DEFAULT_CHARSET));
            os.write("FRED TEST\n".getBytes(StreamUtil.DEFAULT_CHARSET));
            os.write("<XML> TEST\n".getBytes(StreamUtil.DEFAULT_CHARSET));
        }//from  w  w w . j  a  v  a  2s.  com

        os.close();

        onCloseOutput(os);
    }

    final long startTime = System.currentTimeMillis();

    try (LineNumberReader reader = new LineNumberReader(
            new InputStreamReader(getInputStream(), StreamUtil.DEFAULT_CHARSET))) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (!line.contains("TEST")) {
                throw new RuntimeException("Something has gone wrong");
            }

        }

        final long timeTaken = System.currentTimeMillis() - startTime;
        return timeTaken;
    }
}

From source file:com.github.nlloyd.hornofmongo.action.MongoScriptAction.java

private boolean isOneLine(final String script) {
    LineNumberReader lnr = new LineNumberReader(new StringReader(script));
    try {/*w w  w . j a  v a2 s. c  om*/
        @SuppressWarnings("unused")
        int lastRead;
        while ((lastRead = lnr.read()) != -1) {
        }
    } catch (IOException e) {
    }
    // 0 lines just means no line terminator in the string
    return lnr.getLineNumber() <= 1;
}