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:edu.stanford.muse.index.NEROld.java

public static void readLocationNamesToSuppress() {
    String suppress_file = "suppress.locations.txt.gz";
    try {//from  w  ww  . ja  va  2s .  c  o  m
        InputStream is = new GZIPInputStream(NER.class.getClassLoader().getResourceAsStream(suppress_file));
        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(is, "UTF-8"));
        while (true) {
            String line = lnr.readLine();
            if (line == null)
                break;
            StringTokenizer st = new StringTokenizer(line);
            if (st.hasMoreTokens()) {
                String s = st.nextToken();
                if (!s.startsWith("#"))
                    locationsToSuppress.add(s.toLowerCase());
            }
        }
    } catch (Exception e) {
        log.warn("Error: unable to read " + suppress_file);
        Util.print_exception(e);
    }
    log.info(locationsToSuppress.size() + " names to suppress as locations");
}

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

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

    sb.append(e.getMessage());/*from w w w  . j ava 2s .  c  om*/
    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(e.getMessage());
        sb.append(StringPool.NEW_LINE);
        sb.append(script);
    }

    return sb.toString();
}

From source file:com.sds.acube.ndisc.xmigration.util.XNDiscMigUtil.java

/**
 * XMigration ? ?//from  ww  w . j  a v  a 2 s  .c om
 */
private static void readVersionFromFile() {
    XMigration_PublishingVersion = "<unknown>";
    XMigration_PublishingDate = "<unknown>";
    InputStreamReader isr = null;
    LineNumberReader lnr = null;
    try {
        isr = new InputStreamReader(
                XNDiscMigUtil.class.getResourceAsStream("/com/sds/acube/ndisc/xmigration/version.txt"));
        if (isr != null) {
            lnr = new LineNumberReader(isr);
            String line = null;
            do {
                line = lnr.readLine();
                if (line != null) {
                    if (line.startsWith("Publishing-Version=")) {
                        XMigration_PublishingVersion = line
                                .substring("Publishing-Version=".length(), line.length()).trim();
                    } else if (line.startsWith("Publishing-Date=")) {
                        XMigration_PublishingDate = line.substring("Publishing-Date=".length(), line.length())
                                .trim();
                    }
                }
            } while (line != null);
            lnr.close();
        }
    } catch (IOException ioe) {
        XMigration_PublishingVersion = "<unknown>";
        XMigration_PublishingDate = "<unknown>";
    } finally {
        try {
            if (lnr != null) {
                lnr.close();
            }
            if (isr != null) {
                isr.close();
            }
        } catch (IOException ioe) {
        }
    }
}

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

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

    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: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());
    }/*  www  .j  a  va 2 s  .c  om*/

    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;
    }
}

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

public Collection<Comune> donwloadAndParse() {
    try {/*ww w.  j  av a  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:org.testng.spring.test.AbstractTransactionalDataSourceSpringContextTests.java

/**
 * Execute the given SQL script. Will be rolled back by default,
 * according to the fate of the current transaction.
 * @param sqlResourcePath Spring resource path for the SQL script.
 * Should normally be loaded by classpath. There should be one statement
 * per line. Any semicolons will be removed.
 * <b>Do not use this method to execute DDL if you expect rollback.</b>
 * @param continueOnError whether or not to continue without throwing
 * an exception in the event of an error
 * @throws DataAccessException if there is an error executing a statement
 * and continueOnError was false/*from   w ww . ja  v a 2 s.c o  m*/
 */
protected void executeSqlScript(String sqlResourcePath, boolean continueOnError) throws DataAccessException {
    if (logger.isInfoEnabled()) {
        logger.info("Executing SQL script '" + sqlResourcePath + "'");
    }

    long startTime = System.currentTimeMillis();
    List statements = new LinkedList();
    Resource res = getApplicationContext().getResource(sqlResourcePath);
    try {
        LineNumberReader lnr = new LineNumberReader(new InputStreamReader(res.getInputStream()));
        String currentStatement = lnr.readLine();
        while (currentStatement != null) {
            currentStatement = StringUtils.replace(currentStatement, ";", "");
            statements.add(currentStatement);
            currentStatement = lnr.readLine();
        }

        for (Iterator itr = statements.iterator(); itr.hasNext();) {
            String statement = (String) itr.next();
            try {
                int rowsAffected = this.jdbcTemplate.update(statement);
                if (logger.isDebugEnabled()) {
                    logger.debug(rowsAffected + " rows affected by SQL: " + statement);
                }
            } catch (DataAccessException ex) {
                if (continueOnError) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("SQL: " + statement + " failed", ex);
                    }
                } else {
                    throw ex;
                }
            }
        }
        long elapsedTime = System.currentTimeMillis() - startTime;
        logger.info("Done executing SQL script '" + sqlResourcePath + "' in " + elapsedTime + " ms");
    } catch (IOException ex) {
        throw new DataAccessResourceFailureException("Failed to open SQL script '" + sqlResourcePath + "'", ex);
    }
}

From source file:com.l2jfree.tools.GPLLicenseChecker.java

private static List<String> read(File f) throws IOException {
    final List<String> list = new ArrayList<String>();

    LineNumberReader lnr = null;/*from   w ww . j a  va  2s  .c  om*/
    try {
        lnr = new LineNumberReader(new FileReader(f));

        for (String line; (line = lnr.readLine()) != null;)
            list.add(line);
    } finally {
        IOUtils.closeQuietly(lnr);
    }

    // to skip the script classes
    for (String line : list)
        if (line.startsWith("package com.sun.script."))
            return null;

    int ln = 0;
    if (!CLEARED) {
        for (int j = 0; j < CONFIDENTIAL.length; j++, ln++) {
            if (!list.get(j).equals(CONFIDENTIAL[j])) {
                MODIFIED.add(f.getPath() + ":" + ln);
                return list;
            }
        }
    }
    for (int j = 0; j < LICENSE.length; j++, ln++) {
        if (!list.get(ln).equals(LICENSE[j])) {
            MODIFIED.add(f.getPath() + ":LI" + ln);
            return list;
        }
    }

    if (!startsWithPackageName(list.get(ln))) {
        MODIFIED.add(f.getPath() + ":" + lnr.getLineNumber());
        return list;
    }

    return list;
}

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

public void run() {

    final String queue = getArgs()[0];

    String message = "";

    try {/*w w  w . ja  v a  2  s.  c  om*/
        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:pl.nask.hsn2.service.FileFeederTask.java

private LineNumberReader openReader() throws ResourceException {
    FileReader fileReader;/*  w w  w.j  a  v a  2  s . c om*/
    try {
        fileReader = new FileReader(uri);
    } catch (FileNotFoundException e) {
        throw new ResourceException(String.format("No file with name=%s found", uri), e);
    }
    LineNumberReader reader = new LineNumberReader(fileReader);

    return reader;
}