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:ostepu.cconfig.control.java

/**
 * ruft die existierende Konfiguration ab und gibt sie aus
 *
 * @param context  der Kontext des Servlet
 * @param request  die eingehende Anfrage
 * @param response das Antwortobjekt//from  w  w w .  ja  va 2  s  . c om
 */
public static void getControl(ServletContext context, HttpServletRequest request,
        HttpServletResponse response) {
    PrintWriter out;
    try {
        out = response.getWriter();
    } catch (IOException ex) {
        Logger.getLogger(control.class.getName()).log(Level.SEVERE, null, ex);
        response.setStatus(500);
        return;
    }
    Path cconfigPath = Paths.get(context.getRealPath("/data/CConfig.json"));

    try {
        if (Files.exists(cconfigPath)) {
            List<String> content = Files.readAllLines(cconfigPath);
            JsonElement obj = new JsonParser().parse(String.join("", content));
            JsonObject newObject = obj.getAsJsonObject();

            if (newObject.has("prefix")) {
                newObject.remove("prefix");
                newObject.add("prefix",
                        (JsonElement) new JsonPrimitive(context.getAttribute("prefix").toString()));
            } else {
                newObject.add("prefix",
                        (JsonElement) new JsonPrimitive(context.getAttribute("prefix").toString()));
            }
            out.print(newObject.toString());
            response.setStatus(200);
        } else {
            response.setStatus(404);
            out.print("[]");
        }
    } catch (IOException ex) {
        Logger.getLogger(control.class.getName()).log(Level.SEVERE, null, ex);
        response.setStatus(500);
    } finally {
        out.close();
    }
}

From source file:org.moe.cli.manager.ExecutorManager.java

public static IExecutor getExecutorByParams(CommandLine request)
        throws IOException, InterruptedException, WrapNatJGenException {

    if (request.hasOption(OptionsHandler.HELP.getLongOpt())) {
        OptionsHandler.printHelp();/*from   w ww.  ja v a  2s  .c  o m*/
        return null;
    }

    String packageName = request.hasOption(OptionsHandler.PACKAGE_NAME.getLongOpt())
            ? request.getOptionValue(OptionsHandler.PACKAGE_NAME.getLongOpt())
            : "org.moe";

    String[] javaSource = request.getOptionValues(OptionsHandler.JAVA_SOURCE.getLongOpt());
    String[] bundle = request.getOptionValues(OptionsHandler.BUNDLE.getLongOpt());
    String ldFlags = null;
    if (request.hasOption(OptionsHandler.LD_FLAGS.getLongOpt())) {
        String ldFlagsPath = request.getOptionValue(OptionsHandler.LD_FLAGS.getLongOpt());
        File ldFlagsFile = new File(ldFlagsPath);
        if (ldFlagsFile.exists()) {
            List<String> lines = Files.readAllLines(ldFlagsFile.toPath());
            StringBuilder strbldr = new StringBuilder();
            for (String line : lines) {
                strbldr.append(line);
                strbldr.append(";");
            }
            ldFlags = strbldr.toString();
            if (ldFlags.startsWith(" "))
                ldFlags = ldFlags.substring(1);
        }
    }

    IExecutor executor = null;
    if (request.hasOption(OptionsHandler.FRAMEWORK.getLongOpt())) {
        String[] frameworks = request.getOptionValues(OptionsHandler.FRAMEWORK.getLongOpt());
        String[] headers = request.getOptionValues(OptionsHandler.HEADERS.getLongOpt());

        if (headers == null) {
            File frameworkFile = null;
            Set<String> headersContent = new HashSet<String>();
            Set<String> frameworkNameSet = new HashSet<String>();

            for (String framework : frameworks) {
                if ((framework == null) || framework.isEmpty()) {
                    continue;
                }
                frameworkFile = new File(framework);

                if (!frameworkNameSet.contains(frameworkFile.getName())) {
                    File headersFolder = new File(frameworkFile, "Headers");
                    if (headersFolder.exists()) {
                        headersContent.add(headersFolder.getPath());
                    } else {
                        System.err.println(String.format("Specify correct path in %s parameter",
                                OptionsHandler.FRAMEWORK.getLongOpt()));
                        return null; // TODO: Error throwing
                    }
                }

                frameworkNameSet.add(frameworkFile.getName());
            }

            headers = headersContent.toArray(new String[0]);
        }

        String outFile = request.getOptionValue(OptionsHandler.OUTPUT_FILE_PATH.getLongOpt());
        if (outFile == null || !outFile.endsWith(".jar")) {
            System.err.println(String.format("Specify jar file in %s parameter",
                    OptionsHandler.OUTPUT_FILE_PATH.getLongOpt()));
            return null; // TODO: Error throwing
        }

        executor = new ThirdPartyFrameworkLinkExecutor(packageName, frameworks, javaSource, headers, bundle,
                outFile, ldFlags);
    } else if (request.hasOption(OptionsHandler.LIBRARY.getLongOpt())) {
        String[] library = request.getOptionValues(OptionsHandler.LIBRARY.getLongOpt());
        String[] headers = request.getOptionValues(OptionsHandler.HEADERS.getLongOpt());

        if (headers == null) {
            System.err.println(
                    String.format("Specify headers in %s parameter", OptionsHandler.HEADERS.getLongOpt()));
            return null; // TODO: Error throwing
        }

        String outFile = request.getOptionValue(OptionsHandler.OUTPUT_FILE_PATH.getLongOpt());
        if (outFile == null || !outFile.endsWith(".jar")) {
            System.err.println(String.format("Specify jar file in %s parameter",
                    OptionsHandler.OUTPUT_FILE_PATH.getLongOpt()));
            return null; // TODO: Error throwing
        }

        executor = new ThirdPartyLibraryLinkExecutor(packageName, library, javaSource, headers, bundle, outFile,
                ldFlags);
    } else if (request.hasOption(OptionsHandler.POD.getLongOpt())) {

        String pod = request.getOptionValue(OptionsHandler.POD.getLongOpt());
        String outFile = request.getOptionValue(OptionsHandler.OUTPUT_FILE_PATH.getLongOpt());
        if (outFile == null || !outFile.endsWith(".jar")) {
            System.err.println(String.format("Specify jar file in %s parameter",
                    OptionsHandler.OUTPUT_FILE_PATH.getLongOpt()));
            return null; // TODO: Error throwing
        }
        String jpodSpecRepo = request.getOptionValue(OptionsHandler.JPOD_SPEC_REPO.getLongOpt());

        executor = new CocoaPodsExecutor(pod, outFile, javaSource, jpodSpecRepo, packageName,
                Collections.emptySet());
    } else if (request.hasOption(OptionsHandler.ALL_DEPENDENCIES.getLongOpt())) {
        String pod = request.getOptionValue(OptionsHandler.ALL_DEPENDENCIES.getLongOpt());
        Utils.printDependencies(pod, new HashSet<String>());
    } else {

        String pathToProject = request.getOptionValue(OptionsHandler.PATH_TO_PROJECT.getLongOpt());
        String headers = request.getOptionValue(OptionsHandler.HEADERS.getLongOpt());

        if (pathToProject == null) {
            System.err.println(String.format("Specify correct path in %s parameter",
                    OptionsHandler.PATH_TO_PROJECT.getLongOpt()));
            return null; // TODO: Error throwing
        }

        if (headers == null) {
            System.err.println(String.format("Specify jar correct path in %s parameter",
                    OptionsHandler.HEADERS.getLongOpt()));
            return null; // TODO: Error throwing
        }

        executor = new GenerateBindingExecutor(pathToProject, packageName, headers,
                request.hasOption(OptionsHandler.CREATE_FROM_PROTOTYPE.getLongOpt()));

    }

    return executor;
}

From source file:com.edmunds.etm.tools.urltoken.util.OptionUtils.java

@SuppressWarnings("unchecked")
public static List<String> parseValues(OptionSet options, OptionSpec<File> fileSpec) throws IOException {

    List<String> values;
    File file = options.valueOf(fileSpec);
    if (file != null) {
        values = Files.readAllLines(file.toPath());
    } else {// ww  w  .  java2 s. co m
        values = Lists.newArrayList();
    }

    return values;
}

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

public static Query parseBasicVariantQuery(StorageVariantCommandOptions.BasicVariantQueryOptions options,
        Query query) throws Exception {

    /*/*from  ww  w. j av a  2s.  com*/
     * Parse Variant parameters
     */
    if (options.region != null && !options.region.isEmpty()) {
        query.put(REGION.key(), options.region);
    } else if (options.regionFile != null && !options.regionFile.isEmpty()) {
        Path gffPath = Paths.get(options.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, options.id);
    addParam(query, GENE, options.gene);
    addParam(query, TYPE, options.type);

    /**
     * Annotation parameters
     */
    addParam(query, ANNOT_CONSEQUENCE_TYPE, options.consequenceType);
    addParam(query, ANNOT_POPULATION_ALTERNATE_FREQUENCY, options.populationFreqs);
    addParam(query, ANNOT_CONSERVATION, options.conservation);
    addParam(query, ANNOT_FUNCTIONAL_SCORE, options.functionalScore);
    addParam(query, ANNOT_PROTEIN_SUBSTITUTION, options.proteinSubstitution);

    /*
     * Stats parameters
     */
    //        if (options.stats != null && !options.stats.isEmpty()) {
    //            Set<String> acceptedStatKeys = new HashSet<>(Arrays.asList(STATS_MAF.key(),
    //                    STATS_MGF.key(),
    //                    MISSING_ALLELES.key(),
    //                    MISSING_GENOTYPES.key()));
    //
    //            for (String stat : options.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, options.maf);

    return query;
}

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

public static Query parseQuery(CliOptionsParser.QueryVariantsCommandOptions queryVariantsOptions,
        List<String> studyNames) throws Exception {
    Query query = new Query();

    /*/*from  www . j  av  a2  s.  com*/
     * 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<String> studies = new LinkedList<>();
    if (queryVariantsOptions.study != null && !queryVariantsOptions.study.isEmpty()) {
        query.put(STUDIES.key(), queryVariantsOptions.study);
        for (String study : queryVariantsOptions.study.split(",|;")) {
            if (!study.startsWith("!")) {
                studies.add(study);
            }
        }
    }

    // If the studies to be returned is empty then we return the studies being queried
    if (queryVariantsOptions.returnStudy != null && !queryVariantsOptions.returnStudy.isEmpty()) {
        //            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);
    addParam(query, RETURNED_SAMPLES, 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);

    if (queryVariantsOptions.proteinSubstitution != null
            && !queryVariantsOptions.proteinSubstitution.isEmpty()) {
        String[] fields = queryVariantsOptions.proteinSubstitution.split(",");
        for (String field : fields) {
            String[] arr = field.replaceAll("==", " ").replaceAll(">=", " ").replaceAll("<=", " ")
                    .replaceAll("=", " ").replaceAll("<", " ").replaceAll(">", " ").split(" ");

            if (arr != null && arr.length > 1) {
                switch (arr[0]) {
                case "sift":
                    query.put(ANNOT_SIFT.key(), field.replaceAll("sift", ""));
                    break;
                case "polyphen":
                    query.put(ANNOT_POLYPHEN.key(), field.replaceAll("polyphen", ""));
                    break;
                default:
                    query.put(ANNOT_PROTEIN_SUBSTITUTION.key(), field.replaceAll(arr[0], ""));
                    break;
                }
            }
        }
    }

    /*
     * 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);

    String outputFormat = "vcf";
    if (StringUtils.isNotEmpty(queryVariantsOptions.outputFormat)) {
        if (queryVariantsOptions.outputFormat.equals("json")
                || queryVariantsOptions.outputFormat.equals("json.gz")) {
            outputFormat = "json";
        }
    }

    if (returnVariants && outputFormat.equalsIgnoreCase("vcf")) {
        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 && studyNames.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 VCF, please use '--return-study' to select the returned "
                            + "study. Available studies: [ " + String.join(", ", studyNames) + " ]");
        } else {
            if (returnedStudiesSize == 0) { //If there were no returned studies, set the study existing one
                query.put(RETURNED_STUDIES.key(), studyNames.get(0));
            }
        }
    }

    return query;
}

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

public static void ignoreUnitTestGeneratedByInitializer(String generatedAppHome) throws IOException {
    Collection<File> files = FileUtils.listFiles(new File(generatedAppHome, "src/test/java"), null, true);
    Optional<File> first = files.stream().filter(f -> f.getName().endsWith("ApplicationTests.java"))
            .findFirst();//w ww.ja  v  a2s  .com

    if (first.isPresent()) {
        StringBuilder sb = new StringBuilder();
        File f1 = first.get();
        Files.readAllLines(f1.toPath()).forEach(l -> {
            if (l.startsWith("import") && !sb.toString().contains("import org.junit.Ignore")) {
                sb.append("import org.junit.Ignore;\n");
            } else if (l.startsWith("@RunWith") && !sb.toString().contains("@Ignore")) {
                sb.append("@Ignore\n");
            }
            sb.append(l);
            sb.append("\n");
        });
        Files.write(f1.toPath(), sb.toString().getBytes());
    }
}

From source file:org.omegat.MainTest.java

public static void testConsoleTranslate() throws Exception {
    // Create project properties
    ProjectProperties props = new ProjectProperties(tmpDir.toFile());
    // Create project internal directories
    props.autocreateDirectories();// w w w .j  av a2 s.c  o  m
    // Create version-controlled glossary file
    props.getWritableGlossaryFile().getAsFile().createNewFile();
    ProjectFileStorage.writeProjectFile(props);

    String fileName = "foo.txt";
    List<String> fileContent = Arrays.asList("Foo");

    Path srcFile = tmpDir.resolve(OConsts.DEFAULT_SOURCE).resolve(fileName);
    Files.write(srcFile, fileContent);

    Main.main(new String[] { "--mode=console-translate", tmpDir.toString() });

    Path trgFile = tmpDir.resolve(OConsts.DEFAULT_TARGET).resolve(fileName);
    assertTrue(trgFile.toFile().isFile());
    assertEquals(fileContent, Files.readAllLines(trgFile));
}

From source file:fi.johannes.kata.ocr.utils.files.ExistingFileConnection.java

public List<String> readLines() throws IOException {
    return Files.readAllLines(p);
}

From source file:org.elasticsearch.qa.die_with_dignity.DieWithDignityIT.java

public void testDieWithDignity() throws Exception {
    // deleting the PID file prevents stopping the cluster from failing since it occurs if and only if the PID file exists
    final Path pidFile = PathUtils.get(System.getProperty("pidfile"));
    final List<String> pidFileLines = Files.readAllLines(pidFile);
    assertThat(pidFileLines, hasSize(1));
    final int pid = Integer.parseInt(pidFileLines.get(0));
    Files.delete(pidFile);//from w  w  w . j  ava2s.  c  o m
    IOException e = expectThrows(IOException.class,
            () -> client().performRequest(new Request("GET", "/_die_with_dignity")));
    Matcher<IOException> failureMatcher = instanceOf(ConnectionClosedException.class);
    if (Constants.WINDOWS) {
        /*
         * If the other side closes the connection while we're waiting to fill our buffer
         * we can get IOException with the message below. It seems to only come up on
         * Windows and it *feels* like it could be a ConnectionClosedException but
         * upstream does not consider this a bug:
         * https://issues.apache.org/jira/browse/HTTPASYNC-134
         *
         * So we catch it here and consider it "ok".
        */
        failureMatcher = either(failureMatcher).or(
                hasToString(containsString("An existing connection was forcibly closed by the remote host")));
    }
    assertThat(e, failureMatcher);

    // the Elasticsearch process should die and disappear from the output of jps
    assertBusy(() -> {
        final String jpsPath = PathUtils.get(System.getProperty("runtime.java.home"), "bin/jps").toString();
        final Process process = new ProcessBuilder().command(jpsPath).start();
        assertThat(process.waitFor(), equalTo(0));
        try (InputStream is = process.getInputStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
            String line;
            while ((line = in.readLine()) != null) {
                final int currentPid = Integer.parseInt(line.split("\\s+")[0]);
                assertThat(line, pid, not(equalTo(currentPid)));
            }
        }
    });

    // parse the logs and ensure that Elasticsearch died with the expected cause
    final List<String> lines = Files.readAllLines(PathUtils.get(System.getProperty("log")));

    final Iterator<String> it = lines.iterator();

    boolean fatalErrorOnTheNetworkLayer = false;
    boolean fatalErrorInThreadExiting = false;

    while (it.hasNext() && (fatalErrorOnTheNetworkLayer == false || fatalErrorInThreadExiting == false)) {
        final String line = it.next();
        if (line.contains("fatal error on the network layer")) {
            fatalErrorOnTheNetworkLayer = true;
        } else if (line.matches(".*\\[ERROR\\]\\[o.e.b.ElasticsearchUncaughtExceptionHandler\\] \\[node-0\\]"
                + " fatal error in thread \\[Thread-\\d+\\], exiting$")) {
            fatalErrorInThreadExiting = true;
            assertTrue(it.hasNext());
            assertThat(it.next(), equalTo("java.lang.OutOfMemoryError: die with dignity"));
        }
    }

    assertTrue(fatalErrorOnTheNetworkLayer);
    assertTrue(fatalErrorInThreadExiting);
}