List of usage examples for java.nio.file FileSystems getDefault
public static FileSystem getDefault()
From source file:cpd3314.project.CPD3314ProjectTest.java
@Test public void testFormatHTML() throws Exception { System.out.println("main"); String[] args = { "-format=HTML" }; CPD3314Project.main(args);//from ww w. j av a 2 s. co m File expected = FileSystems.getDefault().getPath("testFiles", "formatHTML.html").toFile(); File result = new File("CPD3314.html"); assertTrue("Output File Doesn't Exist", result.exists()); assertXMLFilesEqual(expected, result); }
From source file:com.team3637.service.ScheduleServiceMySQLImpl.java
@Override public void importCSV(String inputFile) { try {//from w w w .j a v a2s .co m String csvData = new String(Files.readAllBytes(FileSystems.getDefault().getPath(inputFile))); csvData = csvData.replaceAll("\\r", ""); CSVParser parser = CSVParser.parse(csvData, CSVFormat.DEFAULT.withRecordSeparator("\n")); for (CSVRecord record : parser) { Schedule schedule = new Schedule(); schedule.setId(Integer.parseInt(record.get(0))); schedule.setMatchNum(Integer.parseInt(record.get(1))); schedule.setB1(Integer.parseInt(record.get(2))); schedule.setB2(Integer.parseInt(record.get(3))); schedule.setB3(Integer.parseInt(record.get(4))); schedule.setR1(Integer.parseInt(record.get(5))); schedule.setR2(Integer.parseInt(record.get(6))); schedule.setR3(Integer.parseInt(record.get(7))); if (checkForMatch(schedule)) update(schedule); else create(schedule); } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.networknt.codegen.eventuate.EventuateHybridServiceGenerator.java
@Override public void generate(String targetPath, Object model, Any config) throws IOException { // whoever is calling this needs to make sure that model is converted to Map<String, Object> String handlerPackage = config.get("handlerPackage").toString(); boolean overwriteHandler = config.toBoolean("overwriteHandler"); boolean overwriteHandlerTest = config.toBoolean("overwriteHandlerTest"); boolean enableHttp = config.toBoolean("enableHttp"); boolean enableHttps = config.toBoolean("enableHttps"); boolean enableRegistry = config.toBoolean("enableRegistry"); boolean supportClient = config.toBoolean("supportClient"); String version = config.toString("version"); transfer(targetPath, "", "pom.xml", templates.eventuate.hybrid.service.pom.template(config)); //transfer(targetPath, "", "Dockerfile", templates.dockerfile.template(config)); transfer(targetPath, "", ".gitignore", templates.eventuate.hybrid.gitignore.template()); transfer(targetPath, "", "README.md", templates.eventuate.hybrid.service.README.template()); transfer(targetPath, "", "LICENSE", templates.eventuate.hybrid.LICENSE.template()); transfer(targetPath, "", ".classpath", templates.eventuate.hybrid.classpath.template()); transfer(targetPath, "", ".project", templates.eventuate.hybrid.project.template()); // config/*from ww w .j av a2 s . c o m*/ transfer(targetPath, ("src.main.resources.config").replace(".", separator), "service.yml", templates.eventuate.hybrid.serviceYml.template(config)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "server.yml", templates.eventuate.hybrid.serverYml.template( config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"), enableHttp, "49587", enableHttps, "49588", enableRegistry, version)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "secret.yml", templates.eventuate.hybrid.secretYml.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "hybrid-security.yml", templates.eventuate.hybrid.securityYml.template()); if (supportClient) { transfer(targetPath, ("src.main.resources.config").replace(".", separator), "client.yml", templates.eventuate.hybrid.clientYml.template()); } else { transfer(targetPath, ("src.test.resources.config").replace(".", separator), "client.yml", templates.eventuate.hybrid.clientYml.template()); } transfer(targetPath, ("src.test.resources.config").replace(".", separator), "primary.crt", templates.eventuate.hybrid.primaryCrt.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "secondary.crt", templates.eventuate.hybrid.secondaryCrt.template()); // logging transfer(targetPath, ("src.main.resources").replace(".", separator), "logback.xml", templates.eventuate.hybrid.logback.template()); transfer(targetPath, ("src.test.resources").replace(".", separator), "logback-test.xml", templates.eventuate.hybrid.logback.template()); // handler Map<String, Object> services = new HashMap<String, Object>(); Any anyModel = (Any) model; String host = anyModel.toString("host"); String service = anyModel.toString("service"); List<Any> items = anyModel.get("action").asList(); if (items != null && items.size() > 0) { for (Any item : items) { Any any = item.get("example"); String example = any.valueType() != ValueType.INVALID ? StringEscapeUtils.escapeJson(any.toString()).trim() : ""; if (overwriteHandler) transfer(targetPath, ("src.main.java." + handlerPackage).replace(".", separator), item.get("handler") + ".java", templates.eventuate.hybrid.handler .template(handlerPackage, host, service, item, example)); String serviceId = host + "/" + service + "/" + item.get("name") + "/" + item.get("version"); Map<String, Object> map = new HashMap<>(); map.put("schema", item.get("schema")); map.put("scope", item.get("scope")); services.put(serviceId, map); } // handler test cases transfer(targetPath, ("src.test.java." + handlerPackage + ".").replace(".", separator), "TestServer.java", templates.eventuate.hybrid.testServer.template(handlerPackage)); if (overwriteHandlerTest) { for (Any item : items) { transfer(targetPath, ("src.test.java." + handlerPackage).replace(".", separator), item.get("handler") + "Test.java", templates.eventuate.hybrid.handlerTest.template(handlerPackage, host, service, item)); } } } // transfer binary files without touching them. try (InputStream is = EventuateHybridServiceGenerator.class .getResourceAsStream("/binaries/server.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "server.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = EventuateHybridServiceGenerator.class .getResourceAsStream("/binaries/server.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "server.truststore"), StandardCopyOption.REPLACE_EXISTING); } if (Files.notExists(Paths.get(targetPath, ("src.main.resources.config").replace(".", separator)))) { Files.createDirectories(Paths.get(targetPath, ("src.main.resources.config").replace(".", separator))); } // write the generated schema into the config folder for schema validation. JsonStream.serialize(services, new FileOutputStream(FileSystems.getDefault() .getPath(targetPath, ("src.main.resources").replace(".", separator), "schema.json").toFile())); }
From source file:org.fcrepo.http.api.ExternalContentPathValidator.java
/** * Starts up monitoring of the allowed list configuration for changes. *///from w w w . j a v a 2 s . c o m private void monitorForChanges() { if (monitorRunning) { return; } final Path path = Paths.get(configPath); if (!path.toFile().exists()) { LOGGER.debug("Allow list configuration {} does not exist, disabling monitoring", configPath); return; } final Path directoryPath = path.getParent(); try { final WatchService watchService = FileSystems.getDefault().newWatchService(); directoryPath.register(watchService, ENTRY_MODIFY); monitorThread = new Thread(new Runnable() { @Override public void run() { try { for (;;) { WatchKey key; try { key = watchService.take(); } catch (final InterruptedException e) { LOGGER.debug("Interrupted the configuration monitor thread."); break; } for (final WatchEvent<?> event : key.pollEvents()) { final WatchEvent.Kind<?> kind = event.kind(); if (kind == OVERFLOW) { continue; } // If the configuration file triggered this event, reload it final Path changed = (Path) event.context(); if (changed.equals(path.getFileName())) { LOGGER.info("External binary configuration {} has been updated, reloading.", path); try { loadAllowedPaths(); } catch (final IOException e) { LOGGER.error("Failed to reload external locations configuration", e); } } // reset the key final boolean valid = key.reset(); if (!valid) { LOGGER.debug("Monitor of {} is no longer valid", path); break; } } } } finally { try { watchService.close(); } catch (final IOException e) { LOGGER.error("Failed to stop configuration monitor", e); } } monitorRunning = false; } }); } catch (final IOException e) { LOGGER.error("Failed to start configuration monitor", e); } monitorThread.start(); monitorRunning = true; }
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.ja v a2 s .co m // 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:com.networknt.codegen.hybrid.HybridServiceGenerator.java
@Override public void generate(String targetPath, Object model, Any config) throws IOException { // whoever is calling this needs to make sure that model is converted to Map<String, Object> String handlerPackage = config.get("handlerPackage").toString(); boolean overwriteHandler = config.toBoolean("overwriteHandler"); boolean overwriteHandlerTest = config.toBoolean("overwriteHandlerTest"); boolean enableHttp = config.toBoolean("enableHttp"); boolean enableHttps = config.toBoolean("enableHttps"); boolean enableRegistry = config.toBoolean("enableRegistry"); boolean supportClient = config.toBoolean("supportClient"); String version = config.toString("version"); transfer(targetPath, "", "pom.xml", templates.hybrid.service.pom.template(config)); //transfer(targetPath, "", "Dockerfile", templates.dockerfile.template(config)); transfer(targetPath, "", ".gitignore", templates.hybrid.gitignore.template()); transfer(targetPath, "", "README.md", templates.hybrid.service.README.template()); transfer(targetPath, "", "LICENSE", templates.hybrid.LICENSE.template()); transfer(targetPath, "", ".classpath", templates.hybrid.classpath.template()); transfer(targetPath, "", ".project", templates.hybrid.project.template()); // config/*www.j av a 2s.com*/ transfer(targetPath, ("src.test.resources.config").replace(".", separator), "service.yml", templates.hybrid.serviceYml.template(config)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "server.yml", templates.hybrid.serverYml.template( config.get("groupId") + "." + config.get("artifactId") + "-" + config.get("version"), enableHttp, "49587", enableHttps, "49588", enableRegistry, version)); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "secret.yml", templates.hybrid.secretYml.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "hybrid-security.yml", templates.hybrid.securityYml.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "client.yml", templates.hybrid.clientYml.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "primary.crt", templates.hybrid.primaryCrt.template()); transfer(targetPath, ("src.test.resources.config").replace(".", separator), "secondary.crt", templates.hybrid.secondaryCrt.template()); // logging transfer(targetPath, ("src.main.resources").replace(".", separator), "logback.xml", templates.hybrid.logback.template()); transfer(targetPath, ("src.test.resources").replace(".", separator), "logback-test.xml", templates.hybrid.logback.template()); // handler Map<String, Object> services = new HashMap<String, Object>(); Any anyModel = (Any) model; String host = anyModel.toString("host"); String service = anyModel.toString("service"); List<Any> items = anyModel.get("action").asList(); if (items != null && items.size() > 0) { for (Any item : items) { Any any = item.get("example"); String example = any.valueType() != ValueType.INVALID ? StringEscapeUtils.escapeJson(any.toString()).trim() : ""; if (!overwriteHandler && checkExist(targetPath, ("src.main.java." + handlerPackage).replace(".", separator), item.get("handler") + ".java")) { continue; } transfer(targetPath, ("src.main.java." + handlerPackage).replace(".", separator), item.get("handler") + ".java", templates.hybrid.handler.template(handlerPackage, host, service, item, example)); String serviceId = host + "/" + service + "/" + item.get("name") + "/" + item.get("version"); Map<String, Object> map = new HashMap<>(); map.put("schema", item.get("schema")); map.put("scope", item.get("scope")); services.put(serviceId, map); } // handler test cases transfer(targetPath, ("src.test.java." + handlerPackage + ".").replace(".", separator), "TestServer.java", templates.hybrid.testServer.template(handlerPackage)); for (Any item : items) { if (!overwriteHandlerTest && checkExist(targetPath, ("src.test.java." + handlerPackage).replace(".", separator), item.get("handler") + "Test.java")) { continue; } transfer(targetPath, ("src.test.java." + handlerPackage).replace(".", separator), item.get("handler") + "Test.java", templates.hybrid.handlerTest.template(handlerPackage, host, service, item)); } } // transfer binary files without touching them. try (InputStream is = HybridServiceGenerator.class.getResourceAsStream("/binaries/server.keystore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "server.keystore"), StandardCopyOption.REPLACE_EXISTING); } try (InputStream is = HybridServiceGenerator.class.getResourceAsStream("/binaries/server.truststore")) { Files.copy(is, Paths.get(targetPath, ("src.test.resources.config").replace(".", separator), "server.truststore"), StandardCopyOption.REPLACE_EXISTING); } if (Files.notExists(Paths.get(targetPath, ("src.main.resources.config").replace(".", separator)))) { Files.createDirectories(Paths.get(targetPath, ("src.main.resources.config").replace(".", separator))); } // write the generated schema into the config folder for schema validation. JsonStream.serialize(services, new FileOutputStream(FileSystems.getDefault() .getPath(targetPath, ("src.main.resources").replace(".", separator), "schema.json").toFile())); }
From source file:us.colloquy.index.IndexHandler.java
@Test public void loadDiariesIndex() { Properties properties = loadProperties(); List<DiaryEntry> diaryEntries = new ArrayList<>(); List<DocumentPointer> documentPointers = new ArrayList<>(); // getURIForAllDiaries(documentPointers, System.getProperty("user.home") + "/Documents/Tolstoy/openDiaries"); ///*from w w w .j av a 2s. c o m*/ String strPathToDiaries = "samples/diaries"; //find all volumes with diaries Path pathToDiaries = FileSystems.getDefault().getPath(strPathToDiaries); List<Path> listOfDiaryVolumes = new ArrayList<>(); int maxDepth = 1; try (Stream<Path> stream = Files.find(pathToDiaries, maxDepth, (path, attr) -> { return String.valueOf(path).contains("dnevnik"); })) { stream.forEach(listOfDiaryVolumes::add); } catch (IOException e) { e.printStackTrace(); } int diaryCounter = 0; File entries_debug = new File("entries_debug.txt"); entries_debug.delete(); try (FileWriter fw = new FileWriter("entries_debug.txt", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter outDebug = new PrintWriter(bw)) { outDebug.println("start file"); //more code for (Path path : listOfDiaryVolumes) { documentPointers.clear(); getURIForAllDiaries(documentPointers, path); diaryEntries.clear(); for (DocumentPointer pointer : documentPointers) { List<DiaryEntry> diaryEntriesInPointer = new ArrayList<>(); DiaryParser.parseDiaries(pointer, diaryCounter++, diaryEntriesInPointer, outDebug); //test case "temp/OEBPS/Text/0001_1006_2002.xhtml" //find if anything is wrong in a pointer for (DiaryEntry diaryEntry : diaryEntriesInPointer) { if (diaryEntry.getDate() == null || diaryEntry.getEntry().length() < 20) { System.out.println(" Missing entry: --------------- " + pointer.getUri() + " ---------------------------------"); System.out.println(diaryEntry.toString()); } } diaryEntries.addAll(diaryEntriesInPointer); } System.out.println("Total number of diaries in " + path.getFileName() + ": " + diaryEntries.size()); //code below to set ids and check a few letters int i = 0; for (DiaryEntry diaryEntry : diaryEntries) { i++; String id = "D-" + path.getFileName().toString().replaceAll(".*_", "") + "-" + i; diaryEntry.setId(id); } System.out.println("Total number of diaries in volume: " + diaryEntries.size()); //export json files try { ObjectWriter ow = new com.fasterxml.jackson.databind.ObjectMapper().writer() .withDefaultPrettyPrinter(); String json = ow.writeValueAsString(diaryEntries); System.out.println("-------------------- Start exporting diaries in Volume " + path.getFileName() + " ------------- "); // String origin = diaryEntries.get(0).getSource(); String fileName = "parsed/diaries/" + path.getFileName() + ".json"; try (Writer out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"))) { out.write(json); } System.out.println("-------------------- End of export in Volume " + path.getFileName() + " ------------- "); } catch (Exception e) { e.printStackTrace(); } if (properties.getProperty("upload_to_elastic").equalsIgnoreCase("true")) { ElasticLoader.uploadDiariesToElasticServer(properties, diaryEntries); } } outDebug.println("end file"); //more code } catch (IOException e) { //exception handling left as an exercise for the reader } }
From source file:net.lldp.checksims.submission.Submission.java
/** * Recursively find all files matching in a directory. * * @param directory Directory to search in * @param glob Match pattern used to identify files to include * @return List of all matching files in this directory and subdirectories *///from ww w. j a v a 2 s . c o m static Set<File> getAllMatchingFiles(File directory, String glob, boolean recursive) throws NoSuchFileException, NotDirectoryException { checkNotNull(directory); checkNotNull(glob); checkArgument(!glob.isEmpty(), "Glob pattern cannot be empty"); if (!directory.exists()) { throw new NoSuchFileException("Does not exist: " + directory.getAbsolutePath()); } else if (!directory.isDirectory()) { throw new NotDirectoryException("Not a directory: " + directory.getAbsolutePath()); } PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + glob); Set<File> allFiles = new HashSet<>(); Logger logs = LoggerFactory.getLogger(Submission.class); if (recursive) { logs.trace("Recursively traversing directory " + directory.getName()); } // Get files in this directory File[] contents = directory .listFiles((f) -> matcher.matches(Paths.get(f.getAbsolutePath()).getFileName()) && f.isFile()); // TODO consider mapping to absolute paths? // Add this directory Collections.addAll(allFiles, contents); // Get subdirectories File[] subdirs = directory.listFiles(File::isDirectory); // Recursively call on all subdirectories if specified if (recursive) { for (File subdir : subdirs) { allFiles.addAll(getAllMatchingFiles(subdir, glob, true)); } } return allFiles; }
From source file:org.springframework.data.solr.test.util.EmbeddedSolrServer.java
public void init(String solrHome) throws SolrServerException, IOException, InterruptedException { Method createAndLoadMethod = ClassUtils.getStaticMethod(CoreContainer.class, "createAndLoad", String.class, File.class); LOGGER.debug("Starting CoreContainer %s and loading cores."); if (createAndLoadMethod != null) { coreContainer = (CoreContainer) ReflectionUtils.invokeMethod(createAndLoadMethod, null, solrHome, new File(solrHome + "/solr.xml")); } else {//from www . java 2 s.c om createAndLoadMethod = ClassUtils.getStaticMethod(CoreContainer.class, "createAndLoad", Path.class, Path.class); coreContainer = (CoreContainer) ReflectionUtils.invokeMethod(createAndLoadMethod, null, FileSystems.getDefault().getPath(solrHome), FileSystems.getDefault().getPath(new File(solrHome + "/solr.xml").getPath())); } Thread.sleep(15); // just a little time to make sure the core container is initialized fully LOGGER.debug("CoreContainer up and running - Happy searching :)"); }
From source file:io.stallion.assets.AssetsController.java
public Long getCurrentTimeStampForAssetFile(String path) { String filePath = Context.settings().getTargetFolder() + "/assets/" + path; Path pathObj = FileSystems.getDefault().getPath(filePath); File file = new File(filePath); Long ts = file.lastModified(); return ts;//from w ww . ja v a 2s .c o m }