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

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

Introduction

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

Prototype

public static void closeQuietly(LineIterator iterator) 

Source Link

Document

Closes the iterator, handling null and ignoring exceptions.

Usage

From source file:com.googlecode.jgenhtml.CoverageReport.java

/**
 * Parses a gcov tracefile./*from   w  w  w  . j  av a2  s .c  o  m*/
 * @param traceFile A gcov tracefile.
 * @param isDescFile true if this is a descriptions (.desc) file.
 * @param isBaseFile true if this is a baseline file.
 */
private void parseDatFile(final File traceFile, final boolean isDescFile, final boolean isBaseFile)
        throws IOException, ParserConfigurationException {
    //I used the info from here: http://manpages.ubuntu.com/manpages/precise/man1/geninfo.1.html
    File fileToProcess;
    if (traceFile.getName().endsWith(".gz")) {
        LOGGER.log(Level.FINE, "File {0} ends with .gz, going to gunzip it.", traceFile.getName());
        fileToProcess = JGenHtmlUtils.gunzip(traceFile);
    } else {
        fileToProcess = traceFile;
    }
    LineIterator iterator = FileUtils.lineIterator(fileToProcess);
    try {
        TestCaseSourceFile testCaseSourceFile = null;
        String testCaseName = DEFAULT_TEST_NAME;
        while (iterator.hasNext()) {
            String line = iterator.nextLine();
            int tokenIdx = line.indexOf("SF:");
            if (tokenIdx >= 0 || (tokenIdx = line.indexOf("KF:")) >= 0) {
                String fullPath = line.substring(line.indexOf(tokenIdx) + 4);
                File sourceFile = new File(fullPath);
                fullPath = sourceFile.getCanonicalPath();
                testCaseSourceFile = parsedFiles.get(fullPath);
                if (!isBaseFile && testCaseSourceFile == null) {
                    testCaseSourceFile = new TestCaseSourceFile(testTitle, sourceFile.getName());
                    testCaseSourceFile.setSourceFile(sourceFile);
                    parsedFiles.put(fullPath, testCaseSourceFile);
                }
            } else if (line.indexOf("end_of_record") >= 0) {
                if (testCaseSourceFile != null) {
                    testCaseName = DEFAULT_TEST_NAME;
                    testCaseSourceFile = null;
                } else {
                    LOGGER.log(Level.FINE, "Unexpected end of record");
                }
            } else if (testCaseSourceFile != null) {
                testCaseSourceFile.processLine(testCaseName, line, isBaseFile);
            } else {
                if (isDescFile) {
                    descriptionsPage.addLine(line);
                } else if (line.startsWith("TN:")) {
                    String[] data = JGenHtmlUtils.extractLineValues(line);
                    testCaseName = data[0].trim();
                    if (testCaseName.length() > 0) {
                        if (runTestNames == null) {
                            runTestNames = new HashSet<String>();
                        }
                        runTestNames.add(testCaseName);
                    }
                } else {
                    LOGGER.log(Level.FINE, "Unexpected line: {0}", line);
                }
            }
        }
    } finally {
        LineIterator.closeQuietly(iterator);
    }
}

From source file:com.ipcglobal.fredimport.process.Reference.java

/**
 * Creates the ref currencies countries.
 *
 * @param path the path/*from  w  ww.  jav  a 2s.c  om*/
 * @throws Exception the exception
 */
private void createRefCurrenciesCountries(String path) throws Exception {
    refCountriesByCurrencies = new HashMap<String, String>();
    refCurrenciesByCountries = new HashMap<String, String>();

    LineIterator it = FileUtils.lineIterator(new File(path + FILENAME_CURRENCIES_COUNTRIES), "UTF-8");
    try {
        while (it.hasNext()) {
            // Format: <countryName>|<primaryCurrencyName>|<akaCurrencyName1>|<akaCurrencyName2>|...
            String line = it.nextLine();
            String[] fields = line.split("[|]");
            for (int i = 0; i < fields.length; i++)
                fields[i] = fields[i].trim();
            fields[1] = fields[1].trim();
            // When looking up by country, always return the primary currency
            refCurrenciesByCountries.put(fields[0], fields[1]);
            for (int i = 1; i < fields.length; i++)
                refCountriesByCurrencies.put(fields[i], fields[0]);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }
}

From source file:com.ipcglobal.fredimport.process.Reference.java

/**
 * Creates the ref world regions.//from   w w  w  .j a  v a 2  s.  com
 *
 * @param path the path
 * @throws Exception the exception
 */
private void createRefWorldRegions(String path) throws Exception {
    refWorldRegions = new HashMap<String, Object>();

    LineIterator it = FileUtils.lineIterator(new File(path + FILENAME_WORLD_REGIONS), "UTF-8");
    try {
        while (it.hasNext()) {
            // Format: <worldRegion>
            String worldRegion = it.nextLine().trim();
            refWorldRegions.put(worldRegion, null);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }
}

From source file:eu.annocultor.converters.geonames.GeonamesCsvToRdf.java

void labels() throws Exception {
    System.out.println("Loading alt names");
    //Map<String, List<XmlValue>> altLabels = new HashMap<String, List<XmlValue>();
    LineIterator it = FileUtils.lineIterator(new File(root, "alternateNames.txt"), "UTF-8");
    try {//from  www  .ja  v a 2s.c o m
        while (it.hasNext()) {
            String text = it.nextLine();

            String[] fields = text.split("\t");
            //               if (fields.length != 4) {
            //                  throw new Exception("Field names mismatch on " + text);
            //               }
            String uri = fields[1];
            String lang = fields[2];
            String label = fields[3];
            if ("link".equals(lang)) {
                // wikipedia links
                links.put(uri, label);
            } else {
                if (lang.length() < 3) {
                    altLabels.put(uri, new LiteralValue(label, lang.isEmpty() ? null : lang));
                } else {
                    // mostly postcodes
                    //System.out.println("LANG: " + lang + " on " + label);
                }
            }
        }
    } finally {
        LineIterator.closeQuietly(it);
    }
}

From source file:com.ipcglobal.fredimport.process.Reference.java

/**
 * Creates the ref institutions./*from   ww w .  j  a v a 2  s . c  om*/
 *
 * @param path the path
 * @throws Exception the exception
 */
private void createRefInstitutions(String path) throws Exception {
    refInstitutions = new HashMap<String, Object>();

    LineIterator it = FileUtils.lineIterator(new File(path + FILENAME_INSTITUTIONS), "UTF-8");
    try {
        while (it.hasNext()) {
            // Format: <institution>
            String institution = it.nextLine().trim();
            refWorldRegions.put(institution, null);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }
}

From source file:eu.annocultor.converters.geonames.GeonamesCsvToRdf.java

void collectParents() throws Exception {
    System.out.println("Loading parents");
    LineIterator it = FileUtils.lineIterator(new File(root, "hierarchy.txt"), "UTF-8");
    try {//ww w . j  ava2  s. c  o  m
        while (it.hasNext()) {
            String text = it.nextLine();

            String[] fields = text.split("\t");
            String parent = NS_GEONAMES_INSTANCES + fields[0] + "/";
            String child = NS_GEONAMES_INSTANCES + fields[1] + "/";
            broader.put(child, parent);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }
}

From source file:dk.netarkivet.harvester.datamodel.PartialHarvest.java

/**
 * This method is a duplicate of the addSeeds method but for seedsFile parameter
 *
 * @param seedsFile a newline-separated File containing the seeds to be added
 * @param templateName the name of the template to be used
 * @param maxBytes Maximum number of bytes to harvest per domain
 * @param maxObjects Maximum number of objects to harvest per domain
 *//*w w w . j  a va2s .  c om*/
public void addSeedsFromFile(File seedsFile, String templateName, long maxBytes, int maxObjects,
        Map<String, String> attributeValues) {
    ArgumentNotValid.checkNotNull(seedsFile, "seeds");
    ArgumentNotValid.checkTrue(seedsFile.isFile(), "seedsFile does not exist");
    ArgumentNotValid.checkNotNullOrEmpty(templateName, "templateName");
    if (!TemplateDAO.getInstance().exists(templateName)) {
        throw new UnknownID("No such template: " + templateName);
    }

    Map<String, Set<String>> acceptedSeeds = new HashMap<String, Set<String>>();
    StringBuilder invalidMessage = new StringBuilder(
            "Unable to create an event harvest.\n" + "The following seeds are invalid:\n");
    boolean valid = true;

    // validate all the seeds in the file
    // those accepted are entered into the acceptedSeeds datastructure

    // Iterate through the contents of the file
    LineIterator seedIterator = null;
    try {
        seedIterator = new LineIterator(new FileReader(seedsFile));
        while (seedIterator.hasNext()) {
            String seed = seedIterator.next();
            boolean seedValid = processSeed(seed, invalidMessage, acceptedSeeds);
            if (!seedValid) {
                valid = false;
            }
        }
    } catch (IOException e) {
        throw new IOFailure("Unable to process seedsfile ", e);
    } finally {
        LineIterator.closeQuietly(seedIterator);
    }

    if (!valid) {
        throw new ArgumentNotValid(invalidMessage.toString());
    }

    addSeedsToDomain(templateName, maxBytes, maxObjects, acceptedSeeds, attributeValues);
}

From source file:egovframework.rte.fdl.filehandling.FilehandlingServiceTest.java

/**
 * @throws Exception//from   w  w  w  . ja v a2  s .c o m
 */
@Test
public void testLineIterator() throws Exception {

    String[] string = {
            "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"",
            "  xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">",
            "  <parent>", "     <groupId>egovframework.rte</groupId>",
            "     <artifactId>egovframework.rte.root</artifactId>", "     <version>1.0.0-SNAPSHOT</version>",
            "  </parent>", "  <modelVersion>4.0.0</modelVersion>", "  <groupId>egovframework.rte</groupId>",
            "  <artifactId>egovframework.rte.fdl.filehandling</artifactId>", "  <packaging>jar</packaging>",
            "  <version>1.0.0-SNAPSHOT</version>", "  <name>egovframework.rte.fdl.filehandling</name>",
            "  <url>http://maven.apache.org</url>", "  <dependencies>", "    <dependency>",
            "      <groupId>junit</groupId>", "      <artifactId>junit</artifactId>",
            "      <version>4.4</version>", "      <scope>test</scope>", "    </dependency>",
            "    <dependency>", "      <groupId>commons-vfs</groupId>",
            "      <artifactId>commons-vfs</artifactId>", "      <version>1.0</version>", "    </dependency>",
            "    <dependency>", "      <groupId>commons-io</groupId>",
            "      <artifactId>commons-io</artifactId>", "      <version>1.4</version>", "    </dependency>",
            "    <!-- egovframework.rte -->", "    <dependency>", "      <groupId>egovframework.rte</groupId>",
            "      <artifactId>egovframework.rte.fdl.string</artifactId>",
            "      <version>1.0.0-SNAPSHOT</version>", "    </dependency>", "  </dependencies>", "</project>" };

    try {
        File file = new File("pom.xml");

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

        try {
            log.debug("############################# LineIterator ###############################");

            for (int i = 0; it.hasNext(); i++) {
                String line = it.nextLine();
                log.info(line);

                assertEquals(string[i], line);
            }
        } finally {
            LineIterator.closeQuietly(it);
        }

    } catch (Exception e) {
        log.error(e.getCause());
    }
}

From source file:com.rodaxsoft.mailgun.message.tools.MailgunSender.java

/**
 * Sends message to the recipients specified by the <code>-R</code> option.
 * @param cmd Command line arguments/*w  w w.  j a v a2s .  co m*/
 * @param text Plain text email content
 * @param html HTML email content
 * @throws ContextedRuntimeException if the recipients option or -R is omitted.
 */
private static void sendMessageToRecipientsInFile(CommandLine cmd, String text, String html) {

    if (cmd.hasOption(RECIPIENTS_FILE_OPT)) {
        LineIterator it = null;
        try {
            it = FileUtils.lineIterator(new File(cmd.getOptionValue(RECIPIENTS_FILE_OPT)), "UTF-8");

            while (it.hasNext()) {
                final String to = it.nextLine();
                //Build the email request object
                final EmailRequest er = makeEmailRequest(cmd, text, html, to);
                LOG.trace(er);

                sendMessage(cmd, er);
            }

        } catch (IOException e) {
            LOG.error("Error occurre while sending from recipients file", e);

        } finally {
            LineIterator.closeQuietly(it);
        }
    } else {

        final String msg = "Option must be a recipients file";
        handleOmittedOptionError(cmd, msg);
    }
}

From source file:com.seniorproject.semanticweb.services.WebServices.java

public ArrayList<String> replaceWithPrefix(String filepath) throws IOException {
    File file = new File(filepath);
    LineIterator it = FileUtils.lineIterator(file, "UTF-8");
    ArrayList<String> results = new ArrayList<>();
    try {/*w w w . j  av  a  2 s  .c o  m*/
        while (it.hasNext()) {
            String content = it.nextLine();
            content = content.replace("^^<http://www.w3.org/2001/XMLSchema#int>", "");
            content = content.replace("<http://xmlns.com/foaf/0.1/page>\n", "");
            content = content.replace("<http://www.w3.org/2002/07/owl#sameAs>\n", "");
            content = content.replace("<http://www.w3.org/2000/01/rdf-schema#label>\n", "");
            content = content.replace("<http://dbpedia.org/property/hasPhotoCollection>\n", "");
            content = content.replace("<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>\n", "");
            content = content.replace("<http://www.w3.org/2002/07/owl#", "owl:");
            content = content.replace("<http://www.w3.org/2001/XMLSchema#", "xsd:");
            content = content.replace("<http://www.w3.org/2000/01/rdf-schema#", "rdfs:");
            content = content.replace("<http://www.w3.org/1999/02/22-rdf-syntax-ns#", "rdf:");
            content = content.replace("<http://xmlns.com/foaf/0.1/", "foaf:");
            content = content.replace("<http://data.linkedmdb.org/resource/oddlinker/", "oddlinker:");
            content = content.replace("<file:/C:/d2r-server-0.4/mapping.n3#", "map:");
            content = content.replace("<http://data.linkedmdb.org/resource/movie/", "movie:");
            content = content.replace("<http://data.linkedmdb.org/resource/", "db:");
            content = content.replace("<http://dbpedia.org/property/", "dbpedia:");
            content = content.replace("<http://www.w3.org/2004/02/skos/core#", "skos:");
            content = content.replace("<http://purl.org/dc/terms/", "dc:");
            content = content.replace(">", "");
            content = content.replace("<", "");
            results.add(content);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }
    return results;
}