List of usage examples for java.nio.file FileSystems getDefault
public static FileSystem getDefault()
From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java
public boolean createCacheFileGenomes(String filePath) { boolean isSuccess = false; JSONObject jsonData = new JSONObject(); JSONObject data;// w w w . j ava2 s .c om // from WP // data data = read(baseURL + "/tab/dlp-genomes-data/?req=passphrase"); if (data != null) { jsonData.put("data", data); } // tools data = read(baseURL + "/tab/dlp-genomes-tools/?req=passphrase"); if (data != null) { jsonData.put("tools", data); } // process data = read(baseURL + "/tab/dlp-genomes-process/?req=passphrase"); if (data != null) { jsonData.put("process", data); } // download data = read(baseURL + "/tab/dlp-genomes-download/?req=passphrase"); if (data != null) { jsonData.put("download", data); } // from solr or database // add popularGenomes data = getPopularGenomes(); if (data != null) { jsonData.put("popularGenomes", data); } // add top5_1 data = getTop5List("host_name"); if (data != null) { jsonData.put("top5_1", data); } // add top5_2 data = getTop5List("isolation_country"); if (data != null) { jsonData.put("top5_2", data); } // add numberGenomes data = getGenomeCounts(); if (data != null) { jsonData.put("numberGenomes", data); } // add genomeStatus data = getGenomeStatus(); if (data != null) { jsonData.put("genomeStatus", data); } // save jsonData to file try (PrintWriter jsonOut = new PrintWriter( Files.newBufferedWriter(FileSystems.getDefault().getPath(filePath), Charset.defaultCharset()));) { jsonData.writeJSONString(jsonOut); isSuccess = true; } catch (IOException e) { LOGGER.error(e.getMessage(), e); } return isSuccess; }
From source file:org.mail.bridge.FolderMonitor.java
@SuppressWarnings("unchecked") @Override/*from w w w. j a va 2s. c o m*/ public void run() { Path outboxPath = outboxFolder.toPath(); WatchService watcher; try { watcher = FileSystems.getDefault().newWatchService(); outboxPath.register(watcher, ENTRY_CREATE); } catch (IOException e) { LOG.error(e.getMessage(), e); throw new IllegalStateException(e); } while (true) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException e) { LOG.error(e.getMessage(), e); throw new IllegalStateException(e); } if (timer != null) { timer.cancel(); timer = null; } LOG.info("Folder '{}' content changed", outboxFolder.getAbsolutePath()); for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == OVERFLOW) continue; File patch = outboxPath.resolve(((WatchEvent<Path>) event).context()).toFile(); if (fileFilter.accept(patch)) files.add(patch); } if (!files.isEmpty()) { timer = new Timer(); timer.schedule(new ProcessFilesTimerTask(), NEW_FILES_PROCESS_DELAY); LOG.debug("File processing timer is (re-)scheduled"); } boolean valid = key.reset(); if (!valid) { LOG.error("Path '{}' isn't valid anymore", outboxPath); postMessage(new Main.StopMessage( String.format("Please verify validity of folder '%s' and re-run application", outboxPath))); break; } } monitorThread = null; }
From source file:com.github.aptd.simulation.TestCLanguageLabels.java
/** * test-case all resource strings//from ww w . j av a 2s. c o m * * @throws IOException throws on io errors */ @Test public void testResourceString() throws IOException { assumeTrue("no languages are defined for checking", !LANGUAGEPROPERY.isEmpty()); final Set<String> l_ignoredlabel = new HashSet<>(); // --- parse source and get label definition final Set<String> l_label = Collections.unmodifiableSet(Files.walk(Paths.get(SEARCHPATH)) .filter(Files::isRegularFile).filter(i -> i.toString().endsWith(".java")).flatMap(i -> { try { final CJavaVistor l_parser = new CJavaVistor(); l_parser.visit(JavaParser.parse(new FileInputStream(i.toFile())), null); return l_parser.labels().stream(); } catch (final IOException l_excpetion) { assertTrue(MessageFormat.format("io error on file [{0}]: {1}", i, l_excpetion.getMessage()), false); return Stream.empty(); } catch (final ParseProblemException l_exception) { // add label build by class path to the ignore list l_ignoredlabel.add(i.toAbsolutePath().toString() // remove path to class directory .replace(FileSystems.getDefault().provider().getPath(SEARCHPATH).toAbsolutePath() .toString(), "") // string starts with path separator .substring(1) // remove file extension .replace(".java", "") // replace separators with dots .replace("/", CLASSSEPARATOR) // convert to lower-case .toLowerCase() // remove package-root name .replace(CCommon.PACKAGEROOT + CLASSSEPARATOR, "")); System.err.println(MessageFormat.format("parsing error on file [{0}]:\n{1}", i, l_exception.getMessage())); return Stream.empty(); } }).collect(Collectors.toSet())); // --- check of any label is found assertFalse("translation labels are empty, check naming of translation method", l_label.isEmpty()); // --- check label towards the property definition if (l_ignoredlabel.size() > 0) System.err.println(MessageFormat.format( "labels that starts with {0} are ignored, because parsing errors are occurred", l_ignoredlabel)); LANGUAGEPROPERY.forEach((k, v) -> { try { final Properties l_property = new Properties(); l_property.load(new FileInputStream(new File(v))); final Set<String> l_parseditems = new HashSet<>(l_label); final Set<String> l_propertyitems = l_property.keySet().parallelStream().map(Object::toString) .collect(Collectors.toSet()); // --- check if all property items are within the parsed labels l_parseditems.removeAll(l_propertyitems); assertTrue(MessageFormat.format( "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the language file:\n{2}", k, l_parseditems.size(), StringUtils.join(l_parseditems, ", ")), l_parseditems.isEmpty()); // --- check if all parsed labels within the property item and remove ignored labels l_propertyitems.removeAll(l_label); final Set<String> l_ignoredpropertyitems = l_propertyitems.parallelStream() .filter(j -> l_ignoredlabel.parallelStream().map(j::startsWith).allMatch(l -> false)) .collect(Collectors.toSet()); assertTrue(MessageFormat.format( "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the source code:\n{2}", k, l_ignoredpropertyitems.size(), StringUtils.join(l_ignoredpropertyitems, ", ")), l_ignoredpropertyitems.isEmpty()); } catch (final IOException l_exception) { assertTrue(MessageFormat.format("io exception: {0}", l_exception.getMessage()), false); } }); }
From source file:com.ccserver.digital.controller.AdminControllerTest.java
@Test public void downloadApplication() throws IOException { CreditCardApplicationDTO ccApp = getCreditCardApplicationDTOMock(1L); Mockito.when(ccAppService.getApplication(1L)).thenReturn(ccApp); File ifile = new File("./src/main/resources/sample"); Path idDocPath = FileSystems.getDefault().getPath(ifile.getAbsolutePath(), "IdDoc.pdf"); byte[] idDocByteArray = Files.readAllBytes(idDocPath); Map<String, byte[]> docs = new HashMap<String, byte[]>(); docs.put("abc", idDocByteArray); Mockito.when(docsService.getFullDocumentsByApplicationId(1L)).thenReturn(docs); Mockito.when(response.getOutputStream()).thenReturn(servletOutputStream); Mockito.when(zipFileService.zipIt(docs)).thenReturn(idDocByteArray); // when// w ww .ja v a2s . c o m ResponseEntity<?> application = controller.downloadApplication(1L, response); // then Assert.assertEquals(HttpStatus.OK, application.getStatusCode()); }
From source file:org.lightjason.agentspeak.TestCLanguageLabels.java
/** * test-case all resource strings/*from www. j ava 2 s. c om*/ * * @throws IOException throws on io errors */ @Test public void testResourceString() throws IOException { assumeTrue("no languages are defined for checking", !LANGUAGEPROPERY.isEmpty()); final Set<String> l_ignoredlabel = new HashSet<>(); // --- parse source and get label definition final Set<String> l_label = Collections.unmodifiableSet(Files.walk(Paths.get(SEARCHPATH)) .filter(Files::isRegularFile).filter(i -> i.toString().endsWith(".java")).flatMap(i -> { try { final CJavaVistor l_parser = new CJavaVistor(); l_parser.visit(JavaParser.parse(new FileInputStream(i.toFile())), null); return l_parser.labels().stream(); } catch (final IOException l_excpetion) { assertTrue(MessageFormat.format("io error on file [{0}]: {1}", i, l_excpetion.getMessage()), false); return Stream.empty(); } catch (final ParseProblemException l_exception) { // add label build by class path to the ignore list l_ignoredlabel.add(i.toAbsolutePath().toString() // remove path to class directory .replace(FileSystems.getDefault().provider().getPath(SEARCHPATH).toAbsolutePath() .toString(), "") // string starts with path separator .substring(1) // remove file extension .replace(".java", "") // replace separators with dots .replace("/", CLASSSEPARATOR) // convert to lower-case .toLowerCase() // remove package-root name .replace(CCommon.PACKAGEROOT + CLASSSEPARATOR, "")); System.err.println(MessageFormat.format("parsing error on file [{0}]:\n{1}", i, l_exception.getMessage())); return Stream.empty(); } }).collect(Collectors.toSet())); // --- check of any label is found assertFalse("translation labels are empty, check naming of translation method", l_label.isEmpty()); // --- check label towards the property definition if (l_ignoredlabel.size() > 0) System.err.println(MessageFormat.format( "labels that starts with {0} are ignored, because parsing errors are occurred", l_ignoredlabel)); LANGUAGEPROPERY.forEach((k, v) -> { try (final FileInputStream l_stream = new FileInputStream(new File(v))) { final Properties l_property = new Properties(); l_property.load(l_stream); final Set<String> l_parseditems = new HashSet<>(l_label); final Set<String> l_propertyitems = l_property.keySet().parallelStream().map(Object::toString) .collect(Collectors.toSet()); // --- check if all property items are within the parsed labels l_parseditems.removeAll(l_propertyitems); assertTrue(MessageFormat.format( "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the language file:\n{2}", k, l_parseditems.size(), StringUtils.join(l_parseditems, ", ")), l_parseditems.isEmpty()); // --- check if all parsed labels within the property item and remove ignored labels l_propertyitems.removeAll(l_label); final Set<String> l_ignoredpropertyitems = l_propertyitems.parallelStream() .filter(j -> l_ignoredlabel.parallelStream().map(j::startsWith).allMatch(l -> false)) .collect(Collectors.toSet()); assertTrue(MessageFormat.format( "the following {1,choice,1#key|1<keys} in language [{0}] {1,choice,1#is|1<are} not existing within the source code:\n{2}", k, l_ignoredpropertyitems.size(), StringUtils.join(l_ignoredpropertyitems, ", ")), l_ignoredpropertyitems.isEmpty()); } catch (final IOException l_exception) { assertTrue(MessageFormat.format("io exception: {0}", l_exception.getMessage()), false); } }); }
From source file:org.wso2.appserver.integration.tests.logging.accesslogs.HttpAccessLogTestCase.java
@Test(groups = "wso2.as", description = "Send GET and POST requests to generate http access logs and read " + "http access log files", dependsOnMethods = "testWebAppUpload") public void testWebAppResponse() throws Exception { //GET request HttpResponse response = HttpURLConnectionClient.sendGetRequest(getWebAppURL(WebAppTypes.WEBAPPS) + "/" + WEB_APP_NAME + "/services/test_access_log/simpleget?name=abc&domain=wso2.com", null); assertEquals(response.getResponseCode(), HttpStatus.SC_OK, "GET Request was not successful in user mode : " + userMode); //POST Request assertEquals(/*from ww w. j a va 2 s . c om*/ makePostRequest(getWebAppURL(WebAppTypes.WEBAPPS) + "/" + WEB_APP_NAME + "/services/test_access_log/simplepost").toString(), "hello abc", "POST Request was not successful in user mode : " + userMode); //Register a watch service to wait until log files are created WatchService watcher = FileSystems.getDefault().newWatchService(); Path filePath = Paths.get(logFileLocation); filePath.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY); long time = System.currentTimeMillis() + 30 * 1000; boolean isNewLogFilesAreCreated = false; while (!isNewLogFilesAreCreated && System.currentTimeMillis() < time) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException ex) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { if (request_log_file.exists() && response_log_file.exists() && variable_log_file.exists()) { isNewLogFilesAreCreated = true; break; } } } boolean valid = key.reset(); if (!valid) { break; } } }
From source file:cpd3314.project.CPD3314ProjectTest.java
@Test public void testLimitAndOutput() throws Exception { System.out.println("main"); String[] args = { "-o=ten", "-limit=10" }; CPD3314Project.main(args);//from w w w . ja v a 2s. c o m File expected = FileSystems.getDefault().getPath("testFiles", "limit10.xml").toFile(); File result = new File("ten.xml"); assertTrue("Output File Doesn't Exist", result.exists()); assertXMLFilesEqual(expected, result); }
From source file:business.services.FileService.java
public InputStream getInputStream(File attachment) { if (attachment == null) { throw new FileNotFound(); }// w w w . j a va2s .c o m try { FileSystem fileSystem = FileSystems.getDefault(); Path path = fileSystem.getPath(uploadPath, attachment.getFilename()); InputStream input = new FileInputStream(path.toFile()); return input; } catch (IOException e) { log.error(e); throw new FileDownloadError(); } }
From source file:org.apache.tomee.jul.handler.rotating.ArchivingTest.java
@SuppressWarnings("unchecked") @Test//w w w . ja v a 2 s . c om public void logAndRotateAndPurge() throws Exception { clean("target/ArchivingTestPurge-" + format + "/logs"); final AtomicReference<String> today = new AtomicReference<>(); final Map<String, String> config = new HashMap<>(); // initial config today.set("2015-09-01"); config.put("filenamePattern", "target/ArchivingTestPurge-" + format + "/logs/test.%s.%d.log"); config.put("archiveDirectory", "target/ArchivingTestPurge-" + format + "/logs/archives"); config.put("archiveFormat", format); config.put("archiveOlderThan", "1 s"); config.put("purgeOlderThan", "2 s"); config.put("limit", "10 kilobytes"); config.put("level", "INFO"); config.put("dateCheckInterval", "1 second"); final LocalFileHandler handler = new LocalFileHandler() { @Override protected String currentDate() { return today.get(); } @Override protected String getProperty(final String name, final String defaultValue) { final String s = config.get(name.substring(name.lastIndexOf('.') + 1)); return s != null ? s : defaultValue; } }; final String string10chars = "abcdefghij"; final int iterations = 950; for (int i = 0; i < iterations; i++) { handler.publish(new LogRecord(Level.INFO, string10chars)); } today.set("2015-09-02"); try { Thread.sleep(2000); } catch (final InterruptedException e) { Thread.interrupted(); } final File logArchive = new File( "target/ArchivingTestPurge-" + format + "/logs/archives/test.2015-09-01.0.log." + format); final File parentFile = logArchive.getParentFile(); if (!parentFile.exists() && !parentFile.mkdirs()) { Assert.fail("Unable to create: " + parentFile); } final Path dir = parentFile.toPath(); final WatchService watcher = FileSystems.getDefault().newWatchService(); final WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY); latch.set(new CountDownLatch(1)); watch(key); handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the archiving assertTrue("Failed to get archived log", latch.get().await(20, TimeUnit.SECONDS)); final WatchEvent<?> watchEvent = lastEvent.get(); assertTrue(StandardWatchEventKinds.ENTRY_CREATE.equals(watchEvent.kind()) || StandardWatchEventKinds.ENTRY_MODIFY.equals(watchEvent.kind())); final WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent; final String io = ev.context().toString(); assertTrue(io.startsWith("test.2015-09-01.") && io.endsWith(format)); today.set("2015-09-03"); try { Thread.sleep(2500); } catch (final InterruptedException e) { Thread.interrupted(); } handler.publish(new LogRecord(Level.INFO, string10chars)); // will trigger the purging handler.close(); withRetry(10, 2, new Runnable() { @Override public void run() { assertFalse(logArchive.getAbsolutePath() + " was purged", logArchive.exists()); } }); }
From source file:com.yahoo.pulsar.zookeeper.LocalBookkeeperEnsemble.java
private void runBookies(ServerConfiguration baseConf) throws Exception { LOG.info("Starting Bookie(s)"); // Create Bookie Servers (B1, B2, B3) bs = new BookieServer[numberOfBookies]; bsConfs = new ServerConfiguration[numberOfBookies]; statsProviders = new StatsProvider[numberOfBookies]; for (int i = 0; i < numberOfBookies; i++) { File bkDataDir = isNotBlank(bkDataDirName) ? Files.createDirectories(Paths.get(bkDataDirName + Integer.toString(i))).toFile() : Files.createTempDirectory("bk" + Integer.toString(i) + "test").toFile(); if (this.clearOldData) { cleanDirectory(bkDataDir);/*from w w w . j av a 2 s .c o m*/ } bsConfs[i] = new ServerConfiguration(baseConf); // override settings bsConfs[i].setBookiePort(initialPort + i); bsConfs[i].setZkServers("127.0.0.1:" + ZooKeeperDefaultPort); bsConfs[i].setJournalDirName(bkDataDir.getPath()); bsConfs[i].setLedgerDirNames(new String[] { bkDataDir.getPath() }); bsConfs[i].setAllowLoopback(true); bsConfs[i].setGcWaitTime(60000); String statsFilePath = FileSystems.getDefault() .getPath(bkDataDir.getAbsolutePath(), "bookie-stats.json").toString(); // Initialize Stats Provider statsProviders[i] = new DataSketchesMetricsProvider(); bsConfs[i].setProperty("dataSketchesMetricsJsonFileReporter", statsFilePath); statsProviders[i].start(bsConfs[i]); StatsLogger statsLogger = statsProviders[i].getStatsLogger(""); bs[i] = new BookieServer(bsConfs[i], statsLogger); bs[i].start(); LOG.debug("Local BK[{}] started (port: {}, data_directory: {})", i, initialPort + i, bkDataDir.getAbsolutePath()); } }