Example usage for java.nio.file Files readAllLines

List of usage examples for java.nio.file Files readAllLines

Introduction

In this page you can find the example usage for java.nio.file Files readAllLines.

Prototype

public static List<String> readAllLines(Path path) throws IOException 

Source Link

Document

Read all lines from a file.

Usage

From source file:com.ethercamp.harmony.service.wallet.FileSystemWalletStore.java

public List<WalletAddressItem> fromStore() {
    final ObjectMapper mapper = new ObjectMapper();

    try {/*from ww w  .  j  a  v  a2s.co m*/
        final File file = getKeyStoreLocation().resolve(FILE_NAME).toFile();

        final String content = Files.readAllLines(file.toPath()).stream().collect(Collectors.joining(""));

        return mapper.readValue(content, new TypeReference<List<WalletAddressItem>>() {
        });
    } catch (NoSuchFileException e) {
        return Collections.EMPTY_LIST;
    } catch (IOException e) {
        throw new RuntimeException("Problem loading data. Message: " + e.getMessage(), e);
    }
}

From source file:org.springframework.cloud.stream.app.plugin.utils.SpringCloudStreamPluginUtils.java

public static void addCopyRight(Path p) throws IOException {
    StringBuilder sb = new StringBuilder();
    sb.append(COPY_RIGHT_STRING);/* w w  w . jav a2s  .c  o  m*/
    Files.readAllLines(p).forEach(l -> {
        sb.append(l);
        sb.append("\n");
    });
    Files.write(p, sb.toString().getBytes());
}

From source file:io.pivio.dependencies.SbtDependencyReader.java

private List<String> getLinesOfFile(File file) {
    List<String> strings;
    try {/*from  ww w  .  j av a  2  s . c  om*/
        strings = Files.readAllLines(file.toPath());
    } catch (IOException e) {
        return new ArrayList<>();
    }
    return strings;
}

From source file:System.ConsoleHelper.java

@Override
public List<String> getClientFile(String fileName) {
    List<String> result = null;
    try {/* w w w  .  j  a  va  2  s. c  om*/
        result = Files.readAllLines(Paths.get(clientID + "/" + fileName));
    } catch (IOException ex) {
        System.err.println("ConsoleHelper : Error retrieving client's file " + ex.getMessage());
    }
    return result;
}

From source file:com.thoughtworks.go.helper.SvnRemoteRepository.java

public void addUser(String username, String password) throws Exception {
    enableAuthentication();/*from   w  ww  .  j  a va 2  s  .c  om*/
    File passwdFile = new File(repo.projectRepositoryRoot(), "conf/passwd");
    String passwd = String.join(FileUtil.lineSeparator(), Files.readAllLines(passwdFile.toPath()));
    if (!(passwd.contains("\n[users]\n"))) {
        passwd = passwd + "\n[users]\n";
    }
    passwd = passwd + String.format("\n%s = %s\n", username, password);
    FileUtils.writeStringToFile(passwdFile, passwd, UTF_8);
}

From source file:org.zanata.magpie.backend.google.GoogleCredential.java

private static boolean isValidGoogleCredentialFile(@Nonnull File googleADCFile) {
    ObjectMapper objectMapper = new ObjectMapper();
    try {//  w w  w.j ava  2s .c  o m
        List<String> lines = Files.readAllLines(googleADCFile.toPath());
        if (lines.isEmpty()) {
            return false;
        }
        GoogleCredentialBasic value = objectMapper.readerFor(GoogleCredentialBasic.class)
                .readValue(googleADCFile);
        return value.isValid();
    } catch (Exception e) {
        log.error("unable to read Google Application Default Credentials file", e);
        return false;
    }
}

From source file:org.opencb.opencga.app.cli.analysis.VariantQueryCommandUtils.java

public static Query parseQuery(AnalysisCliOptionsParser.QueryVariantCommandOptions queryVariantsOptions,
        Map<Long, String> studyIds) throws Exception {
    Query query = new Query();

    /*/*w w w. j  ava 2 s  . c  o  m*/
     * Parse Variant parameters
     */
    if (queryVariantsOptions.region != null && !queryVariantsOptions.region.isEmpty()) {
        query.put(REGION.key(), queryVariantsOptions.region);
    } else if (queryVariantsOptions.regionFile != null && !queryVariantsOptions.regionFile.isEmpty()) {
        Path gffPath = Paths.get(queryVariantsOptions.regionFile);
        FileUtils.checkFile(gffPath);
        String regionsFromFile = Files.readAllLines(gffPath).stream().map(line -> {
            String[] array = line.split("\t");
            return new String(array[0].replace("chr", "") + ":" + array[3] + "-" + array[4]);
        }).collect(Collectors.joining(","));
        query.put(REGION.key(), regionsFromFile);
    }

    addParam(query, ID, queryVariantsOptions.id);
    addParam(query, GENE, queryVariantsOptions.gene);
    addParam(query, TYPE, queryVariantsOptions.type);

    List studies = new LinkedList<>();
    if (StringUtils.isNotEmpty(queryVariantsOptions.study)) {
        query.put(STUDIES.key(), queryVariantsOptions.study);
        for (String study : queryVariantsOptions.study.split(",|;")) {
            if (!study.startsWith("!")) {
                studies.add(study);
            }
        }
    } else {
        studies = new ArrayList<>(studyIds.keySet());
    }

    // If the studies to be returned is empty then we return the studies being queried
    if (StringUtils.isNotEmpty(queryVariantsOptions.returnStudy)) {
        //            query.put(RETURNED_STUDIES.key(), Arrays.asList(queryVariantsOptions.returnStudy.split(",")));
        List<String> list = new ArrayList<>();
        Collections.addAll(list, queryVariantsOptions.returnStudy.split(","));
        query.put(RETURNED_STUDIES.key(), list);
    } else {
        if (!studies.isEmpty()) {
            query.put(RETURNED_STUDIES.key(), studies);
        }
    }

    addParam(query, FILES, queryVariantsOptions.file);
    addParam(query, GENOTYPE, queryVariantsOptions.sampleGenotype);
    if (queryVariantsOptions.returnSample != null) {
        if (queryVariantsOptions.returnSample.isEmpty() || queryVariantsOptions.returnSample.equals(".")) {
            query.put(RETURNED_SAMPLES.key(), Collections.emptyList());
        } else {
            query.put(RETURNED_SAMPLES.key(), queryVariantsOptions.returnSample);
        }
    }
    addParam(query, UNKNOWN_GENOTYPE, queryVariantsOptions.unknownGenotype);

    /**
     * Annotation parameters
     */
    addParam(query, ANNOT_CONSEQUENCE_TYPE, queryVariantsOptions.consequenceType);
    addParam(query, ANNOT_BIOTYPE, queryVariantsOptions.biotype);
    addParam(query, ANNOT_POPULATION_ALTERNATE_FREQUENCY, queryVariantsOptions.populationFreqs);
    addParam(query, ANNOT_POPULATION_MINOR_ALLELE_FREQUENCY, queryVariantsOptions.populationMaf);
    addParam(query, ANNOT_CONSERVATION, queryVariantsOptions.conservation);
    addParam(query, ANNOT_TRANSCRIPTION_FLAGS, queryVariantsOptions.flags);
    addParam(query, ANNOT_GENE_TRAITS_ID, queryVariantsOptions.geneTraitId);
    addParam(query, ANNOT_GENE_TRAITS_NAME, queryVariantsOptions.geneTraitName);
    addParam(query, ANNOT_HPO, queryVariantsOptions.hpo);
    addParam(query, ANNOT_GO, queryVariantsOptions.go);
    addParam(query, ANNOT_EXPRESSION, queryVariantsOptions.expression);
    addParam(query, ANNOT_PROTEIN_KEYWORDS, queryVariantsOptions.proteinKeywords);
    addParam(query, ANNOT_DRUG, queryVariantsOptions.drugs);

    if (StringUtils.isNoneEmpty(queryVariantsOptions.proteinSubstitution)) {
        query.put(ANNOT_PROTEIN_SUBSTITUTION.key(), queryVariantsOptions.proteinSubstitution);
    }

    /*
     * Stats parameters
     */
    if (queryVariantsOptions.stats != null && !queryVariantsOptions.stats.isEmpty()) {
        Set<String> acceptedStatKeys = new HashSet<>(Arrays.asList(STATS_MAF.key(), STATS_MGF.key(),
                MISSING_ALLELES.key(), MISSING_GENOTYPES.key()));

        for (String stat : queryVariantsOptions.stats.split(",")) {
            int index = stat.indexOf("<");
            index = index >= 0 ? index : stat.indexOf("!");
            index = index >= 0 ? index : stat.indexOf("~");
            index = index >= 0 ? index : stat.indexOf("<");
            index = index >= 0 ? index : stat.indexOf(">");
            index = index >= 0 ? index : stat.indexOf("=");
            if (index < 0) {
                throw new UnsupportedOperationException("Unknown stat filter operation: " + stat);
            }
            String name = stat.substring(0, index);
            String cond = stat.substring(index);

            if (acceptedStatKeys.contains(name)) {
                query.put(name, cond);
            } else {
                throw new UnsupportedOperationException("Unknown stat filter name: " + name);
            }
            logger.info("Parsed stat filter: {} {}", name, cond);
        }
    }

    addParam(query, STATS_MAF, queryVariantsOptions.maf);
    addParam(query, STATS_MGF, queryVariantsOptions.mgf);
    addParam(query, MISSING_ALLELES, queryVariantsOptions.missingAlleleCount);
    addParam(query, MISSING_GENOTYPES, queryVariantsOptions.missingGenotypeCount);

    boolean returnVariants = !queryVariantsOptions.count && StringUtils.isEmpty(queryVariantsOptions.groupBy)
            && StringUtils.isEmpty(queryVariantsOptions.rank);

    VariantOutputFormat of = VCF;
    if (StringUtils.isNotEmpty(queryVariantsOptions.outputFormat)) {
        of = VariantOutputFormat.safeValueOf(queryVariantsOptions.outputFormat);
        if (of == null) {
            throw variantFormatNotSupported(queryVariantsOptions.outputFormat);
        }
    }

    if (returnVariants && !of.isMultiStudyOutput()) {
        int returnedStudiesSize = query.getAsStringList(RETURNED_STUDIES.key()).size();
        if (returnedStudiesSize == 0 && studies.size() == 1) {
            query.put(RETURNED_STUDIES.key(), studies.get(0));
        } else if (returnedStudiesSize == 0 && studyIds.size() != 1 //If there are no returned studies, and there are more than one study
                || returnedStudiesSize > 1) { // Or is required more than one returned study
            throw new Exception("Only one study is allowed when returning " + of
                    + ", please use '--return-study' to select the returned " + "study. Available studies: "
                    + studyIds);
        } else {
            if (returnedStudiesSize == 0) { //If there were no returned studies, set the study existing one
                query.put(RETURNED_STUDIES.key(), studyIds.get(0));
            }
        }
    }

    return query;
}

From source file:JDBCExecutor.java

public void executeSQLFile(File sqlFile) {
    Preconditions.checkArgument(sqlFile.exists() && sqlFile.isFile(), "Please provide valid file.." + sqlFile);
    try {/*from  w ww . j  a v a  2  s.  c  om*/
        List<String> sqlLines = Files.readAllLines(sqlFile.toPath());
        for (String sql : sqlLines) {
            sql = sql.trim();
            if (sql.endsWith(";")) {
                sql = sql.substring(0, sql.lastIndexOf(";"));
            }
            if (!sql.isEmpty()) {
                executeStatement(sql);
                System.out.println();
            }
        }
    } catch (IOException e) {
        LOG("Error in processing file " + sqlFile, e);
    }
}

From source file:org.opencb.opencga.app.cli.analysis.executors.VariantQueryCommandUtils.java

@Deprecated
public static Query oldParseQuery(VariantCommandOptions.VariantQueryCommandOptions queryVariantsOptions,
        Map<Long, String> studyIds) throws Exception {
    Query query = new Query();

    /*//from   ww  w  .j a v  a 2  s.c  o  m
     * Parse Variant parameters
     */
    if (queryVariantsOptions.genericVariantQueryOptions.region != null
            && !queryVariantsOptions.genericVariantQueryOptions.region.isEmpty()) {
        query.put(REGION.key(), queryVariantsOptions.genericVariantQueryOptions.region);
    } else if (queryVariantsOptions.genericVariantQueryOptions.regionFile != null
            && !queryVariantsOptions.genericVariantQueryOptions.regionFile.isEmpty()) {
        Path gffPath = Paths.get(queryVariantsOptions.genericVariantQueryOptions.regionFile);
        FileUtils.checkFile(gffPath);
        String regionsFromFile = Files.readAllLines(gffPath).stream().map(line -> {
            String[] array = line.split("\t");
            return new String(array[0].replace("chr", "") + ":" + array[3] + "-" + array[4]);
        }).collect(Collectors.joining(","));
        query.put(REGION.key(), regionsFromFile);
    }

    addParam(query, ID, queryVariantsOptions.genericVariantQueryOptions.id);
    addParam(query, GENE, queryVariantsOptions.genericVariantQueryOptions.gene);
    addParam(query, TYPE, queryVariantsOptions.genericVariantQueryOptions.type);

    List studies = new LinkedList<>();
    if (StringUtils.isNotEmpty(queryVariantsOptions.study)) {
        query.put(STUDIES.key(), queryVariantsOptions.study);
        for (String study : queryVariantsOptions.study.split(",|;")) {
            if (!study.startsWith("!")) {
                studies.add(study);
            }
        }
    } else {
        studies = new ArrayList<>(studyIds.keySet());
    }

    // If the studies to be returned is empty then we return the studies being queried
    if (StringUtils.isNotEmpty(queryVariantsOptions.genericVariantQueryOptions.returnStudy)) {
        //            query.put(RETURNED_STUDIES.key(), Arrays.asList(queryVariantCommandOptions.returnStudy.split(",")));
        List<String> list = new ArrayList<>();
        Collections.addAll(list, queryVariantsOptions.genericVariantQueryOptions.returnStudy.split(","));
        query.put(RETURNED_STUDIES.key(), list);
    } else {
        if (!studies.isEmpty()) {
            query.put(RETURNED_STUDIES.key(), studies);
        }
    }

    addParam(query, FILES, queryVariantsOptions.genericVariantQueryOptions.file);
    addParam(query, RETURNED_FILES, queryVariantsOptions.genericVariantQueryOptions.returnFile);
    addParam(query, FILTER, queryVariantsOptions.genericVariantQueryOptions.filter);
    addParam(query, GENOTYPE, queryVariantsOptions.genericVariantQueryOptions.sampleGenotype);
    addParam(query, SAMPLES, queryVariantsOptions.genericVariantQueryOptions.samples);
    addParam(query, VariantCatalogQueryUtils.SAMPLE_FILTER, queryVariantsOptions.sampleFilter);
    if (queryVariantsOptions.genericVariantQueryOptions.returnSample != null) {
        if (queryVariantsOptions.genericVariantQueryOptions.returnSample.isEmpty()
                || queryVariantsOptions.genericVariantQueryOptions.returnSample.equals(".")) {
            query.put(RETURNED_SAMPLES.key(), Collections.emptyList());
        } else {
            query.put(RETURNED_SAMPLES.key(), queryVariantsOptions.genericVariantQueryOptions.returnSample);
        }
    }
    addParam(query, UNKNOWN_GENOTYPE, queryVariantsOptions.genericVariantQueryOptions.unknownGenotype);

    /**
     * Annotation parameters
     */
    addParam(query, ANNOT_CONSEQUENCE_TYPE, queryVariantsOptions.genericVariantQueryOptions.consequenceType);
    addParam(query, ANNOT_BIOTYPE, queryVariantsOptions.genericVariantQueryOptions.geneBiotype);
    addParam(query, ANNOT_POPULATION_ALTERNATE_FREQUENCY,
            queryVariantsOptions.genericVariantQueryOptions.populationFreqs);
    addParam(query, ANNOT_POPULATION_MINOR_ALLELE_FREQUENCY,
            queryVariantsOptions.genericVariantQueryOptions.populationMaf);
    addParam(query, ANNOT_CONSERVATION, queryVariantsOptions.genericVariantQueryOptions.conservation);
    addParam(query, ANNOT_TRANSCRIPTION_FLAGS, queryVariantsOptions.genericVariantQueryOptions.flags);
    addParam(query, ANNOT_GENE_TRAITS_ID, queryVariantsOptions.genericVariantQueryOptions.geneTraitId);
    addParam(query, ANNOT_GENE_TRAITS_NAME, queryVariantsOptions.genericVariantQueryOptions.geneTraitName);
    addParam(query, ANNOT_HPO, queryVariantsOptions.genericVariantQueryOptions.hpo);
    addParam(query, ANNOT_GO, queryVariantsOptions.genericVariantQueryOptions.go);
    //        addParam(query, ANNOT_EXPRESSION, queryVariantsOptions.genericVariantQueryOptions.expression);
    addParam(query, ANNOT_PROTEIN_KEYWORDS, queryVariantsOptions.genericVariantQueryOptions.proteinKeywords);
    addParam(query, ANNOT_DRUG, queryVariantsOptions.genericVariantQueryOptions.drugs);

    if (StringUtils.isNoneEmpty(queryVariantsOptions.genericVariantQueryOptions.proteinSubstitution)) {
        query.put(ANNOT_PROTEIN_SUBSTITUTION.key(),
                queryVariantsOptions.genericVariantQueryOptions.proteinSubstitution);
    }

    /*
     * Stats parameters
     */
    if (queryVariantsOptions.genericVariantQueryOptions.stats != null
            && !queryVariantsOptions.genericVariantQueryOptions.stats.isEmpty()) {
        Set<String> acceptedStatKeys = new HashSet<>(Arrays.asList(STATS_MAF.key(), STATS_MGF.key(),
                MISSING_ALLELES.key(), MISSING_GENOTYPES.key()));

        for (String stat : queryVariantsOptions.genericVariantQueryOptions.stats.split(",")) {
            int index = stat.indexOf("<");
            index = index >= 0 ? index : stat.indexOf("!");
            index = index >= 0 ? index : stat.indexOf("~");
            index = index >= 0 ? index : stat.indexOf("<");
            index = index >= 0 ? index : stat.indexOf(">");
            index = index >= 0 ? index : stat.indexOf("=");
            if (index < 0) {
                throw new UnsupportedOperationException("Unknown stat filter operation: " + stat);
            }
            String name = stat.substring(0, index);
            String cond = stat.substring(index);

            if (acceptedStatKeys.contains(name)) {
                query.put(name, cond);
            } else {
                throw new UnsupportedOperationException("Unknown stat filter name: " + name);
            }
            logger.info("Parsed stat filter: {} {}", name, cond);
        }
    }

    addParam(query, STATS_MAF, queryVariantsOptions.genericVariantQueryOptions.maf);
    addParam(query, STATS_MGF, queryVariantsOptions.genericVariantQueryOptions.mgf);
    addParam(query, MISSING_ALLELES, queryVariantsOptions.genericVariantQueryOptions.missingAlleleCount);
    addParam(query, MISSING_GENOTYPES, queryVariantsOptions.genericVariantQueryOptions.missingGenotypeCount);

    boolean returnVariants = !queryVariantsOptions.numericOptions.count
            && StringUtils.isEmpty(queryVariantsOptions.genericVariantQueryOptions.groupBy)
            && StringUtils.isEmpty(queryVariantsOptions.genericVariantQueryOptions.rank);

    VariantOutputFormat of = VCF;
    if (StringUtils.isNotEmpty(queryVariantsOptions.commonOptions.outputFormat)) {
        of = VariantWriterFactory.toOutputFormat(queryVariantsOptions.commonOptions.outputFormat, null);
        if (of == null) {
            throw variantFormatNotSupported(queryVariantsOptions.commonOptions.outputFormat);
        }
    }

    if (returnVariants && !of.isMultiStudyOutput()) {
        int returnedStudiesSize = query.getAsStringList(RETURNED_STUDIES.key()).size();
        if (returnedStudiesSize == 0 && studies.size() == 1) {
            query.put(RETURNED_STUDIES.key(), studies.get(0));
        } else if (returnedStudiesSize == 0 && studyIds.size() != 1 //If there are no returned studies, and there are more than one study
                || returnedStudiesSize > 1) { // Or is required more than one returned study
            throw new Exception("Only one study is allowed when returning " + of
                    + ", please use '--return-study' to select the returned " + "study. Available studies: "
                    + studyIds);
        } else {
            if (returnedStudiesSize == 0) { //If there were no returned studies, set the study existing one
                query.put(RETURNED_STUDIES.key(), studyIds.get(0));
            }
        }
    }

    return query;
}