Example usage for org.apache.commons.io FileUtils readLines

List of usage examples for org.apache.commons.io FileUtils readLines

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readLines.

Prototype

public static List readLines(File file, String encoding) throws IOException 

Source Link

Document

Reads the contents of a file line by line to a List of Strings.

Usage

From source file:it.user.SsoAuthenticationTest.java

@Test
public void fail_when_email_already_exists() throws Exception {
    USER_RULE.createUser("another", "Another", USER_EMAIL, "another");

    Response response = doCall(USER_LOGIN, USER_NAME, USER_EMAIL, null);

    String expectedError = "You can't sign up because email 'tester@email.com' is already used by an existing user. This means that you probably already registered with another account";
    assertThat(response.code()).isEqualTo(200);
    assertThat(response.request().url().toString()).contains(URLEncoder.encode(expectedError, UTF_8.name()));
    assertThat(FileUtils.readLines(orchestrator.getServer().getWebLogs(), UTF_8)).doesNotContain(expectedError);
}

From source file:es.ehu.si.ixa.pipe.parse.Annotate.java

public void parseForTesting(File inputText) throws IOException {
    StringBuffer parsingDoc = new StringBuffer();
    if (inputText.isFile()) {
        List<String> inputTrees = FileUtils.readLines(inputText, "UTF-8");
        for (String sentence : inputTrees) {
            Parse parsedSentence = parser.parse(sentence, 1)[0];
            parsedSentence.show(parsingDoc);
            parsingDoc.append("\n");
        }//from  w  ww  .  ja v a  2s  . co m
        File outfile = new File(FilenameUtils.removeExtension(inputText.getPath()) + ".test");
        System.err.println("Writing test parse file to " + outfile);
        FileUtils.writeStringToFile(outfile, parsingDoc.toString(), "UTF-8");
    } else {
        System.out.println("Choose a correct file!");
        System.exit(1);
    }
}

From source file:com.blackducksoftware.integration.hub.docker.HubDockerManager.java

public List<File> generateBdioFromImageFilesDir(final String dockerImageRepo, final String dockerImageTag,
        final List<ManifestLayerMapping> mappings, final String projectName, final String versionName,
        final File dockerTar, final File targetImageFileSystemRootDir, final OperatingSystemEnum osEnum)
        throws IOException, HubIntegrationException, InterruptedException {
    final ImageInfo imagePkgMgrInfo = tarParser.collectPkgMgrInfo(targetImageFileSystemRootDir, osEnum);
    if (imagePkgMgrInfo.getOperatingSystemEnum() == null) {
        throw new HubIntegrationException("Could not determine the Operating System of this Docker tar.");
    }/* w  ww .jav  a2  s .c o  m*/
    String architecture = null;
    if (osEnum == OperatingSystemEnum.ALPINE) { // TODO This code should be in a pkg-manager-specific class
        final List<File> etcDirectories = FileOperations.findFileWithName(targetImageFileSystemRootDir, "etc");
        for (final File etc : etcDirectories) {
            File architectureFile = new File(etc, "apk");
            architectureFile = new File(architectureFile, "arch");
            if (architectureFile.exists()) {
                architecture = FileUtils.readLines(architectureFile, "UTF-8").get(0);
                break;
            }
        }
    }
    logger.debug(String.format("generateBdioFromImageFilesDir(): architecture: %s", architecture));
    return generateBdioFromPackageMgrDirs(dockerImageRepo, dockerImageTag, mappings, projectName, versionName,
            dockerTar.getName(), imagePkgMgrInfo, architecture);
}

From source file:com.grossbart.forbiddenfunction.FFRunner.java

private void readForbiddenFuncts(ForbiddenFunction ff) throws IOException {
    for (String f : m_forbidden) {
        File file = new File(f);
        List<String> externs = FileUtils.readLines(file, m_charset);

        for (String extern : externs) {
            ff.addForbiddenFuncion(extern);
        }//from  www.ja  v a 2 s .  co  m
    }
}

From source file:de.meisl.eisstockitems.ImportTest.java

public void importFromFile(String fileName, long categoryId) throws ParseException, IOException {

    List<String> readLines = FileUtils.readLines(new File(fileName), "UTF-8");
    for (String line : readLines) {

        DateFormat format = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);

        String[] split = line.split(",", -1);
        String regNr = split[0];/* ww w  . ja  v  a 2  s .c o m*/
        String ifipartnerid = split[1];
        String producerName = split[2];
        Date registrationDate = format.parse(split[3]);
        Date prodCeasedDate = split[4].isEmpty() ? null : format.parse(split[4]);
        Date sellingProhibitedDate = split[5].isEmpty() ? null : format.parse(split[5]);
        Date expiredDate = split[6].isEmpty() ? null : format.parse(split[6]);
        Date sellingCeasedDate = split[7].isEmpty() ? null : format.parse(split[7]);
        String remark = split[8];

        // 1 Eisstockkrper
        // 2 Eisstockkrper fr Schler
        // 3 Stiele
        // 4 Winterlaufsohlen
        // 5 Grundplatten
        // 6 Sommerlaufsohlen mit glatter Laufflche
        // 7 Sommerlaufsohle - rot - Negativprofil (sehr schnel...
        // 8 Sommerlaufsohlen mit Negativprofil
        // 9 Zwischenplatten
        // 10 Runddauben

        Category category = categoryRepository.findOne(categoryId);
        Producer producer;
        Item item;

        List<Producer> findByIfiPartnerId = producerRepository.findByIfiPartnerIdAndName(ifipartnerid,
                producerName);

        int partnerListSize = findByIfiPartnerId.size();
        if (partnerListSize > 0) {
            if (partnerListSize > 1) {
                System.err.println("Many partners for IFI partner ID '" + ifipartnerid + "': "
                        + findByIfiPartnerId.toString());
            }

            producer = findByIfiPartnerId.get(0);

            log.info("Found Producer for ifiPartnerId '" + ifipartnerid + "': " + producer);
        } else {
            log.info("Did not find Producer for ifiPartnerId '" + ifipartnerid + "' and name '" + producerName
                    + "'");
            producer = new Producer();
            producer.setIfiPartnerId(ifipartnerid);
            producer.setName(producerName);
            producer.setUpdated(new Date());
            producer = producerRepository.save(producer);

            log.info("Created Producer for ifiPartnerId '" + ifipartnerid + "': " + producer);
        }

        List<Item> findByRegNumber = itemRepository.findByRegNumber(regNr);
        if (findByRegNumber.size() > 0) {
            if (findByRegNumber.size() > 1) {
                throw new RuntimeException("more than 1 item with regNr '" + regNr + "'");
            }
            item = findByRegNumber.get(0);

            log.info("Found Item for RegNr '" + regNr + "': " + item);
        } else {
            item = new Item();
            item.setCategory(category);
            item.setProducer(producer);
            item.setRegNumber(regNr);
            item.setRemark(remark);
            item.setRegistrationDate(registrationDate);
            item.setExpired(expiredDate);
            item.setProductionCeased(prodCeasedDate);
            item.setSellingCeased(sellingCeasedDate);
            item.setSellingProhibited(sellingProhibitedDate);
            item.setUpdated(new Date());
            item = itemRepository.save(item);

            log.info("Created Item for RegNr '" + regNr + "': " + item);
        }

    }
}

From source file:io.fabric8.vertx.maven.plugin.utils.ServiceCombinerUtil.java

private Map<String, Set<String>> findLocalSPI() {
    Map<String, Set<String>> map = new HashMap<>();
    if (classes == null || !classes.isDirectory()) {
        return map;
    }//  w  w  w  .ja  v a2s.  co m

    File spiRoot = new File(classes, "META-INF/services");
    if (!spiRoot.isDirectory()) {
        return map;
    }

    Collection<File> files = FileUtils.listFiles(spiRoot, null, false);
    for (File file : files) {
        try {
            map.put(file.getName(), new LinkedHashSet<>(FileUtils.readLines(file, "UTF-8")));
        } catch (IOException e) {
            throw new RuntimeException("Cannot read  " + file.getAbsolutePath(), e);
        }
    }
    return map;
}

From source file:com.anrisoftware.sscontrol.scripts.locale.ubuntu_12_04.Ubuntu_12_04_InstallLocale.java

private List<String> loadLocales(File file, Charset charset) throws ScriptException {
    try {/*from   www. jav a 2  s. com*/
        return FileUtils.readLines(file, charset);
    } catch (IOException e) {
        throw log.errorLoadLocales(this, e, file);
    }
}

From source file:net.nifheim.beelzebu.coins.common.utils.FileManager.java

private void updateMessages() {
    try {//from  w w  w  . jav  a  2 s .com
        List<String> lines = FileUtils.readLines(messagesFiles.get("default"), Charsets.UTF_8);
        int index;
        if (core.getMessages("").getInt("version") == 6) {
            index = lines.indexOf("version: 6");
            lines.set(index, "version: 7");
            index = lines.indexOf("Multipliers:");
            lines.remove(index);
            index = lines.indexOf("  Menu:");
            lines.add(index, "Multipliers:");
            core.log("Updated messages.yml file to v7");
        }
        if (core.getMessages("").getInt("version") == 7) {
            index = lines.indexOf("version: 7");
            lines.set(index, "version: 8");
            index = lines.indexOf("  Menu:") + 2;
            lines.addAll(index,
                    Arrays.asList("    Confirm:", "      Title: '&8Are you sure?'", "      Accept: '&aYES!'",
                            "      Decline: '&cNope'", "    Multipliers:",
                            "      Name: '&6Multiplier &cx%amount%'", "      Lore:", "      - ''",
                            "      - '&7Amount: &c%amount%'", "      - '&7Server: &c%server%'",
                            "      - '&7Minutes: &c%minutes%'", "      - ''", "      - '&7ID: &c#%id%'",
                            "    No Multipliers:", "      Name: '&cYou don''t have any multiplier :('",
                            "      Lore:", "      - ''", "      - '&7You can buy multipliers in our store'",
                            "      - '&6&nstore.servername.net'"));
            core.log("Updated messages.yml file to v8");
        }
        if (core.getMessages("").getInt("version") == 8) {
            index = lines.indexOf("version: 8");
            lines.set(index, "version: 9");
            lines.removeAll(Arrays.asList("# Coins messages file.",
                    "# If you need support or find a bug open a issuse in",
                    "# the official github repo https://github.com/Beelzebu/Coins/issuses/", "",
                    "# The version of this file, don't edit!"));
            lines.addAll(0,
                    Arrays.asList("# Coins messages file.",
                            "# If you need support or find a bug open a issuse in",
                            "# the official github repo https://github.com/Beelzebu/Coins/issuses/", "",
                            "# The version of this file, is used to auto update this file, don't change it",
                            "# unless you know what you do."));
            core.log("Updated messages.yml file to v9");
        }
        if (core.getMessages("").getInt("version") == 9) {
            index = lines.indexOf("version: 9");
            lines.set(index, "version: 10");
            index = lines.indexOf(
                    "  Multiplier Create: '" + core.getMessages("").getString("Help.Multiplier Create") + "'")
                    + 1;
            lines.add(index,
                    "  Multiplier Set: '%prefix% &cPlease use &f/coins multiplier set <amount> <enabler> <minutes> (server)'");
            lines.addAll(Arrays.asList("  Set:",
                    "  - '%prefix% A multiplier with the following data was set for %server%'",
                    "  - '  &7Enabler: &c%enabler%'", "  - '  &7Amount: &c%amount%'",
                    "  - '  &7Minutes: &c%minutes%'"));
            core.log("Updated messages.yml file to v10");
        }
        FileUtils.writeLines(messagesFiles.get("default"), lines);
    } catch (IOException ex) {
        core.log("An unexpected error occurred while updating the messages.yml file.");
        core.debug(ex.getMessage());
    }
    try {
        List<String> lines = FileUtils.readLines(messagesFiles.get("es"), Charsets.UTF_8);
        int index;
        if (core.getMessages("es").getInt("version") == 6) {
            index = lines.indexOf("version: 6");
            lines.set(index, "version: 7");
            index = lines.indexOf("Multipliers:");
            lines.remove(index);
            index = lines.indexOf("  Menu:");
            lines.add(index, "Multipliers:");
            core.log("Updated messages_es.yml file to v7");
        }
        if (core.getMessages("es").getInt("version") == 7) {
            index = lines.indexOf("version: 7");
            lines.set(index, "version: 8");
            index = lines.indexOf("  Menu:") + 2;
            lines.addAll(index, Arrays.asList("    Confirm:", "      Title: '&8Ests seguro?'",
                    "      Accept: '&aSI!'", "      Decline: '&cNo'", "    Multipliers:",
                    "      Name: '&6Multiplicador &cx%amount%'", "      Lore:", "      - ''",
                    "      - '&7Cantidad: &c%amount%'", "      - '&7Servidor: &c%server%'",
                    "      - '&7Minutos: &c%minutes%'", "      - ''", "      - '&7ID: &c#%id%'",
                    "    No Multipliers:", "      Name: '&cNo tienes ningn multiplicador :('", "      Lore:",
                    "      - ''", "      - '&7Puedes comprar multiplicadores en nuestra tienda'",
                    "      - '&6&nstore.servername.net'"));
            core.log("Updated messages_es.yml file to v8");
        }
        index = lines.indexOf("      - '&6&nstore.servername.net'\"");
        if (index != -1) {
            lines.set(index, "      - '&6&nstore.servername.net'");
        }
        if (core.getMessages("es").getInt("version") == 8) {
            index = lines.indexOf("version: 8");
            lines.set(index, "version: 9");
            lines.removeAll(Arrays.asList("# Coins messages file.",
                    "# If you need support or find a bug open a issuse in",
                    "# the official github repo https://github.com/Beelzebu/Coins/issuses/", "",
                    "# The version of this file, don't edit!"));
            lines.addAll(0, Arrays.asList("# Coins messages file.",
                    "# Si necesitas soporte o encuentras un error por favor abre un ticket en el",
                    "# repositorio oficial de github https://github.com/Beelzebu/Coins/issuses/", "",
                    "# La versin de este archivo, es usado para actualizarlo automticamente, no lo cambies",
                    "# a menos que sepas lo que haces."));
            core.log("Updated messages_es.yml file to v9");
        }
        if (core.getMessages("es").getInt("version") == 9) {
            index = lines.indexOf("version: 9");
            lines.set(index, "version: 10");
            index = lines.indexOf(
                    "  Multiplier Create: '" + core.getMessages("es").getString("Help.Multiplier Create") + "'")
                    + 1;
            lines.add(index,
                    "  Multiplier Set: '%prefix% &cPor favor usa &f/coins multiplier set <cantidad> <activador> <minutos> (server)'");
            lines.addAll(Arrays.asList("  Set:",
                    "  - '%prefix% Un multiplicador con la siguiente informacin fue establecido en %server%'",
                    "  - '  &7Activador: &c%enabler%'", "  - '  &7Cantidad: &c%amount%'",
                    "  - '  &7Minutos: &c%minutes%'"));
            core.log("Updated messages_es.yml file to v10");
        }
        if (lines.get(0).startsWith("  Multiplier Set:")) {
            lines.remove(0);
            index = lines.indexOf(
                    "  Multiplier Create: '" + core.getMessages("es").getString("Help.Multiplier Create") + "'")
                    + 1;
            lines.add(index,
                    "  Multiplier Set: '%prefix% &cPor favor usa &f/coins multiplier set <cantidad> <activador> <minutos> (server)'");
        }
        FileUtils.writeLines(messagesFiles.get("es"), lines);
    } catch (IOException ex) {
        core.log("An unexpected error occurred while updating the messages_es.yml file.");
        core.debug(ex.getMessage());
    }
}

From source file:es.ehu.si.ixa.pipe.parse.Annotate.java

/**
 * Takes a file containing Penn Treebank oneline annotation and annotates the
 * headwords, saving it to a file with the *.th extension. Optionally also
 * processes recursively an input directory adding heads only to the files
 * with the files with the specified extension
 * //from  ww  w  . j  a  v a2  s. c  o  m
 * @param dir
 *          the input file or directory
 * @param ext
 *          the extension to look for in the directory
 * @throws IOException
 */
public void processTreebankWithHeadWords(File dir, String ext) throws IOException {
    // process one file
    if (dir.isFile()) {
        List<String> inputTrees = FileUtils.readLines(new File(dir.getCanonicalPath()), "UTF-8");
        File outfile = new File(FilenameUtils.removeExtension(dir.getPath()) + ".th");
        String outTree = addHeadWordsToTreebank(inputTrees);
        FileUtils.writeStringToFile(outfile, outTree, "UTF-8");
        System.err.println(">> Wrote headWords to Penn Treebank to " + outfile);
    } else {
        // recursively process directories
        File listFile[] = dir.listFiles();
        if (listFile != null) {
            if (ext == null) {
                System.out.println(
                        "For recursive directory processing of treebank files specify the extension of the files containing the syntactic trees.");
                System.exit(1);
            }
            for (int i = 0; i < listFile.length; i++) {
                if (listFile[i].isDirectory()) {
                    processTreebankWithHeadWords(listFile[i], ext);
                } else {
                    try {
                        List<String> inputTrees = FileUtils.readLines(
                                new File(FilenameUtils.removeExtension(listFile[i].getCanonicalPath()) + ext),
                                "UTF-8");
                        File outfile = new File(FilenameUtils.removeExtension(listFile[i].getPath()) + ".th");
                        String outTree = addHeadWordsToTreebank(inputTrees);
                        FileUtils.writeStringToFile(outfile, outTree, "UTF-8");
                        System.err.println(">> Wrote headWords to " + outfile);
                    } catch (FileNotFoundException noFile) {
                        continue;
                    }
                }
            }
        }
    }
}

From source file:com.blackducksoftware.tools.commonframework.core.config.ConfigurationFile.java

public void init(final File file) {
    this.file = file;
    if (!file.exists()) {
        final String msg = "Configuration file: " + file.getAbsolutePath() + " does not exist";
        log.error(msg);/*ww  w  .  j  a  v  a  2 s  .c  om*/
        // A ConfigurationManager test depends on this message:
        throw new IllegalArgumentException("File DNE @: " + file.getName());
    }
    if (!file.canRead()) {
        final String msg = "Configuration file: " + file.getAbsolutePath() + " is not readable";
        log.error(msg);
        throw new IllegalArgumentException(msg);
    }
    props = new ConfigurationProperties();
    try {
        props.load(file);
    } catch (final Exception e) {
        final String msg = "Error loading properties from file: " + file.getAbsolutePath() + ": "
                + e.getMessage();
        log.error(msg);
        throw new IllegalArgumentException(msg);
    }

    try {
        lines = FileUtils.readLines(file, "UTF-8");
    } catch (final IOException e) {
        final String msg = "Error reading file: " + file.getAbsolutePath() + ": " + e.getMessage();
        log.error(msg);
        throw new IllegalArgumentException(msg);
    }
    configurationPasswords = loadConfigurationPasswords();
    inNeedOfUpdate = hasPasswordsNeedingEncryptionOrPropertyUpdate();

}