Example usage for org.apache.commons.io LineIterator nextLine

List of usage examples for org.apache.commons.io LineIterator nextLine

Introduction

In this page you can find the example usage for org.apache.commons.io LineIterator nextLine.

Prototype

public String nextLine() 

Source Link

Document

Returns the next line in the wrapped Reader.

Usage

From source file:org.neo4art.sentiment.service.DictionaryBasicService.java

/**
 * //from w  w w .j a  va 2 s.  c o  m
 * @param file
 * @param polarity
 * @throws IOException
 */
private void addPolarity(String file, int polarity) throws IOException {
    logger.info("Adding polarity from file: " + file);

    LineIterator polarityFile = IOUtils.lineIterator(getClass().getClassLoader().getResourceAsStream(file),
            Charset.defaultCharset());

    while (polarityFile.hasNext()) {
        String word = polarityFile.nextLine();

        if (StringUtils.isNotEmpty(word) && !StringUtils.startsWith(word, ";")) {
            Long wordNodeId = this.mergeWordWithoutFlushing(DictionaryUtils.escapeWordForLuceneSearch(word));

            Neo4ArtBatchInserterSingleton.setNodeProperty(wordNodeId, Word.POLARITY_PROPERTY_NAME, polarity);
        }
    }

    Neo4ArtBatchInserterSingleton.flushLegacyNodeIndex(NLPLegacyIndex.WORD_LEGACY_INDEX);
}

From source file:org.objectstyle.woproject.maven2.wobootstrap.utils.WebObjectsUtils.java

/**
 * Retrieves the version of installed WebObjects. It uses a
 * <code>WebObjectsLocator</code> to find the WebObjects version file.
 * //from   w  ww .j  a v a2 s. co  m
 * @param locator
 *            The WebObjects locator
 * @return Returns the WebObjects version or <code>null</code> if cannot
 *         discover the WebObjects version
 */
public static String getWebObjectsVersion(WebObjectsLocator locator) {
    if (locator == null) {
        return null;
    }

    File versionFile = locator.getWebObjectsVersionFile();

    if (versionFile == null || !versionFile.exists()) {
        return null;
    }

    String version = null;

    LineIterator iterator = null;

    try {
        iterator = FileUtils.lineIterator(versionFile, null);

        while (iterator.hasNext()) {
            String line = iterator.nextLine();

            if ("<key>CFBundleShortVersionString</key>".equals(line.trim())) {
                String versionLine = iterator.nextLine();

                version = versionLine.trim().replaceAll("</?string>", "");

                break;
            }
        }

    } catch (IOException exception) {
        // TODO: hprange, write an info to log instead
        exception.printStackTrace();
    } finally {
        if (iterator != null) {
            LineIterator.closeQuietly(iterator);
        }
    }

    return version;
}

From source file:org.onesec.raven.ivr.impl.ExternalTextToSpeechEngineNodeTest.java

private void printStream(InputStream stream) throws IOException {
    LineIterator it = IOUtils.lineIterator(stream, "utf-8");
    while (it.hasNext())
        System.out.println("LINE: " + it.nextLine());
}

From source file:org.openmrs.module.emrmonitor.metric.ConfigurableMetricProducer.java

/**
 * If multiple lines of output are returned and each is in the format of key=value, then the key will be considered part of the metric, and the value the value
 * Otherwise, the full contents of output will be the value of a single metric
 *//*from  www  .j a va 2  s  . c o  m*/
protected void handleShellScript(Map<String, String> metrics, String namespace, File f) throws IOException {
    Process process = Runtime.getRuntime().exec(f.getAbsolutePath());
    StringBuilder singleValueMetric = new StringBuilder();
    Map<String, String> keyValueMetrics = new LinkedHashMap<String, String>();
    LineIterator successIterator = null;
    try {
        successIterator = IOUtils.lineIterator(process.getInputStream(), "UTF-8");
        while (successIterator.hasNext()) {
            String line = successIterator.nextLine();
            String[] split = StringUtils.splitByWholeSeparatorPreserveAllTokens(line, "=", 2);
            if (split.length == 2) {
                keyValueMetrics.put(namespace + "." + split[0], split[1]);
            } else {
                singleValueMetric.append(line).append(System.getProperty("line.separator"));
            }
        }
        if (singleValueMetric.length() > 0) {
            metrics.put(namespace, singleValueMetric.toString());
        } else {
            metrics.putAll(keyValueMetrics);
        }
    } finally {
        successIterator.close();
    }

    StringBuilder error = new StringBuilder();
    LineIterator errorIterator = null;
    try {
        errorIterator = IOUtils.lineIterator(process.getErrorStream(), "UTF-8");
        while (errorIterator.hasNext()) {
            String line = errorIterator.nextLine();
            error.append(System.getProperty("line.separator")).append(line);
        }
    } finally {
        errorIterator.close();
    }

    if (error.length() > 0) {
        throw new RuntimeException(
                "An error occurred while executing shell script " + f.getName() + ": " + error);
    }
}

From source file:org.openmrs.module.pihmalawi.sql.MysqlRunner.java

/**
  * Executes a Sql Script//from  w  ww.  ja  v a 2s .  c  o  m
 */
public static MysqlResult executeSql(String sql, Map<String, Object> parameterValues) {

    log.info("Executing SQL...");

    File toExecute = null;
    try {
        // Writing SQL to temporary file for execution
        toExecute = File.createTempFile("mysqlrunner", ".sql");

        StringBuilder sqlToWrite = new StringBuilder();

        if (parameterValues != null) {
            for (String paramName : parameterValues.keySet()) {
                Object paramValue = parameterValues.get(paramName);
                sqlToWrite.append("set @").append(paramName);
                sqlToWrite.append("=").append(getParameterAssignmentString(paramValue)).append(";");
                sqlToWrite.append(System.getProperty("line.separator"));
            }
        }
        sqlToWrite.append(sql);

        FileUtils.writeStringToFile(toExecute, sqlToWrite.toString());
        log.debug("Wrote SQL file for execution: " + toExecute.getAbsolutePath());
        log.debug("Contents:\n" + sqlToWrite);

        // Constructing command line elements to execute
        List<String> commands = new ArrayList<String>();
        commands.add("mysql");
        commands.add("-u" + Context.getRuntimeProperties().getProperty("connection.username"));
        commands.add("-p" + Context.getRuntimeProperties().getProperty("connection.password"));
        commands.add("-esource " + toExecute.getAbsolutePath());

        commands.add(DatabaseUpdater.getConnection().getCatalog()); // Database Name
        log.debug("Constructed command to execute: \n" + OpenmrsUtil.join(commands, " "));

        Process process = Runtime.getRuntime().exec(commands.toArray(new String[] {}));

        MysqlResult result = new MysqlResult();
        LineIterator successIterator = null;
        try {
            successIterator = IOUtils.lineIterator(process.getInputStream(), "UTF-8");
            while (successIterator.hasNext()) {
                String line = successIterator.nextLine();
                String[] elements = StringUtils.splitPreserveAllTokens(line, '\t');
                if (result.getColumns().isEmpty()) {
                    result.setColumns(Arrays.asList(elements));
                } else {
                    Map<String, String> row = new LinkedHashMap<String, String>();
                    for (int i = 0; i < result.getColumns().size(); i++) {
                        String value = elements[i].trim();
                        if ("NULL".equals(value)) {
                            value = null;
                        }
                        row.put(result.getColumns().get(i), value);
                    }
                    result.getData().add(row);
                }
            }
        } finally {
            successIterator.close();
        }

        LineIterator errorIterator = null;
        try {
            errorIterator = IOUtils.lineIterator(process.getErrorStream(), "UTF-8");
            while (errorIterator.hasNext()) {
                String line = errorIterator.nextLine();
                if (!line.toLowerCase().startsWith("warning")) {
                    result.getErrors().add(line);
                }
            }
        } finally {
            errorIterator.close();
        }

        return result;
    } catch (Exception e) {
        throw new RuntimeException("An error occurred while executing a SQL file", e);
    } finally {
        FileUtils.deleteQuietly(toExecute);
    }
}

From source file:org.orbisgis.view.toc.actions.cui.legend.components.ColorScheme.java

/**
 * Fills the inner collections using the dedicated resource file.
 *//*from  w ww  .j av a2  s .  co m*/
private static void load() {
    rangeColorSchemeNames = new ArrayList<>();
    discreteColorSchemeNames = new ArrayList<>();
    nameToColorsMap = new HashMap<>();
    InputStream stream = ColorScheme.class.getResourceAsStream("ColorScheme.txt");
    if (stream != null) {
        InputStreamReader br = new InputStreamReader(stream);
        LineIterator lineIterator = IOUtils.lineIterator(br);
        try {
            while (lineIterator.hasNext()) {
                String line = lineIterator.nextLine();
                add(line);
            }
        } finally {
            LineIterator.closeQuietly(lineIterator);
        }
    }
}

From source file:org.pentaho.metadata.query.model.util.CsvDataReader.java

public List<List<String>> loadData() {
    String line = null;/*from   ww  w.ja  v  a2 s  . c  om*/
    List<List<String>> dataSample = new ArrayList<List<String>>(rowLimit);
    List<String> rowData = null;
    InputStreamReader reader = null;
    CSVTokenizer csvt = null;
    LineIterator lineIterator = null;
    try {
        InputStream inputStream = KettleVFS.getInputStream(fileLocation);
        reader = new InputStreamReader(inputStream);
        lineIterator = new LineIterator(reader);
        int row = 0;
        int count;
        while (row < rowLimit && lineIterator.hasNext()) {
            line = lineIterator.nextLine();
            ++row;

            csvt = new CSVTokenizer(line, delimiter, enclosure, false);
            rowData = new ArrayList<String>();
            count = 0;

            while (csvt.hasMoreTokens()) {
                // get next token and store it in the list
                rowData.add(csvt.nextToken());
                count++;
            }

            if (columnCount < count) {
                columnCount = count;
            }

            if (headerPresent && row == 1) {
                header = rowData;
            } else {
                dataSample.add(rowData);
            }
        }
    } catch (KettleFileException e) {
        logger.error(Messages.getString("CsvDataReader.ERROR_0001_Failed"), e); //$NON-NLS-1$
    } finally {
        LineIterator.closeQuietly(lineIterator);
        IOUtils.closeQuietly(reader);
    }
    data = dataSample;
    return dataSample;
}

From source file:org.proninyaroslav.libretorrent.core.IPFilterParser.java

public static boolean parseDATFilterFile(String path, ip_filter filter) {
    if (path == null || filter == null) {
        return false;
    }//  w  ww.ja  va  2 s .c om

    File file = new File(path);
    if (!file.exists()) {
        return false;
    }

    LineIterator it = null;

    try {
        it = FileUtils.lineIterator(file, "UTF-8");

    } catch (IOException e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }

    if (it == null) {
        return false;
    }

    long lineNum = 0;
    long badLineNum = 0;
    try {
        while (it.hasNext()) {
            ++lineNum;
            String line = it.nextLine();

            line = line.trim();
            if (line.isEmpty()) {
                continue;
            }

            /* Ignoring commented lines */
            if (line.startsWith("#") || line.startsWith("//")) {
                continue;
            }

            /* Line should be split by commas */
            String[] parts = line.split(",");
            long elementNum = parts.length;

            /* IP Range should be split by a dash */
            String[] ips = parts[0].split("-");
            if (ips.length != 2) {
                Log.w(TAG, "parseDATFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "Line was " + line);
                ++badLineNum;
                continue;
            }

            String startIp = cleanupIPAddress(ips[0]);
            if (startIp == null || startIp.isEmpty()) {
                Log.w(TAG, "parseDATFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "Start IP of the range is malformated: " + ips[0]);
                ++badLineNum;
                continue;
            }

            error_code error = new error_code();
            address startAddr = address.from_string(startIp, error);
            if (error.value() > 0) {
                Log.w(TAG, "parseDATFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "Start IP of the range is malformated:" + ips[0]);
                ++badLineNum;
                continue;
            }

            String endIp = cleanupIPAddress(ips[1]);
            if (endIp == null || endIp.isEmpty()) {
                Log.w(TAG, "parseDATFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "End IP of the range is malformated: " + ips[1]);
                ++badLineNum;
                continue;
            }

            address endAddr = address.from_string(endIp, error);
            if (error.value() > 0) {
                Log.w(TAG, "parseDATFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "End IP of the range is malformated:" + ips[1]);
                ++badLineNum;
                continue;
            }

            if (startAddr.is_v4() != endAddr.is_v4()) {
                Log.w(TAG, "parseDATFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "One IP is IPv4 and the other is IPv6!");
                ++badLineNum;
                continue;
            }

            /* Check if there is an access value (apparently not mandatory) */
            int accessNum = 0;
            if (elementNum > 1) {
                /* There is possibly one */
                accessNum = Integer.parseInt(parts[1].trim());
            }

            /* Ignoring this rule because access value is too high */
            if (accessNum > 127) {
                continue;
            }

            try {
                filter.add_rule(startAddr, endAddr, ip_filter.access_flags.blocked.swigValue());

            } catch (Exception e) {
                Log.w(TAG, "parseDATFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "Line was " + line);
                ++badLineNum;
            }
        }

    } finally {
        it.close();
    }

    return badLineNum < lineNum;
}

From source file:org.proninyaroslav.libretorrent.core.IPFilterParser.java

public static boolean parseP2PFilterFile(String path, ip_filter filter) {
    if (path == null || filter == null) {
        return false;
    }/*from  w w  w.jav  a 2s  .  c  o m*/

    File file = new File(path);
    if (!file.exists()) {
        return false;
    }

    LineIterator it = null;

    try {
        it = FileUtils.lineIterator(file, "UTF-8");

    } catch (IOException e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }

    if (it == null) {
        return false;
    }

    long lineNum = 0;
    long badLineNum = 0;

    try {
        while (it.hasNext()) {
            ++lineNum;
            String line = it.nextLine();

            line = line.trim();
            if (line.isEmpty()) {
                continue;
            }

            /* Ignoring commented lines */
            if (line.startsWith("#") || line.startsWith("//")) {
                continue;
            }

            /* Line should be split by ':' */
            String[] parts = line.split(":");
            if (parts.length < 2) {
                Log.w(TAG, "parseP2PFilterFile: line " + lineNum + " is malformed.");
                ++badLineNum;
                continue;
            }

            /* IP Range should be split by a dash */
            String[] ips = parts[1].split("-");
            if (ips.length != 2) {
                Log.w(TAG, "parseP2PFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "Line was " + line);
                ++badLineNum;
                continue;
            }

            String startIp = cleanupIPAddress(ips[0]);
            if (startIp == null || startIp.isEmpty()) {
                Log.w(TAG, "parseP2PFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "Start IP of the range is malformated: " + ips[0]);
                ++badLineNum;
                continue;
            }

            error_code error = new error_code();
            address startAddr = address.from_string(startIp, error);
            if (error.value() > 0) {
                Log.w(TAG, "parseP2PFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "Start IP of the range is malformated:" + ips[0]);
                ++badLineNum;
                continue;
            }

            String endIp = cleanupIPAddress(ips[1]);
            if (endIp == null || endIp.isEmpty()) {
                Log.w(TAG, "parseP2PFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "End IP of the range is malformated: " + ips[1]);
                ++badLineNum;
                continue;
            }

            address endAddr = address.from_string(endIp, error);
            if (error.value() > 0) {
                Log.w(TAG, "parseP2PFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "End IP of the range is malformated:" + ips[1]);
                ++badLineNum;
                continue;
            }

            if (startAddr.is_v4() != endAddr.is_v4()) {
                Log.w(TAG, "parseP2PFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "One IP is IPv4 and the other is IPv6!");
                ++badLineNum;
                continue;
            }

            try {
                filter.add_rule(startAddr, endAddr, ip_filter.access_flags.blocked.swigValue());

            } catch (Exception e) {
                Log.w(TAG, "parseP2PFilterFile: line " + lineNum + " is malformed.");
                Log.w(TAG, "Line was " + line);
                ++badLineNum;
            }
        }

    } finally {
        it.close();
    }

    return badLineNum < lineNum;
}

From source file:org.schedulesdirect.api.LineupTest.java

static private void initJsonData() throws Exception {
    try {/*from w  ww .  j  a  v a  2 s .  c o m*/
        if (!SampleData.updateFor(SampleType.LINEUPS, false))
            LOG.info("Using current sample data because it's less than a week old.");
    } catch (Exception e) {
        if (!SampleData.exists(SampleType.LINEUPS))
            throw new IOException("No sample data available!", e);
        else
            LOG.warn("Failed to download fresh sample data; using existing data instead!");
    }
    LineIterator itr = FileUtils.lineIterator(SampleData.locate(SampleType.LINEUPS), "UTF-8");
    while (itr.hasNext())
        SAMPLE_DATA.add(itr.nextLine());
}