Example usage for java.io LineNumberReader readLine

List of usage examples for java.io LineNumberReader readLine

Introduction

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

Prototype

public String readLine() throws IOException 

Source Link

Document

Read a line of text.

Usage

From source file:org.seqdoop.hadoop_bam.TestVCFOutputFormat.java

@Test
public void testSimple() throws Exception {
    VariantContextBuilder vctx_builder = new VariantContextBuilder();

    ArrayList<Allele> alleles = new ArrayList<Allele>();
    alleles.add(Allele.create("A", false));
    alleles.add(Allele.create("C", true));
    vctx_builder.alleles(alleles);/*from   w  ww .j  a  v a 2s. co  m*/

    GenotypesContext genotypes = GenotypesContext.NO_GENOTYPES;
    vctx_builder.genotypes(genotypes);

    HashSet<String> filters = new HashSet<String>();
    vctx_builder.filters(filters);

    HashMap<String, Object> attributes = new HashMap<String, Object>();
    attributes.put("NS", new Integer(4));
    vctx_builder.attributes(attributes);

    vctx_builder.loc("20", 2, 2);
    vctx_builder.log10PError(-8.0);

    String[] expected = new String[] { "20", "2", ".", "C", "A", "80", "PASS", "NS=4" };

    VariantContext ctx = vctx_builder.make();
    writable.set(ctx);
    writer.write(1L, writable);
    writer.close(taskAttemptContext);

    LineNumberReader reader = new LineNumberReader(new FileReader(test_vcf_output));
    skipHeader(reader);
    String[] fields = Arrays.copyOf(reader.readLine().split("\t"), expected.length);
    Assert.assertArrayEquals("comparing VCF single line", expected, fields);
}

From source file:ch.cyberduck.core.i18n.RegexLocale.java

private void load(final String table, final File file) throws IOException {
    final LineNumberReader reader = new LineNumberReader(
            new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-16")));
    try {/* www .j a  v a2  s .  c  om*/
        String line;
        while ((line = reader.readLine()) != null) {
            final Matcher matcher = pattern.matcher(line);
            if (matcher.matches()) {
                cache.put(new Key(table, matcher.group(1)), matcher.group(2));
            }
        }
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:org.apache.qpid.amqp_1_0.client.Send.java

public void run() {

    final String queue = getArgs()[0];

    String message = "";

    try {//from ww  w.  jav  a2 s  .  c o  m
        Connection conn = newConnection();

        Session session = conn.createSession();

        Sender s = session.createSender(queue, getWindowSize(), getMode(), getLinkName());

        Transaction txn = null;

        if (useTran()) {
            txn = session.createSessionLocalTransaction();
        }

        if (!useStdIn()) {
            if (getArgs().length <= 2) {
                if (getArgs().length == 2) {
                    message = getArgs()[1];
                }
                for (int i = 0; i < getCount(); i++) {

                    Properties properties = new Properties();
                    properties.setMessageId(UnsignedLong.valueOf(i));
                    if (getSubject() != null) {
                        properties.setSubject(getSubject());
                    }
                    Section bodySection;
                    byte[] bytes = (message + "  " + i).getBytes();
                    if (bytes.length < getMessageSize()) {
                        byte[] origBytes = bytes;
                        bytes = new byte[getMessageSize()];
                        System.arraycopy(origBytes, 0, bytes, 0, origBytes.length);
                        for (int x = origBytes.length; x < bytes.length; x++) {
                            bytes[x] = (byte) '.';
                        }
                        bodySection = new Data(new Binary(bytes));
                    } else {
                        bodySection = new AmqpValue(message + " " + i);
                    }

                    Section[] sections = { properties, bodySection };
                    final Message message1 = new Message(Arrays.asList(sections));

                    s.send(message1, txn);
                }
            } else {
                for (int i = 1; i < getArgs().length; i++) {
                    s.send(new Message(getArgs()[i]), txn);
                }

            }
        } else {
            LineNumberReader buf = new LineNumberReader(new InputStreamReader(System.in));

            try {
                while ((message = buf.readLine()) != null) {
                    s.send(new Message(message), txn);
                }
            } catch (IOException e) {
                // TODO
                e.printStackTrace();
            }
        }

        if (txn != null) {
            txn.commit();
        }

        s.close();

        session.close();
        conn.close();
    } catch (Sender.SenderClosingException e) {
        e.printStackTrace(); //TODO.
    } catch (Connection.ConnectionException e) {
        e.printStackTrace(); //TODO.
    } catch (Sender.SenderCreationException e) {
        e.printStackTrace(); //TODO.
    }

}

From source file:net.sf.ginp.tags.GetFolderInfo.java

/**
 *  Called when a Start tag is processed.
 *
 *@return                   Description of the Return Value
 *@exception  JspException  Description of the Exception
 *///from w w  w .j  av a  2 s. co  m
public final int doStartTag() throws JspException {
    String title = "";
    String description = "";
    String date = "";
    String time = "";

    try {
        model = ModelUtil.getModel((HttpServletRequest) pageContext.getRequest());
    } catch (Exception e) {
        throw new JspException(e);
    }

    try {
        File fl = new File(
                model.getCollection().getRoot() + model.getCollection().getPath() + "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");
            }

            // Date
            date = StringTool.getXMLTagContent("date", sb.toString());

            if (date != null) {
                pageContext.setAttribute("date", date);
            } else {
                pageContext.setAttribute("date", "");
            }

            // Time
            time = StringTool.getXMLTagContent("time", sb.toString());

            if (time != null) {
                pageContext.setAttribute("time", time);
            } else {
                pageContext.setAttribute("time", "");
            }

            // Title
            temp = StringTool.getXMLTagContent("title", sb.toString());
            title = StringTool.getXMLTagContent(model.getLocale().getLanguage(), temp);

            if (title != null) {
                pageContext.setAttribute("title", title);
            } else {
                pageContext.setAttribute("title", "");
            }

            // description
            temp = StringTool.getXMLTagContent("description", sb.toString());
            description = StringTool.getXMLTagContent(model.getLocale().getLanguage(), temp);

            if (description != null) {
                pageContext.setAttribute("description", description);
            } else {
                pageContext.setAttribute("description", "");
            }

            pageContext.setAttribute("path", model.getCollection().getPath());
            pageContext.setAttribute("colid", "" + model.getCurrCollectionId());
            pageContext.setAttribute("langcode", "" + model.getLocale().getLanguage());

            return EVAL_BODY_AGAIN;
        } else {
            return SKIP_BODY;
        }
    } catch (Exception ex) {
        return SKIP_BODY;
    }
}

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

private void replayScript(File scriptFile) throws SQLException, IOException {
    if (!scriptFile.exists()) {
        return;/*from  ww w .  j av a 2  s  .  com*/
    }

    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.openanzo.jdbc.opgen.ant.DDLTask.java

private void writeFile(Writer writer, String filename, String file, String outputFormat)
        throws FileNotFoundException, IOException {
    Reader in = new InputStreamReader(new FileInputStream(file), "UTF-8");
    LineNumberReader lnr = new LineNumberReader(in);
    StringBuilder content = new StringBuilder();
    String line;//w  ww. j av a 2s  .co m
    while ((line = lnr.readLine()) != null) {
        line = StringUtils.trim(line);
        if (line.length() == 0 || line.startsWith("#"))
            continue;
        line = Pattern.compile("[\\s+]", Pattern.MULTILINE).matcher(line).replaceAll(" ");
        line = Pattern.compile(";+", Pattern.MULTILINE).matcher(line).replaceAll(";;");
        line = Pattern.compile("&sc", Pattern.MULTILINE).matcher(line).replaceAll(";");
        line = Pattern.compile("&plus", Pattern.MULTILINE).matcher(line).replaceAll("+");
        content.append(line);
        content.append(" ");
    }
    writer.write(content.toString());
    in.close();
    lnr.close();
}

From source file:com.sg2net.utilities.ListaCAP.ListaComuniCapFromInternet.java

public Collection<Comune> donwloadAndParse() {
    try {/*from   w ww .  java  2 s.c  o  m*/
        List<Comune> comuni = new ArrayList<>();
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(ZIP_URL);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            try (InputStream instream = entity.getContent();) {
                ZipInputStream zipInputStream = new ZipInputStream(instream);
                ZipEntry entry = zipInputStream.getNextEntry();

                if (entry != null) {
                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    byte data[] = new byte[BUFFER];
                    int count = 0;
                    while ((count = zipInputStream.read(data, 0, BUFFER)) != -1) {
                        outputStream.write(data, 0, count);
                    }
                    StringReader reader = new StringReader(
                            new String(outputStream.toByteArray(), HTML_ENCODING));
                    LineNumberReader lineReader = new LineNumberReader(reader);
                    String line;
                    int lineNumber = 0;
                    while ((line = lineReader.readLine()) != null) {
                        logger.trace("line " + (lineNumber + 1) + " from zip file=" + line);
                        if (lineNumber > 0) {
                            String[] values = line.split(";");
                            if (values.length >= 9) {
                                Comune comune = new Comune(values[CODICE_ISTAT_POS],
                                        values[CODICE_CATASTALE_POS], values[NOME_POS], values[PROVINCIA_POS]);
                                comuni.add(comune);
                                String capStr = values[CAP_POS];
                                Collection<String> capList;
                                if (capStr.endsWith("x")) {
                                    capList = getListaCAPFromHTMLPage(values[URL_COMUNE_POS]);
                                } else {
                                    capList = new HashSet<>();
                                    capList.add(capStr);
                                }
                                comune.setCodiciCap(capList);
                            }
                        }
                        lineNumber++;
                    }
                }
            }
        }
        return comuni;
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:nl.b3p.viewer.util.databaseupdate.ScriptRunner.java

/**
 * Runs an SQL script (read in using the Reader parameter) using the
 * connection passed in//from ww w . j av a2 s . com
 *
 * @param conn - the connection to use for the script
 * @param reader - the source of the script
 * @throws SQLException if any SQL errors occur
 * @throws IOException if there is an error reading from the Reader
 */
private void runScript(Connection conn, Reader reader) throws IOException, SQLException {
    StringBuffer command = null;
    try {
        LineNumberReader lineReader = new LineNumberReader(reader);
        String line = null;
        while ((line = lineReader.readLine()) != null) {
            if (command == null) {
                command = new StringBuffer();
            }
            String trimmedLine = line.trim();
            if (trimmedLine.startsWith("--")) {
                log.debug(trimmedLine);
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("//")) {
                // Do nothing
            } else if (trimmedLine.length() < 1 || trimmedLine.startsWith("--")) {
                // Do nothing
            } else if (!fullLineDelimiter && trimmedLine.endsWith(getDelimiter())
                    || fullLineDelimiter && trimmedLine.equals(getDelimiter())) {
                command.append(line.substring(0, line.lastIndexOf(getDelimiter())));
                command.append(" ");
                Statement statement = conn.createStatement();

                log.debug(command);

                boolean hasResults = false;
                if (stopOnError) {
                    hasResults = statement.execute(command.toString());
                } else {
                    try {
                        statement.execute(command.toString());
                    } catch (SQLException e) {
                        e.fillInStackTrace();
                        log.error("Error executing: " + command, e);
                    }
                }

                if (autoCommit && !conn.getAutoCommit()) {
                    conn.commit();
                }

                ResultSet rs = statement.getResultSet();
                if (hasResults && rs != null) {
                    ResultSetMetaData md = rs.getMetaData();
                    int cols = md.getColumnCount();
                    for (int i = 0; i < cols; i++) {
                        String name = md.getColumnLabel(i);
                        log.debug(name + "\t");
                    }
                    while (rs.next()) {
                        for (int i = 0; i < cols; i++) {
                            String value = rs.getString(i);
                            log.debug(value + "\t");
                        }
                    }
                }

                command = null;
                try {
                    statement.close();
                } catch (Exception e) {
                    // Ignore to workaround a bug in Jakarta DBCP
                }
                Thread.yield();
            } else {
                command.append(line);
                command.append(" ");
            }
        }
        if (!autoCommit) {
            conn.commit();
        }
    } catch (SQLException e) {
        e.fillInStackTrace();
        log.error("Error executing: " + command, e);
        throw e;
    } catch (IOException e) {
        e.fillInStackTrace();
        log.error("Error executing: " + command, e);
        throw e;
    } finally {
        if (!this.autoCommit) {
            conn.rollback();
        }
    }
}

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

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

    sb.append(getErrorMessage(e));/*from   ww w.  jav a  2s .com*/
    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:mitm.common.security.ca.handlers.comodo.AutoAuthorize.java

private void handleResponse(int statusCode, HttpMethod httpMethod) throws IOException {
    if (statusCode != HttpStatus.SC_OK) {
        throw new IOException("Error Authorize. Message: " + httpMethod.getStatusLine());
    }//from   ww  w .j a  va 2s .co m

    InputStream input = httpMethod.getResponseBodyAsStream();

    if (input == null) {
        throw new IOException("Response body is null.");
    }

    /*
     * we want to set a max on the number of bytes to download. We do not want a rogue server to return 1GB.
     */
    InputStream limitInput = new SizeLimitedInputStream(input, MAX_HTTP_RESPONSE_SIZE);

    String response = IOUtils.toString(limitInput, CharEncoding.US_ASCII);

    if (logger.isDebugEnabled()) {
        logger.debug("Response:\r\n" + response);
    }

    LineNumberReader lineReader = new LineNumberReader(new StringReader(response));

    String statusParameter = lineReader.readLine();

    errorCode = CustomClientStatusCode.fromCode(statusParameter);

    if (errorCode.getID() < CustomClientStatusCode.SUCCESSFUL.getID()) {
        error = true;

        errorMessage = lineReader.readLine();
    } else {
        error = false;
    }
}