List of usage examples for java.nio.file FileSystems getDefault
public static FileSystem getDefault()
From source file:MonitorSaurausRex.MainMenu.java
public boolean MonitorDirectory() { Path directory = Paths.get("C:/Users/" + user + "/Documents/"); try {//w ww.j av a 2 s . c om WatchService fileSystemWatchService = FileSystems.getDefault().newWatchService(); WatchKey watchKey = directory.register(fileSystemWatchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); testTimer = new TimerTask() { @Override public void run() { checkPause = true; test = changeCheck(); if (test) { testTimer.cancel(); System.out.println("Quaritnen sucsessfully activates"); } } }; Timer timer = new Timer(); timer.schedule(testTimer, 0, 1000); while (true) { WatchKey watchKeyActual = fileSystemWatchService.take(); for (WatchEvent<?> event : watchKeyActual.pollEvents()) { WatchEvent.Kind<?> eventKind = event.kind(); if (eventKind == StandardWatchEventKinds.OVERFLOW) { continue; } WatchEvent<Path> eventPath = (WatchEvent<Path>) event; Path fileName = eventPath.context(); //timerCheck(); ????? //http://stackoverflow.com/questions/4044726/how-to-set-a-timer-in-java // boolean test = false; if (checkPause == false) { checkPause = true; } else { ChangeCounter++; System.out.println("Event " + eventKind + " occurred on " + fileName); } if (test) break; } boolean isReset = watchKeyActual.reset(); if (!isReset || test) { break; } } } catch (IOException | InterruptedException ioe) { } return true; /// EXIT METHOD }
From source file:gedi.util.FileUtils.java
public static String[] find(String path, String glob, boolean stripPath) throws IOException { if (!path.endsWith("/")) path = path + "/"; String cpath = path;/*www . ja v a2 s .com*/ ArrayList<String> re = new ArrayList<String>(); PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + path + glob); Files.find(Paths.get(path), 9999, (p, per) -> { return matcher.matches(p); }, FileVisitOption.FOLLOW_LINKS).forEach(f -> { String file = f.toString(); if (stripPath && file.startsWith(cpath)) file = file.substring(cpath.length()); re.add(file); }); return re.toArray(new String[0]); }
From source file:com.team3637.service.TagServiceMySQLImpl.java
@Override public void importCSV(String inputFile) { try {//from w ww . j a v a 2 s. com 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) { Tag tag = new Tag(); tag.setId(Integer.parseInt(record.get(0))); tag.setTag(record.get(1)); tag.setType(record.get(2)); tag.setCounter(record.get(3)); tag.setInTable(record.get(4).equals("1") || record.get(4).toLowerCase().equals("true")); tag.setRequiesEval(record.get(5).equals("1") || record.get(5).toLowerCase().equals("true")); tag.setExpression(record.get(6).replace("\n", "")); if (checkForTag(tag)) update(tag); else create(tag); } } catch (IOException e) { e.printStackTrace(); } }
From source file:de.cebitec.readXplorer.differentialExpression.plot.DeSeqGraphicsTopComponent.java
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed ReadXplorerFileChooser fc = new ReadXplorerFileChooser(new String[] { "svg" }, "svg") { private static final long serialVersionUID = 1L; @Override/*ww w . java 2s .co m*/ public void save(String fileLocation) { ProgressHandle progressHandle = ProgressHandleFactory .createHandle("Save plot to svg file: " + fileLocation); Path to = FileSystems.getDefault().getPath(fileLocation, ""); DeSeqAnalysisHandler.Plot selectedPlot = (DeSeqAnalysisHandler.Plot) plotType.getSelectedItem(); if (selectedPlot == DeSeqAnalysisHandler.Plot.MAplot) { saveToSVG(fileLocation); } else { Path from = currentlyDisplayed.toPath(); try { Path outputFile = Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING); messages.setText("SVG image saved to " + outputFile.toString()); } catch (IOException ex) { Date currentTimestamp = new Timestamp(Calendar.getInstance().getTime().getTime()); Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "{0}: " + ex.getMessage(), currentTimestamp); JOptionPane.showMessageDialog(null, ex.getMessage(), "Could not write to file.", JOptionPane.WARNING_MESSAGE); } finally { progressHandle.switchToDeterminate(100); progressHandle.finish(); } } } @Override public void open(String fileLocation) { } }; fc.openFileChooser(ReadXplorerFileChooser.SAVE_DIALOG); }
From source file:org.openhab.binding.proserv.internal.ProservBinding.java
@Override public synchronized void internalReceiveCommand(String itemName, Command command) { logger.debug("proServ received command for itemName:{}, command:{}", itemName, command.toString()); String pathLogsDir = ConfigDispatcher.getConfigFolder() + File.separator + ".." + File.separator + "logs"; Path pathBackupRrd = FileSystems.getDefault().getPath(pathLogsDir + File.separator + "BackupRrd.zip") .toAbsolutePath();/*w w w .j a v a 2 s .c o m*/ Path pathZippedCsvFiles = FileSystems.getDefault() .getPath(pathLogsDir + File.separator + "ZippedCsvFiles.zip").toAbsolutePath(); if (itemName.equals("ProservTest") && command.toString().equals("START")) { eventPublisher.postUpdate(itemName, new StringType("PROCESSING")); try { Thread.sleep(3000); } catch (InterruptedException ie) { } //eventPublisher.postUpdate(itemName, new StringType("SUCCESS")); eventPublisher.postUpdate(itemName, new StringType( "FAILED:Please see the logfile for details. This is a very long message which includes a log gfile path : C:\\Users\\jeka\\Documents\\OpenHAB\\source\\openhab-fork\\distribution\\openhabhome\\logs")); } //http://localhost:8080/CMD?ProservBackupResetRrd=START //http://localhost:8080/CMD?ProservBackupRrd=START if (itemName.equals("ProservBackupResetRrd") && command.toString().equals("START") || itemName.equals("ProservBackupRrd") && command.toString().equals("START")) { try { // save a copy of all rrd files in BackupRrd.zip Date now = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String zipFolderName = simpleDateFormat.format(now); ProservLogfileProvider proservLogfileProvider = new ProservLogfileProvider(); File directory = new File(ConfigDispatcher.getConfigFolder() + File.separator + ".." + File.separator + "etc" + File.separator + "rrd4j"); for (File f : directory.listFiles()) { if (f.getName().startsWith("itemProServLog")) { proservLogfileProvider.createZip(pathBackupRrd, f.toPath(), zipFolderName + "/" + f.getName()); } } // clean up garbage from java.nio File directoryLogs = new File( ConfigDispatcher.getConfigFolder() + File.separator + ".." + File.separator + "logs"); for (File f : directoryLogs.listFiles()) if (f.getName().startsWith("zipfstmp")) f.delete(); // delete all rrd files if (itemName.equals("ProservBackupResetRrd")) { int failedToDeleteFiles = 0; for (File f : directory.listFiles()) { if (f.getName().startsWith("itemProServLog")) { int count = 0; while (!f.delete()) { System.gc(); Thread.sleep(300); if (++count > 10) { failedToDeleteFiles++; break; } } } } if (failedToDeleteFiles > 0) { eventPublisher.postUpdate(itemName, new StringType( "FAILED:Failed to delete all history data files, but the backup is done. Number of files that couldn't be deleted: " + new Integer(failedToDeleteFiles).toString())); } else { eventPublisher.postUpdate(itemName, new StringType("SUCCESS")); } } else { eventPublisher.postUpdate(itemName, new StringType("SUCCESS")); } } catch (Throwable e) { logger.error("ProservBackupResetRrd exception: {}", e.toString()); eventPublisher.postUpdate(itemName, new StringType("FAILED:" + e.toString())); } } //http://localhost:8080/CMD?ProservSendRrdBackup=START else if (itemName.equals("ProservSendRrdBackup") && command.toString().equals("START")) { File f = new File(pathBackupRrd.toString()); if (f.exists() && !f.isDirectory()) { if (Mail.sendMail(mailTo, mailSubject, mailContent, pathBackupRrd.toUri().toString())) { eventPublisher.postUpdate(itemName, new StringType("SUCCESS")); } else { eventPublisher.postUpdate(itemName, new StringType("FAILED:" + Mail.getLastError())); } } else { eventPublisher.postUpdate(itemName, new StringType("FAILED:The history data file is missing, please save history data!")); } } //http://localhost:8080/CMD?ProservRestart=START else if (itemName.equals("ProservRestart") && command.toString().equals("START")) { try { ExecUtil.executeCommandLine(shellRestartCommand); eventPublisher.postUpdate(itemName, new StringType("SUCCESS")); } catch (Throwable e) { eventPublisher.postUpdate(itemName, new StringType("FAILED:" + e.toString())); } } //http://localhost:8080/CMD?ProservSendCsvFiles=START else if (itemName.equals("ProservSendCsvFiles") && command.toString().equals("START")) { File f = new File(pathZippedCsvFiles.toString()); if (mailTo.isEmpty()) { eventPublisher.postUpdate(itemName, new StringType("FAILED:The email address is missing, please configure the email address!")); } else if (f.exists() && !f.isDirectory()) { if (Mail.sendMail(mailTo, mailSubject, mailContent, pathZippedCsvFiles.toUri().toString())) { eventPublisher.postUpdate(itemName, new StringType("SUCCESS")); } else { eventPublisher.postUpdate(itemName, new StringType("FAILED:" + Mail.getLastError())); } } else { eventPublisher.postUpdate(itemName, new StringType("FAILED:The CSV data file is missing, please export csv data file!")); } } //http://localhost:8080/CMD?ProservLanguage=de else if (itemName.equals("ProservLanguage")) { boolean retVal = true; if (isSupportedLanguage(command.toString())) { ProservBinding.language = command.toString(); ProservData.updateLangDirJsFile(language); retVal = ProservData.writeConfigData("proserv:language", ProservBinding.language); } if (retVal == false) eventPublisher.postUpdate(itemName, new StringType("FAILED:Failed to save the language setting. Please try later!")); else eventPublisher.postUpdate(itemName, new StringType(ProservBinding.language)); } //http://localhost:8080/CMD?ProservEmail=aa@bb.cc else if (itemName.equals("ProservEmail")) { if (command.toString().equals("?")) { eventPublisher.postUpdate(itemName, new StringType(ProservBinding.mailTo)); } else { ProservBinding.mailTo = command.toString(); if (ProservData.writeConfigData("proserv:mailto", ProservBinding.mailTo)) { eventPublisher.postUpdate(itemName, new StringType(ProservBinding.mailTo)); } else { eventPublisher.postUpdate(itemName, new StringType("FAILED:Failed to save the new setting, please try later!")); } // Test Android notifications: //NotifyMyAndroid.notifyMyAndroid("The event", "the message"); } } //http://localhost:8080/CMD?ProservIP=192.168.2.1 else if (itemName.equals("ProservIP")) { if (command.toString().equals("?")) { eventPublisher.postUpdate(itemName, new StringType(ProservBinding.ip)); } else { ProservBinding.ip = command.toString(); ProservData.updateProservxJsonForRealknx(ProservBinding.ip); if (ProservData.writeConfigData("proserv:ip", ProservBinding.ip)) { eventPublisher.postUpdate(itemName, new StringType(ProservBinding.ip)); } else { eventPublisher.postUpdate(itemName, new StringType("FAILED:Failed to save the new setting, please try later!")); } } } //http://localhost:8080/CMD?ProservCronJobs=DPxx:true:0:0 0 8 ? * 2-6:0 0 21 ? * 1,7;DPyy:true:1:0 0 8 ? * 2-6:0 0 21 ? * 1,7; else if (itemName.equals("ProservCronJobs")) { if (proservData == null) { eventPublisher.postUpdate(itemName, new StringType( "FAILED: unable to communicate with proserv, please check the communcation link (e.g the IP address)!")); return; } if (proservCronJobs.add(command.toString())) { proservData.updateSchedulerHtmlFile(proservCronJobs); proservData.updateProservRulesFile(proservCronJobs); eventPublisher.postUpdate(itemName, new StringType("SUCCESS")); } else { eventPublisher.postUpdate(itemName, new StringType("FAILED:Failed to save the new setting, please try later!")); } } else { // http://192.168.1.13:8081/CMD?dpID772=OFF // GET after to test result: http://192.168.1.13:8081/rest/items/dpID772/state State s = command.toString().equals("ON") ? OnOffType.ON : OnOffType.OFF; internalReceiveUpdate(itemName, s); } }
From source file:it.units.malelab.ege.util.DUMapper.java
private static double[][][] getGomeaData(String baseDir, String fileNamePattern, int generations, int genotypeSize) throws IOException { double[][] usages = new double[generations][]; Set<Character>[] domains = new Set[genotypeSize]; Multiset<Character>[][] symbols = new Multiset[generations][]; for (int i = 0; i < genotypeSize; i++) { domains[i] = new HashSet<>(); }//from w w w .java2s . c o m for (int g = 0; g < generations; g++) { symbols[g] = new Multiset[genotypeSize]; for (int i = 0; i < genotypeSize; i++) { symbols[g][i] = HashMultiset.create(); } usages[g] = new double[genotypeSize]; BufferedReader reader = Files.newBufferedReader( FileSystems.getDefault().getPath(baseDir, String.format(fileNamePattern, g))); String line; int populationSize = 0; while ((line = reader.readLine()) != null) { populationSize = populationSize + 1; String[] pieces = line.split(" "); String genotype = pieces[0]; for (int i = 0; i < genotypeSize; i++) { domains[i].add(genotype.charAt(i)); symbols[g][i].add(genotype.charAt(i)); } for (int i = 2; i < pieces.length; i++) { int intronIndex = Integer.parseInt(pieces[i]); usages[g][intronIndex] = usages[g][intronIndex] + 1; } } for (int i = 0; i < genotypeSize; i++) { usages[g][i] = (populationSize - usages[g][i]) / populationSize; } reader.close(); } double[][] diversities = new double[generations][]; for (int g = 0; g < generations; g++) { diversities[g] = new double[genotypeSize]; for (int i = 0; i < genotypeSize; i++) { diversities[g][i] = Utils.multisetDiversity(symbols[g][i], domains[i]); } } return new double[][][] { diversities, usages }; }
From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java
public boolean createCacheFileProteomics(String filePath) { boolean isSuccess = false; JSONObject jsonData = new JSONObject(); JSONObject data;//from w ww.j a va 2s. c o m // from WP // data data = read(baseURL + "/tab/dlp-proteomics-data/?req=passphrase"); if (data != null) { jsonData.put("data", data); } // tools data = read(baseURL + "/tab/dlp-proteomics-tools/?req=passphrase"); if (data != null) { jsonData.put("tools", data); } // process data = read(baseURL + "/tab/dlp-proteomics-process/?req=passphrase"); if (data != null) { jsonData.put("process", data); } // download data = read(baseURL + "/tab/dlp-proteomics-download/?req=passphrase"); if (data != null) { jsonData.put("download", 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.polago.deployconf.DeployConfRunner.java
/** * Apply the given DeploymentConfig to the source and create the destination. * * @param config the DeploymentConfig to apply * @param source the input file/* w w w . j av a 2s.co m*/ * @param destination the destination file * @throws Exception indicating processing error */ private void apply(DeploymentConfig config, String source, String destination) throws Exception { FileSystem fs = FileSystems.getDefault(); Path sourceFile = fs.getPath(source); Path destFile = fs.getPath(destination); InputStream srcStream = null; OutputStream destStream = null; try { srcStream = Files.newInputStream(sourceFile); destStream = Files.newOutputStream(destFile); config.apply(srcStream, destStream, getDeploymentTemplatePath()); } finally { if (srcStream != null) { srcStream.close(); } if (destStream != null) { destStream.close(); } } }
From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java
public boolean createCacheFilePPInteractions(String filePath) { boolean isSuccess = false; JSONObject jsonData = new JSONObject(); JSONObject data;//from w ww . j av a2s . com // from WP // data data = read(baseURL + "/tab/dlp-ppinteractions-data/?req=passphrase"); if (data != null) { jsonData.put("data", data); } // tools data = read(baseURL + "/tab/dlp-ppinteractions-tools/?req=passphrase"); if (data != null) { jsonData.put("tools", data); } // process data = read(baseURL + "/tab/dlp-ppinteractions-process/?req=passphrase"); if (data != null) { jsonData.put("process", data); } // download data = read(baseURL + "/tab/dlp-ppinteractions-download/?req=passphrase"); if (data != null) { jsonData.put("download", 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:it.units.malelab.ege.util.DUMapper.java
private static double[][][] getNeatData(String baseDir, String fileNamePattern, int generations) throws IOException { List<List<Map<Integer, Pair<Double, Double>>>> data = new ArrayList<>(); int maxInnovationNumber = 0; for (int g = 0; g < generations; g++) { List<Map<Integer, Pair<Double, Double>>> currentPopulation = new ArrayList<>(); BufferedReader reader = Files.newBufferedReader( FileSystems.getDefault().getPath(baseDir, String.format(fileNamePattern, g + 1))); String line;//from w w w. j av a 2 s.co m boolean isInPopulation = false; Map<Integer, Pair<Double, Double>> currentIndividual = null; while ((line = reader.readLine()) != null) { if (line.equals("[NEAT-POPULATION:SPECIES]")) { isInPopulation = true; continue; } if (!isInPopulation) { continue; } if (line.startsWith("\"g\"")) { if (currentIndividual != null) { //save current individual currentPopulation.add(currentIndividual); } currentIndividual = new HashMap<>(); } if (line.startsWith("\"n\"") || line.startsWith("\"l\"")) { String[] pieces = line.split(","); int innovationNumber = Integer.parseInt(pieces[pieces.length - 1]); maxInnovationNumber = Math.max(innovationNumber, maxInnovationNumber); double used = 1; double value = 1; if (line.startsWith("\"l\"")) { value = Double.parseDouble(pieces[pieces.length - 2]); used = Double.parseDouble(pieces[2]); } currentIndividual.put(innovationNumber, new Pair<>(used, value)); } } reader.close(); data.add(currentPopulation); } //populate arrays double[][] usages = new double[generations][]; double[][] diversities = new double[generations][]; for (int g = 0; g < generations; g++) { usages[g] = new double[maxInnovationNumber]; diversities[g] = new double[maxInnovationNumber]; List<Map<Integer, Pair<Double, Double>>> currentPopulation = data.get(g); //populate usages double[][] values = new double[maxInnovationNumber][]; double[] localUsages = new double[maxInnovationNumber]; for (int i = 0; i < maxInnovationNumber; i++) { values[i] = new double[currentPopulation.size()]; } for (int p = 0; p < currentPopulation.size(); p++) { for (int i = 0; i < maxInnovationNumber; i++) { double value = 0; double used = 0; if (currentPopulation.get(p).containsKey(i)) { Pair<Double, Double> pair = currentPopulation.get(p).get(i); value = pair.getSecond(); used = pair.getFirst(); } values[i][p] = value; localUsages[i] = localUsages[i] + used; } } for (int i = 0; i < maxInnovationNumber; i++) { usages[g][i] = localUsages[i] / (double) currentPopulation.size(); diversities[g][i] = normalizedVar(values[i]); } } return new double[][][] { diversities, usages }; }