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:it.polimi.diceH2020.SPACE4CloudWS.solvers.solversImpl.SPNSolver.SPNSolver.java

@Override
protected Pair<List<File>, List<File>> createWorkingFiles(@NotNull SolutionPerJob solutionPerJob)
        throws IOException {
    Pair<List<File>, List<File>> returnValue;

    List<File> netFileList = dataProcessor.retrieveInputFiles(".net", solutionPerJob.getParentID(),
            solutionPerJob.getId(), dataProcessor.getProviderName(),
            solutionPerJob.getTypeVMselected().getId());
    List<File> defFileList = dataProcessor.retrieveInputFiles(".def", solutionPerJob.getParentID(),
            solutionPerJob.getId(), dataProcessor.getProviderName(),
            solutionPerJob.getTypeVMselected().getId());
    List<File> statFileList = dataProcessor.retrieveInputFiles(".stat", solutionPerJob.getParentID(),
            solutionPerJob.getId(), dataProcessor.getProviderName(),
            solutionPerJob.getTypeVMselected().getId());

    final String experiment = String.format("%s, class %s, provider %s, VM %s, # %d",
            solutionPerJob.getParentID(), solutionPerJob.getId(), dataProcessor.getProviderName(),
            solutionPerJob.getTypeVMselected().getId(), solutionPerJob.getNumberVM());

    if (netFileList.isEmpty() || defFileList.isEmpty() || statFileList.isEmpty()) {
        logger.debug(String.format("Generating SPN model for %s", experiment));
        usingInputModel = false;/* w ww.j  ava  2  s.c om*/
        returnValue = generateSPNModel(solutionPerJob);
    } else {
        logger.debug(String.format("Using input SPN model for %s", experiment));
        usingInputModel = true;

        // TODO now it just takes the first file, I would expect a single file per list
        File inputNetFile = netFileList.get(0);
        File inputDefFile = defFileList.get(0);
        File inputStatFile = statFileList.get(0);

        String prefix = filePrefix(solutionPerJob);
        final String originalLabel = String.join("", Files.readAllLines(inputStatFile.toPath()));
        label = statSafeLabel;

        Map<String, String> placeHolders = new TreeMap<>();
        placeHolders.put("@@CONCURRENCY@@", Long.toUnsignedString(solutionPerJob.getNumberUsers().longValue()));
        placeHolders.put("@@CORES@@", Long.toUnsignedString(solutionPerJob.getNumberContainers().longValue()));
        logger.trace("@@CORES@@ replaced with " + solutionPerJob.getNumberContainers().toString());
        placeHolders.put(originalLabel, label);
        List<String> outcomes = processPlaceholders(inputDefFile, placeHolders);

        File defFile = fileUtility.provideTemporaryFile(prefix, ".def");
        writeLinesToFile(outcomes, defFile);
        outcomes = processPlaceholders(inputNetFile, placeHolders);

        File netFile = fileUtility.provideTemporaryFile(prefix, ".net");
        writeLinesToFile(outcomes, netFile);

        File statFile = fileUtility.provideTemporaryFile(prefix, ".stat");
        List<String> statContent = new ArrayList<>(1);
        statContent.add(label);
        writeLinesToFile(statContent, statFile);

        List<File> model = new ArrayList<>(3);
        model.add(netFile);
        model.add(defFile);
        model.add(statFile);
        returnValue = new ImmutablePair<>(model, new ArrayList<>());
    }

    return returnValue;
}

From source file:org.wso2.carbon.launcher.test.OSGiLibBundleDeployerTest.java

private static List<BundleInfo> getActualBundleInfo(Path bundleInfoFile) throws IOException {
    if ((bundleInfoFile != null) && (Files.exists(bundleInfoFile))) {
        List<String> bundleInfoLines = Files.readAllLines(bundleInfoFile);
        List<BundleInfo> bundleInfo = new ArrayList<>();
        bundleInfoLines.stream().forEach(line -> bundleInfo.add(BundleInfo.getInstance(line)));

        return bundleInfo;
    } else {/*from w w w. j  a v a  2  s .  co  m*/
        throw new IOException("Invalid bundles.info file specified");
    }
}

From source file:com.netscape.cmstools.cli.MainCLI.java

public Map<String, String> loadPasswordConfig(String filename) throws Exception {

    Map<String, String> passwords = new LinkedHashMap<String, String>();

    List<String> list = Files.readAllLines(Paths.get(filename));
    String[] lines = list.toArray(new String[list.size()]);

    for (int i = 0; i < lines.length; i++) {

        String line = lines[i].trim();

        if (line.isEmpty()) { // skip blanks
            continue;
        }/* w  ww  . j av a 2 s . c  om*/

        if (line.startsWith("#")) { // skip comments
            continue;
        }

        int p = line.indexOf("=");
        if (p < 0) {
            throw new Exception("Missing delimiter in " + filename + ":" + (i + 1));
        }

        String token = line.substring(0, p).trim();
        String password = line.substring(p + 1).trim();

        if (token.equals("internal")) {
            passwords.put(token, password);

        } else if (token.startsWith("hardware-")) {
            token = token.substring(9); // remove hardware- prefix
            passwords.put(token, password);

        } else {
            // skip non-token passwords
        }
    }

    return passwords;
}

From source file:org.moe.cli.ParameterParserTest.java

@Test
public void generateBindings() throws Exception {

    File project = tmpDir.newFolder();
    ClassLoader cl = this.getClass().getClassLoader();
    URL header = cl.getResource("natives/AppViewController.h");
    CommandLine argc = parseArgs(new String[] { "--path-to-project", project.getPath(), "--headers",
            header.getPath(), "--package-name", "org" });
    IExecutor executor = ExecutorManager.getExecutorByParams(argc);
    assertNotNull(executor);// w  w  w. j  av  a 2 s  .  c  o  m
    assertTrue(executor instanceof GenerateBindingExecutor);

    // generate binding
    executor.execute();

    // check if file exist
    File genJava = new File(project, "src/main/java/org/AppViewController.java");
    assertTrue(genJava.exists());

    // check content
    // @property (weak, nonatomic) IBOutlet UIButton *helloButton;
    // @property (weak, nonatomic) IBOutlet UILabel *statusText;
    // - (IBAction)BtnPressedCancel_helloButton:(NSObject*)sender;

    Pattern helloButtonPattern = Pattern.compile(".*@Selector\\(\"helloButton\"\\).*");
    Pattern statusTextPattern = Pattern.compile(".*@Selector\\(\"statusText\"\\).*");
    Pattern helloButtonActionPattern = Pattern.compile(".*@Selector\\(\"BtnPressedCancel_helloButton:\"\\).*");
    Pattern objCClassBindingPattern = Pattern.compile(".*@ObjCClassBinding.*");

    List<String> lineArray = Files.readAllLines(Paths.get(genJava.getPath()));
    boolean isHelloButton = false;
    boolean isStatusText = false;
    boolean isHelloButtonAction = false;
    boolean isObjCClassBinding = false;

    for (String line : lineArray) {
        Matcher hellowButtonMatcher = helloButtonPattern.matcher(line);
        Matcher statusTextMatcher = statusTextPattern.matcher(line);
        Matcher helloButtonActionMatcher = helloButtonActionPattern.matcher(line);
        Matcher objCMatcher = objCClassBindingPattern.matcher(line);

        isHelloButton |= hellowButtonMatcher.find();
        isStatusText |= statusTextMatcher.find();
        isHelloButtonAction |= helloButtonActionMatcher.find();
        isObjCClassBinding |= objCMatcher.find();
    }

    project.delete();

    assertTrue(isHelloButton);
    assertTrue(isStatusText);
    assertTrue(isHelloButtonAction);
    assertTrue(isObjCClassBinding);

}

From source file:org.evosuite.junit.CoverageAnalysisWithRefectionSystemTest.java

@Test
public void testBindFilteredEventsToMethod() throws IOException {

    EvoSuite evosuite = new EvoSuite();

    String targetClass = ClassPublicInterface.class.getCanonicalName();
    String testClass = ClassPublicInterfaceTest.class.getCanonicalName();
    Properties.TARGET_CLASS = targetClass;

    Properties.CRITERION = new Properties.Criterion[] { Properties.Criterion.LINE };

    Properties.OUTPUT_VARIABLES = RuntimeVariable.Total_Goals + "," + RuntimeVariable.LineCoverage;
    Properties.STATISTICS_BACKEND = StatisticsBackend.CSV;
    Properties.COVERAGE_MATRIX = true;

    String[] command = new String[] { "-class", targetClass, "-Djunit=" + testClass, "-measureCoverage" };

    SearchStatistics statistics = (SearchStatistics) evosuite.parseCommandLine(command);
    Assert.assertNotNull(statistics);/*w ww. ja v  a  2 s .  co  m*/

    Map<String, OutputVariable<?>> outputVariables = statistics.getOutputVariables();

    // The number of lines seems to be different depending on the compiler
    assertTrue(27 - ((Integer) outputVariables.get(RuntimeVariable.Total_Goals.name()).getValue()) <= 1);
    assertTrue(11 - ((Integer) outputVariables.get(RuntimeVariable.Covered_Goals.name()).getValue()) <= 1);
    assertEquals(1, (Integer) outputVariables.get(RuntimeVariable.Tests_Executed.name()).getValue(), 0.0);

    // Assert that all test cases have passed

    String matrix_file = System.getProperty("user.dir") + File.separator + Properties.REPORT_DIR
            + File.separator + "data" + File.separator + targetClass + File.separator
            + Properties.Criterion.LINE.name() + File.separator + Properties.COVERAGE_MATRIX_FILENAME;
    System.out.println("matrix_file: " + matrix_file);

    List<String> lines = Files.readAllLines(FileSystems.getDefault().getPath(matrix_file));
    assertTrue(lines.size() == 1);
    assertTrue(lines.get(0).replace(" ", "").endsWith("+"));
}

From source file:org.esa.snap.smart.configurator.VMParameters.java

/**
 * If allowed, save the VM parameters to disk so they can be used next time
 *
 * @throws IOException if the VM parameters could not be saved
 *///from  w w w .ja v  a 2s .  co  m
void save() throws IOException {

    Properties properties = loadSnapConfProperties();

    String defaultParameters = properties.getProperty(DEFAULT_OPTION_PROPERTY_KEY);

    ArrayList<String> parametersToSave = new ArrayList<>();

    if (defaultParameters != null) {
        // We search for parameters not starting with "-J" in the actual default parameters list.
        // These are not VM parameters and so they will not be replaced
        if (defaultParameters.startsWith("\"")) {
            // we remove global the double quotes
            defaultParameters = defaultParameters.substring(1, defaultParameters.length() - 1);
        }
        List<String> defaultParametersAsList = toParamList(defaultParameters);
        for (String defaultParameter : defaultParametersAsList) {
            if (!defaultParameter.startsWith("-J")) {
                parametersToSave.add(defaultParameter);
            }
        }
    }

    // We add these VM Parameters, adding "-J" to the list
    List<String> vmParametersAsList = toParamList(toString());
    for (String vmParameter : vmParametersAsList) {
        parametersToSave.add("-J" + vmParameter);
    }

    String vmParametersAsString = VMParameters.toString(parametersToSave);
    vmParametersAsString = StringEscapeUtils.escapeJava(vmParametersAsString);
    vmParametersAsString = "\"" + vmParametersAsString + "\"";
    String defaultOptionAsString = DEFAULT_OPTION_PROPERTY_KEY + "=" + vmParametersAsString;

    // we replace the default option setting in the config path
    // we can't use properties.store since this doesn't keep comments and creates some problems with paths
    List<String> snapConfigLines = Files.readAllLines(getSnapConfigPath());

    if (snapConfigLines != null && snapConfigLines.size() > 0) {
        Iterator<String> configLinesIterator = snapConfigLines.iterator();
        String regex = DEFAULT_OPTION_PROPERTY_KEY + "[ =:].*";

        BufferedWriter writer = Files.newBufferedWriter(getSnapConfigPath());
        do {

            String configLine = configLinesIterator.next();

            snapConfigLines.iterator();

            if (configLine != null) {
                if (configLine.matches(regex)) {
                    while (configLine != null && configLine.trim().endsWith("\\")) {
                        configLine = configLinesIterator.next();
                    }
                    writer.write(defaultOptionAsString);
                } else {
                    writer.write(configLine);
                }
                writer.newLine();
            }
        } while (configLinesIterator.hasNext());

        writer.close();
    }
}

From source file:io.syndesis.runtime.action.DynamicActionDefinitionITCase.java

private static String read(final String path) {
    try {/*from w  w  w. java  2 s.  c  om*/
        return String.join("",
                Files.readAllLines(Paths.get(DynamicActionDefinitionITCase.class.getResource(path).toURI())));
    } catch (IOException | URISyntaxException e) {
        throw new IllegalArgumentException("Unable to read from path: " + path, e);
    }
}

From source file:org.apdplat.superword.extract.ChineseSynonymAntonymExtractor.java

private static synchronized void save() {
    System.out.println("?");
    List<String> SYNONYM_LIST = null;
    List<String> ANTONYM_LIST = null;
    try {//from  www  .  ja v a2 s  .c  o m
        if (Files.notExists(CHINESE_SYNONYM)) {
            CHINESE_SYNONYM.toFile().createNewFile();
        }
        if (Files.notExists(CHINESE_ANTONYM)) {
            CHINESE_ANTONYM.toFile().createNewFile();
        }
        System.out.println("??" + SYNONYM_MAP.size());
        Set<String> SYNONYM_STR = new HashSet<>();
        SYNONYM_MAP.keySet().forEach(k -> {
            StringBuilder str = new StringBuilder();
            str.append(k.getWord()).append(" ");
            SYNONYM_MAP.get(k).stream().sorted().forEach(w -> {
                str.append(w.getWord()).append(" ");
            });
            SYNONYM_STR.add(str.toString().trim());
        });

        List<String> existList = Files.readAllLines(CHINESE_SYNONYM);
        SYNONYM_STR.addAll(existList);
        SYNONYM_LIST = SYNONYM_STR.stream().sorted().collect(Collectors.toList());
        System.out.println("??" + SYNONYM_LIST.size());
        Files.write(CHINESE_SYNONYM, SYNONYM_LIST);

        Set<String> set = ANTONYM.keySet().stream().sorted().map(k -> k + " " + ANTONYM.get(k))
                .collect(Collectors.toSet());
        existList = Files.readAllLines(CHINESE_ANTONYM);
        set.addAll(existList);
        ANTONYM_LIST = set.stream().sorted().collect(Collectors.toList());
        System.out.println("???" + ANTONYM_LIST.size());
        Files.write(CHINESE_ANTONYM, ANTONYM_LIST);

        existList = Files.readAllLines(CHECKED_WORDS_PATH);
        CHECKED_WORDS.addAll(existList);
        System.out.println("?" + CHECKED_WORDS.size());
        Files.write(CHECKED_WORDS_PATH, CHECKED_WORDS);
    } catch (Exception e) {
        LOGGER.error("??", SYNONYM_LIST.toString());
        LOGGER.error("???", ANTONYM_LIST.toString());
        LOGGER.error("?", e);
    }
}

From source file:com.wx3.galacdecks.Bootstrap.java

private void importAiHints(GameDatastore datastore, String path) throws IOException {
    Files.walk(Paths.get(path)).forEach(filePath -> {
        if (Files.isRegularFile(filePath)) {
            try {
                if (FilenameUtils.getExtension(filePath.getFileName().toString()).toLowerCase().equals("js")) {
                    String id = FilenameUtils.removeExtension(filePath.getFileName().toString());
                    List<String> lines = Files.readAllLines(filePath);
                    String script = String.join("\n", lines);
                    AiHint hint = new AiHint(id, script);
                    //datastore.createAiHint(hint);
                    aiHintCache.put(id, hint);
                    logger.info("Imported hint " + id);
                }//from ww  w. jav a2  s  . c  o m
            } catch (Exception e) {
                throw new RuntimeException("Failed to parse " + filePath + ": " + e.getMessage());
            }
        }
    });
}

From source file:no.imr.stox.functions.acoustic.PgNapesIO.java

public static void convertPgNapesToLuf20(String path, String fileName, String outFileName) {
    try {/*  w w w  .  j a  v a2s  . c om*/
        List<String> acList = Files.readAllLines(Paths.get(path + "/" + fileName + ".txt"));
        List<String> acVList = Files.readAllLines(Paths.get(path + "/" + fileName + "Values.txt"));
        if (acList.isEmpty() || acVList.isEmpty()) {
            return;
        }
        acList.remove(0);
        acVList.remove(0);
        List<DistanceBO> dList = acList.stream().map(s -> {
            DistanceBO d = new DistanceBO();
            String[] str = s.split("\t", 14);
            d.setNation(str[0]);
            d.setPlatform(str[1]);
            d.setCruise(str[2]);
            d.setLog_start(Conversion.safeStringtoDoubleNULL(str[3]));
            d.setStart_time(Date.from(LocalDateTime.of(Conversion.safeStringtoIntegerNULL(str[4]),
                    Conversion.safeStringtoIntegerNULL(str[5]), Conversion.safeStringtoIntegerNULL(str[6]),
                    Conversion.safeStringtoIntegerNULL(str[7]), Conversion.safeStringtoIntegerNULL(str[8]), 0)
                    .toInstant(ZoneOffset.UTC)));
            d.setLat_start(Conversion.safeStringtoDoubleNULL(str[9]));
            d.setLon_start(Conversion.safeStringtoDoubleNULL(str[10]));
            d.setIntegrator_dist(Conversion.safeStringtoDoubleNULL(str[11]));
            FrequencyBO freq = new FrequencyBO();
            d.getFrequencies().add(freq);
            freq.setTranceiver(1); // implicit in pgnapes
            freq.setUpper_interpret_depth(0d);
            freq.setUpper_integrator_depth(0d);
            freq.setDistance(d);
            freq.setFreq(Conversion.safeStringtoIntegerNULL(str[12]));
            freq.setThreshold(Conversion.safeStringtoDoubleNULL(str[13]));
            return d;
        }).collect(Collectors.toList());
        // Fill in sa values
        acVList.forEach(s -> {
            String[] str = s.split("\t", 11);
            String cruise = str[2];
            Double log = Conversion.safeStringtoDoubleNULL(str[3]);
            Integer year = Conversion.safeStringtoIntegerNULL(str[4]);
            Integer month = Conversion.safeStringtoIntegerNULL(str[5]);
            Integer day = Conversion.safeStringtoIntegerNULL(str[6]);
            if (log == null || year == null || month == null || day == null) {
                return;
            }
            DistanceBO d = dList.parallelStream().filter(di -> {
                if (di.getCruise() == null || di.getLog_start() == null || di.getStart_time() == null) {
                    return false;
                }
                LocalDate ld = di.getStart_time().toInstant().atZone(ZoneOffset.UTC).toLocalDate();
                return cruise.equals(di.getCruise()) && log.equals(di.getLog_start())
                        && year.equals(ld.getYear()) && month.equals(ld.getMonthValue())
                        && day.equals(ld.getDayOfMonth());
            }).findFirst().orElse(null);
            if (d == null) {
                return;
            }
            FrequencyBO freq = d.getFrequencies().get(0);

            String species = str[7];
            Integer acocat = PgNapesEchoConvert.getAcoCatFromPgNapesSpecies(species);
            Double chUppDepth = Conversion.safeStringtoDoubleNULL(str[8]);
            Double chLowDepth = Conversion.safeStringtoDoubleNULL(str[9]);
            Double sa = Conversion.safeStringtoDoubleNULL(str[10]);
            if (acocat == null || sa == null || sa == 0d || chLowDepth == null || chUppDepth == null) {
                return;
            }
            if (d.getPel_ch_thickness() == null) {
                d.setPel_ch_thickness(chLowDepth - chUppDepth);
            }
            Integer ch = (int) (chLowDepth / d.getPel_ch_thickness() + 0.5);
            SABO sabo = new SABO();
            sabo.setFrequency(freq);
            freq.getSa().add(sabo);
            sabo.setAcoustic_category(acocat + "");
            sabo.setCh_type("P");
            sabo.setCh(ch);
            sabo.setSa(sa);
        });
        // Calculate number of pelagic channels

        /*dList.stream().forEach(d -> {
        FrequencyBO f = d.getFrequencies().get(0);
        Integer minCh = f.getSa().stream().map(SABO::getCh).min(Integer::compare).orElse(null);
        Integer maxCh = f.getSa().stream().map(SABO::getCh).max(Integer::compare).orElse(null);
        if (maxCh != null && minCh != null) {
            f.setNum_pel_ch(maxCh - minCh + 1);
        }
        });*/

        if (dList.isEmpty()) {
            return;
        }
        DistanceBO d = dList.get(0);
        String cruise = d.getCruise();
        String nation = d.getNation();
        String pl = d.getPlatform();
        ListUser20Writer.export(cruise, nation, pl, path + "/" + cruise + outFileName + ".xml", dList);

    } catch (IOException ex) {
        Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex);
    }
}