List of usage examples for java.nio.file Files readAllLines
public static List<String> readAllLines(Path path) throws IOException
From source file:com.facebook.buck.util.unarchive.UntarTest.java
/** Assert that a file exists inside of the temp directory with given contents */ private void assertOutputFileExists(Path path, String expectedContents) throws IOException { Path fullPath = tmpFolder.getRoot().resolve(path); Assert.assertTrue(String.format("Expected %s to be a file", fullPath), Files.isRegularFile(fullPath)); String contents = Joiner.on('\n').join(Files.readAllLines(fullPath)); Assert.assertEquals(expectedContents, contents); }
From source file:com.evolveum.midpoint.model.intest.manual.CsvBackingStore.java
protected void replaceInCsv(String[] data) throws IOException { List<String> lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())); boolean found = false; for (int i = 0; i < lines.size(); i++) { String line = lines.get(i); String[] cols = line.split(","); if (cols[0].matches("\"" + data[0] + "\"")) { lines.set(i, formatCsvLine(data)); found = true;//from www . j av a2 s .co m } } if (!found) { throw new IllegalStateException("Not found in CSV: " + data[0]); } Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); }
From source file:org.apdplat.superword.extract.ChineseSynonymAntonymExtractor.java
public static void parseSynonymAntonym(List<String> words) { LOGGER.info("??" + words.size()); Set<String> SKIP_WORDS = new ConcurrentSkipListSet<>(); try {/*from ww w . j a v a 2 s . c o m*/ if (Files.notExists(CHECKED_WORDS_PATH)) { CHECKED_WORDS_PATH.toFile().createNewFile(); } SKIP_WORDS.addAll(Files.readAllLines(CHECKED_WORDS_PATH)); } catch (Exception e) { LOGGER.error("?", e); } int total = words.size() - SKIP_WORDS.size(); LOGGER.info("????" + SKIP_WORDS.size()); LOGGER.info("??" + total); String url = "http://www.iciba.com/"; AtomicInteger i = new AtomicInteger(); EXECUTOR_SERVICE.submit(() -> { while (true) { try { Thread.sleep(60000); } catch (InterruptedException e) { e.printStackTrace(); } save(); } }); words.parallelStream().forEach(word -> { if (SKIP_WORDS.contains(word)) { return; } LOGGER.info( "" + total + "/" + i.incrementAndGet() + " ?" + Thread.currentThread()); try { word = word.trim(); if ("".equals(word) || isNotChineseChar(word) || word.length() < 2) { return; } String html = getContent(url + word); int times = 1; while (StringUtils.isBlank(html) && times < 3) { times++; //IP? ProxyIp.toNewIp(); html = getContent(url + word); } if (StringUtils.isBlank(html)) { LOGGER.error("??" + url + word); return; } times = 1; //LOGGER.debug("?HTML" +html); while (html.contains("??ip?") && times < 3) { times++; //IP? ProxyIp.toNewIp(); html = getContent(url + word); } SynonymAntonym synonymAntonym = parseSynonymAntonym(html, word); if (!synonymAntonym.getSynonym().isEmpty()) { SYNONYM_MAP.put(synonymAntonym.getWord(), synonymAntonym.getSynonym()); } if (!synonymAntonym.getAntonym().isEmpty()) { StringBuilder str = new StringBuilder(); synonymAntonym.getAntonym().forEach(w -> str.append(w.getWord()).append(" ")); ANTONYM.put(word, str.toString().trim()); } CHECKED_WORDS.add(word); } catch (Exception e) { LOGGER.error("", e); } }); save(); filterSameRecord(CHINESE_SYNONYM); filterSameRecord(CHINESE_ANTONYM); }
From source file:org.springframework.security.config.doc.XsdDocumentedTests.java
/** * This test ensures that any element that has children or parents contains a section that has links pointing to that * documentation./*from w w w . j ava 2 s .c om*/ * @return */ @Test public void countLinksWhenReviewingDocumentationThenParentsAndChildrenAreCorrectlyLinked() throws IOException { Map<String, List<String>> docAttrNameToChildren = new HashMap<>(); Map<String, List<String>> docAttrNameToParents = new HashMap<>(); String docAttrName = null; Map<String, List<String>> currentDocAttrNameToElmt = null; List<String> lines = Files.readAllLines(Paths.get(this.referenceLocation)); for (String line : lines) { if (line.matches("^\\[\\[.*\\]\\]$")) { String id = line.substring(2, line.length() - 2); if (id.endsWith("-children")) { docAttrName = id.substring(0, id.length() - 9); currentDocAttrNameToElmt = docAttrNameToChildren; } else if (id.endsWith("-parents")) { docAttrName = id.substring(0, id.length() - 8); currentDocAttrNameToElmt = docAttrNameToParents; } else if (docAttrName != null && !id.startsWith(docAttrName)) { currentDocAttrNameToElmt = null; docAttrName = null; } } if (docAttrName != null && currentDocAttrNameToElmt != null) { String expression = "^\\* <<(nsa-.*),.*>>$"; if (line.matches(expression)) { String elmtId = line.replaceAll(expression, "$1"); currentDocAttrNameToElmt.computeIfAbsent(docAttrName, key -> new ArrayList<>()).add(elmtId); } } } Map<String, Element> elementNameToElement = this.xml.elementsByElementName(this.schemaDocumentLocation); Map<String, List<String>> schemaAttrNameToChildren = new HashMap<>(); Map<String, List<String>> schemaAttrNameToParents = new HashMap<>(); elementNameToElement.entrySet().stream().forEach(entry -> { String key = "nsa-" + entry.getKey(); if (this.ignoredIds.contains(key)) { return; } List<String> parentIds = entry.getValue().getAllParentElmts().values().stream() .filter(element -> !this.ignoredIds.contains(element.getId())).map(element -> element.getId()) .sorted().collect(Collectors.toList()); if (!parentIds.isEmpty()) { schemaAttrNameToParents.put(key, parentIds); } List<String> childIds = entry.getValue().getAllChildElmts().values().stream() .filter(element -> !this.ignoredIds.contains(element.getId())).map(element -> element.getId()) .sorted().collect(Collectors.toList()); if (!childIds.isEmpty()) { schemaAttrNameToChildren.put(key, childIds); } }); assertThat(docAttrNameToChildren).isEqualTo(schemaAttrNameToChildren); assertThat(docAttrNameToParents).isEqualTo(schemaAttrNameToParents); }
From source file:com.evolveum.midpoint.model.intest.manual.CsvBackingStore.java
protected void deleteInCsv(String username) throws IOException { List<String> lines = Files.readAllLines(Paths.get(CSV_TARGET_FILE.getPath())); Iterator<String> iterator = lines.iterator(); while (iterator.hasNext()) { String line = iterator.next(); String[] cols = line.split(","); if (cols[0].matches("\"" + username + "\"")) { iterator.remove();/*from w w w . ja va2s. c o m*/ } } Files.write(Paths.get(CSV_TARGET_FILE.getPath()), lines, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING); }
From source file:com.wx3.galacdecks.Bootstrap.java
private void importDiscardValidators(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); if (lines.size() < 3) { throw new RuntimeException( "Script file should have at least 2 lines: description and code."); }// w w w .j a v a2s . c o m String description = lines.get(0).substring(2).trim(); String script = String.join("\n", lines); ValidatorScript validator = ValidatorScript.createValidator(id, script, description); discardValidatorCache.put(id, validator); logger.info("Imported discard validator " + id); } } catch (Exception e) { throw new RuntimeException("Failed to parse " + filePath + ": " + e.getMessage()); } } }); }
From source file:org.apdplat.superword.tools.WordClassifier.java
public static void save(Map<String, List<String>> data) { LOGGER.info("??"); data.keySet().forEach(key -> {//ww w .j a v a2s. co m try { String path = "src/main/resources/word_" + key + ".txt"; LOGGER.error("??" + path); List<String> existWords = Files.readAllLines(Paths.get(path)); Set<String> allWords = new HashSet<>(); existWords.forEach(line -> { String[] attr = line.split("\\s+"); if (attr != null) { String w = ""; if (attr.length == 1) { w = attr[0]; } if (attr.length == 2) { w = attr[1]; } allWords.add(w); } }); allWords.addAll(data.get(key)); AtomicInteger i = new AtomicInteger(); List<String> list = allWords.stream().sorted().map(word -> i.incrementAndGet() + "\t" + word) .collect(Collectors.toList()); Files.write(Paths.get(path), list); data.get(key).clear(); existWords.clear(); allWords.clear(); list.clear(); } catch (Exception e) { LOGGER.error("??", e); } }); data.clear(); try { if (!NOT_FOUND_WORDS.isEmpty()) { String path = "src/main/resources/word_not_found.txt"; LOGGER.error("??" + path); AtomicInteger i = new AtomicInteger(); //NOT_FOUND_WORDS List<String> list = NOT_FOUND_WORDS.stream().sorted().map(word -> i.incrementAndGet() + "\t" + word) .collect(Collectors.toList()); Files.write(Paths.get(path), list); list.clear(); } //?HTML if (!ORIGIN_HTML.isEmpty()) { String path = "src/main/resources/origin_html_" + System.currentTimeMillis() + ".txt"; LOGGER.error("??" + path); Files.write(Paths.get(path), ORIGIN_HTML); ORIGIN_HTML.clear(); } } catch (Exception e) { LOGGER.error("??", e); } }
From source file:org.moe.cli.ParameterParserTest.java
@Test public void generateBindingsWithoutPackage() throws Exception { File project = tmpDir.newFolder(); ClassLoader cl = this.getClass().getClassLoader(); URL header = cl.getResource("natives/AppViewController.h"); CommandLine argc = parseArgs(//from w ww. j a v a2 s .com new String[] { "--path-to-project", project.getPath(), "--headers", header.getPath() }); IExecutor executor = ExecutorManager.getExecutorByParams(argc); assertNotNull(executor); assertTrue(executor instanceof GenerateBindingExecutor); // generate binding executor.execute(); // check if file exist File genJava = new File(project, "src/main/java/org/moe/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 testHierarchyIncludingInterfaces() throws IOException { EvoSuite evosuite = new EvoSuite(); String targetClass = ClassHierarchyIncludingInterfaces.class.getCanonicalName(); String testClass = ClassHierarchyIncludingInterfacesTest.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" }; Object statistics = evosuite.parseCommandLine(command); Assert.assertNotNull(statistics);/*from w ww . jav a 2s . com*/ // Assert coverage String statistics_file = System.getProperty("user.dir") + File.separator + Properties.REPORT_DIR + File.separator + "statistics.csv"; System.out.println("statistics_file: " + statistics_file); CSVReader reader = new CSVReader(new FileReader(statistics_file)); List<String[]> rows = reader.readAll(); assertTrue(rows.size() == 2); reader.close(); // The number of lines seems to be different depending on the compiler assertTrue( "Expected 32-34lines, but found: " + CsvJUnitData.getValue(rows, RuntimeVariable.Total_Goals.name()), CsvJUnitData.getValue(rows, RuntimeVariable.Total_Goals.name()).equals("32") || CsvJUnitData.getValue(rows, RuntimeVariable.Total_Goals.name()).equals("33") || CsvJUnitData.getValue(rows, RuntimeVariable.Total_Goals.name()).equals("34")); // 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)); assertEquals(1, lines.size()); // The number of lines seems to be different depending on the compiler assertTrue("Expected lines to be 32-34, but got: " + (lines.get(0).replace(" ", "").length()), 34 - lines.get(0).replace(" ", "").length() <= 2); // number of goals + test result ('+' pass, '-' fail) assertTrue("Expected line to end with +, but line is: " + lines.get(0).replace(" ", ""), lines.get(0).replace(" ", "").endsWith("+")); }
From source file:org.g_node.micro.rdf.RdfFileServiceJenaTest.java
/** * Test that the result of a SPARQL query is saved to a file of a specified output format. * @throws Exception/*from w w w . j a v a2 s. c o m*/ */ @Test public void testSaveResultsToSupportedFileFormat() throws Exception { // Set up RDF test file final String miniTTL = "@prefix foaf: <http://xmlns.com/foaf/0.1/> . _:a foaf:name \"TestName\" .\n"; final File currTestFile = this.testFileFolder.resolve("test.ttl").toFile(); FileUtils.write(currTestFile, miniTTL); final String queryString = String.join("", "prefix foaf: <http://xmlns.com/foaf/0.1/> ", "SELECT ?getname WHERE { ?node foaf:name ?getname . }"); final Model queryModel = RdfFileServiceJena.openModelFromFile(currTestFile.getAbsolutePath()); final Query query = QueryFactory.create(queryString); try (QueryExecution qexec = QueryExecutionFactory.create(query, queryModel)) { final ResultSet result = qexec.execSelect(); // Test that an invalid file format exits the method with the proper error message. final String invalidOutputFormat = "iDoNotExist"; RdfFileServiceJena.saveResultsToSupportedFile(result, invalidOutputFormat, ""); assertThat(this.outStream.toString()) .contains(String.join("", invalidOutputFormat, " is not supported by this service.")); // Test that an non existing output file without the proper file extension creates an output // file with the proper file extension. // Further test, that the method saved two lines to the output file. final String validOutputFormat = "csv"; final Path outFileNoExtension = this.testFileFolder.resolve("out.txt"); RdfFileServiceJena.saveResultsToSupportedFile(result, validOutputFormat, outFileNoExtension.toString()); final Path outFileNameAddedFileExtension = Paths .get(String.join("", outFileNoExtension.toString(), ".", validOutputFormat)); assertThat(Files.exists(outFileNoExtension)).isFalse(); assertThat(Files.exists(outFileNameAddedFileExtension)).isTrue(); assertThat(Files.readAllLines(outFileNameAddedFileExtension).size()).isEqualTo(2); // Test that a non existing output file with the proper file extension creates // the output file with an unchanged file name. final Path outFileExtension = this.testFileFolder.resolve(String.join("", "out.", validOutputFormat)); RdfFileServiceJena.saveResultsToSupportedFile(result, validOutputFormat, outFileExtension.toString()); assertThat(Files.exists(outFileExtension)).isTrue(); // Test that an existing output file is overwritten. assertThat(Files.readAllLines(outFileExtension).size()).isEqualTo(1); try (QueryExecution qexec_next = QueryExecutionFactory.create(query, queryModel)) { final ResultSet result_next = qexec_next.execSelect(); RdfFileServiceJena.saveResultsToSupportedFile(result_next, validOutputFormat, outFileExtension.toString()); assertThat(Files.exists(outFileExtension)).isTrue(); assertThat(Files.readAllLines(outFileExtension).size()).isEqualTo(2); } } }