List of usage examples for java.nio.file FileSystems getDefault
public static FileSystem getDefault()
From source file:uk.ac.ebi.interpro.scan.jms.main.AbstractI5Runner.java
/** * Check if a specified path exists and is readable. * @param path The full file or directory path under review (e.g. "/tmp/test_proteins.fasta") * @param checkParent Do we just check the parent path? (e.g. "/tmp") * @param checkWriteable Should we also check that the path or parent path can be written to? * @param option The user input {@link I5Option} this path relates to (or null if not applicable) * @return True if the checks succeed, otherwise false (although the system will exit if a {@link I5Option} check fails) *//*from www . ja v a 2 s.co m*/ protected static boolean checkPathExistence(final String path, final boolean checkParent, final boolean checkWriteable, final I5Option option) { String pathToCheck = path; if (checkParent) { pathToCheck = path.substring(0, path.lastIndexOf(File.separator)); } Path p = FileSystems.getDefault().getPath(pathToCheck); boolean exists = Files.isReadable(p); if (option != null && !exists) { System.out.println("For the (-" + option.getShortOpt() + ") option you specified a location which doesn't exist or is not readable:"); System.out.println(path); System.exit(2); } if (exists && checkWriteable) { boolean writable = Files.isWritable(p); if (option != null && !writable) { System.out.println("For the (-" + option.getShortOpt() + ") option you specified a location which is not writable:"); System.out.println(path); System.exit(2); } return writable; } return exists; }
From source file:eu.edisonproject.rest.FolderWatcherRunnable.java
@Override public void run() { final Path path = FileSystems.getDefault().getPath(dir); try (final WatchService watchService = FileSystems.getDefault().newWatchService()) { final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); while (true) { final WatchKey wk = watchService.take(); for (WatchEvent<?> event : wk.pollEvents()) { final Path changed = (Path) event.context(); executeClassification(new File(dir + File.separator + changed)); }/*from w ww .jav a 2 s .co m*/ // reset the key boolean valid = wk.reset(); if (!valid) { Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.WARNING, "Key has been unregisterede"); } } } catch (IOException ex) { Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:io.stallion.dataAccess.file.TomlPersister.java
@Override public List fetchAll() { File target = new File(Settings.instance().getTargetFolder()); if (!target.isDirectory()) { if (getItemController().isWritable()) { target.mkdirs();//from www. j av a 2 s . c o m } else { throw new ConfigException(String.format( "The TOML bucket %s (path %s) is read-only, but does not exist in the file system. Either create the folder, make it writable, or remove it from the configuration.", getItemController().getBucket(), getBucketFolderPath())); } } TreeVisitor visitor = new TreeVisitor(); Path folderPath = FileSystems.getDefault().getPath(getBucketFolderPath()); try { Files.walkFileTree(folderPath, visitor); } catch (IOException e) { throw new RuntimeException(e); } List<Object> objects = new ArrayList<>(); for (Path path : visitor.getPaths()) { if (!path.toString().toLowerCase().endsWith(".toml")) { continue; } if (path.toString().contains(".#")) { continue; } Log.fine("Load from toml file " + path); if (isManyItemsPerFile()) { try { Log.finer("Load toml path {0} and items {1}", path.toString(), getItemArrayName()); String toml = FileUtils.readFileToString(new File(path.toString()), UTF8); Toml t = new Toml().read(toml); List<HashMap> models = t.getList(getItemArrayName()); long x = 0; for (Map m : models) { x++; T o = getModelClass().newInstance(); for (Object key : m.keySet()) { PropertyUtils.setProperty(o, key.toString(), m.get(key)); } Log.info("add item {0}", ((MappedModel) o).get("title")); if (empty(o.getId())) { o.setId(x); } handleFetchOne(o); objects.add(o); } } catch (IOException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } } else { objects.add(fetchOne(path.toString())); } } return objects; }
From source file:org.ng200.openolympus.services.StorageService.java
public Path createSolutionDirectory() throws IOException { final UUID uuid = UUID.randomUUID(); final Path dir = FileSystems.getDefault().getPath(this.storagePath, "solutions", uuid.toString() + "_" + System.currentTimeMillis()); FileAccess.createDirectories(dir);/*from w w w. jav a 2s .c o m*/ return dir; }
From source file:se.trixon.mapollage.profile.ProfileSource.java
@Override public boolean isValid() { try {/* w w w. j a va 2 s . co m*/ mPathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + mFilePattern); } catch (Exception e) { addValidationError("invalid file pattern: " + mFilePattern); } return true; }
From source file:repast.simphony.R.RWizard.java
public String[] getExecutionCommand() { List<String> commands = new ArrayList<String>(); // NOTE: the LOGFILE and DELIMMTER args are processed by our .Rprofile. if (SystemUtils.IS_OS_WINDOWS) { //commands.add("R_PROFILE_USER=" + prepFileNameForR(getRHome())); //commands.add("&"); envVars.put("R_PROFILE_USER", prepFileNameForR(getRHome()) + ".Rprofile"); //commands.add("SET R_PROFILE_USER=" + prepFileNameForR(getRHome())); //builder.append("& "); List<FileDataSink> outputters = fileStep.getChosenOutputters(); // For each outputter, define the log file and delimitter for (int i = 0; i < outputters.size(); i++) { Path out = outputters.get(i).getFile().toPath().normalize().toAbsolutePath(); Path cwd = FileSystems.getDefault().getPath(".").normalize().toAbsolutePath(); //System.out.println(out); //System.out.println(cwd); String sout = out.toString(); if (out.startsWith(cwd)) { sout = sout.substring(cwd.toString().length() + 1); }//ww w . j a v a2 s . c om envVars.put("LOG_FILE" + i, sout.replace("\\", "/")); Formatter formatter = outputters.get(i).getFormatter(); if (outputters.get(i).getFormat() != FormatType.TABULAR) { LOG.warn("When invoking R, an outputter without a delimited formatter " + "was found. R can only be invoked on output files with using a delimiter."); break; } String delimiter = formatter.getDelimiter(); envVars.put("DELIMITER" + i, delimiter); } commands.add(getInstallHome()); } else if (SystemUtils.IS_OS_MAC) { List<FileDataSink> outputters = fileStep.getChosenOutputters(); List<String> files = new ArrayList<String>(); List<String> delims = new ArrayList<String>(); String cwd = new File(".").getAbsolutePath(); for (int i = 0; i < outputters.size(); i++) { Formatter formatter = outputters.get(i).getFormatter(); if (outputters.get(i).getFormat() != FormatType.TABULAR) { LOG.warn("When invoking R, an outputter without a delimited formatter " + "was found. R can only be invoked on output files with using a delimiter."); break; } delims.add(formatter.getDelimiter()); String fileName = outputters.get(i).getFile().getAbsolutePath(); File f = new File(fileName); if (fileName.startsWith("/")) { files.add(fileName); } else { if (f.exists()) { files.add("./" + fileName); } else { // assume its relative to the current working directory files.add(cwd + "/" + fileName); } } } for (int i = 0; i < files.size(); i++) { envVars.put("LOG_FILE" + i, files.get(i)); envVars.put("DELIMITER" + i, delims.get(i)); } // this should ceate the .RProfile file getRHome(); envVars.put("R_PROFILE_USER", cwd + "/RHome/.RProfile"); commands.add("open"); commands.add("-n"); commands.add(getInstallHome()); commands.add(cwd); } else { // TODO linux command } return commands.toArray(new String[commands.size()]); }
From source file:com.zergiu.tvman.controllers.FSBrowseController.java
/** * @param children//from w ww.jav a 2s . c o m */ private void addRootPaths(Map<String, String> children) { log.debug("reading root files "); Iterable<Path> roots = FileSystems.getDefault().getRootDirectories(); for (Path f : roots) { children.put(f.toString(), f.toString()); } }
From source file:desktopsearch.WatchDir.java
/** * Creates a WatchService and registers the given directory *///from w w w . jav a 2s . c o m WatchDir(Path dir, boolean recursive, Connection connection, Statement statement) throws IOException { this.watcher = FileSystems.getDefault().newWatchService(); this.keys = new HashMap<WatchKey, Path>(); this.recursive = recursive; this.connection = connection; this.statement = statement; if (recursive) { System.out.format("Scanning %s ...\n", dir); registerAll(dir); System.out.println("Done."); } else { register(dir); } // enable trace after initial registration this.trace = true; }
From source file:org.crosswalk.eclipse.cdt.helpers.ExportHelper.java
public static int generateDebPackage(IProject project, DebPackageParameters packageparameters) throws IOException { int runResult = 0; StringBuilder cmd = new StringBuilder(); final Map<String, String> env = new HashMap<String, String>(System.getenv()); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); Path sourceManifestFile = FileSystems.getDefault().getPath(project.getLocation().toString(), "manifest.json"); //copy the manifest.json file String manifestLocation = project.getLocation().toString() + File.separator + "manifest.json"; JSONObject manifest = new JSONObject(new JSONTokener( //get the manifest file new FileReader(manifestLocation))); String packageName = CdtConstants.CROSSWALK_PACKAGE_PREFIX + manifest.get("name"); ProjectHelper projectHelper = new ProjectHelper(); projectHelper.resourceHandler(root.getLocation().toString()); String sourceFolder = project.getLocation().toString(); String targetFolder = sourceFolder + File.separator + ".tmp" + File.separator + packageName + File.separator + "app"; Path targetManifestFile = FileSystems.getDefault().getPath(targetFolder, "manifest.json"); Files.copy(sourceManifestFile, targetManifestFile, REPLACE_EXISTING); //copy the icon file if (NewProjectWizardState.useDefaultIcon) { //do nothing,since we copied the icon from org.crosswalk.appName folder } else { //user-specified icon.We have to delete the default icons and copy the user-specified icon String iconName = manifest.getJSONArray("icons").getJSONObject(2).get("src").toString(); Path sourceIconFile = FileSystems.getDefault().getPath(sourceFolder, iconName); Path targetIconFile = FileSystems.getDefault().getPath(targetFolder, iconName); Path defaultIconFile1 = FileSystems.getDefault().getPath(targetFolder, "icon-48.png"); Path defaultIconFile2 = FileSystems.getDefault().getPath(targetFolder, "icon.png"); Files.copy(sourceIconFile, targetIconFile, REPLACE_EXISTING); Files.delete(defaultIconFile1); Files.delete(defaultIconFile2); }/*w w w . j a v a 2 s. c om*/ //copy the launch file. //We must copy this file no matter whether the name is index.html since user may change it after setting it in manifestSettingPage if (NewProjectWizardState.isPackagedProject) { String startUrl = manifest.get("start_url").toString(); Path sourceStartUrlFile = FileSystems.getDefault().getPath(sourceFolder, startUrl); Path targetStartUrlFile = FileSystems.getDefault().getPath(targetFolder, startUrl); Files.copy(sourceStartUrlFile, targetStartUrlFile, REPLACE_EXISTING); } File buildDir = new File( project.getLocation().toString() + File.separator + ".tmp" + File.separator + packageName); cmd.append("crosswalk-app build"); pMonitor.worked(1); Process process = Runtime.getRuntime().exec(cmd.toString(), mapToStringArray(env), buildDir);//execute cmd in specific targetFolder try { process.waitFor(); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //copy the deb package to user-specified path String debPackageName = packageparameters.appName + "_" + packageparameters.appVersion + "-1_" + packageparameters.supportedArch + ".deb"; Path source = FileSystems.getDefault().getPath(buildDir.toString(), "pkg", debPackageName); Path target = FileSystems.getDefault().getPath(packageparameters.targetFolder, debPackageName); Files.copy(source, target, REPLACE_EXISTING); try { for (int i = 0; i < 20; i++) { pMonitor.worked(1); Thread.sleep(10); } } catch (InterruptedException e) { } // redirect the error and input stream try { exportStream(process.getErrorStream(), System.err); exportStream(process.getInputStream(), System.out); } catch (Exception e) { e.printStackTrace(); } try { runResult = process.waitFor(); } catch (InterruptedException e) { e.printStackTrace(); CdtPluginLog.logError("Error when involking package tool.", e); } return runResult; }
From source file:com.lukakama.serviio.watchservice.watcher.WatcherRunnable.java
private void initialize() throws InterruptedException { try {// ww w . ja v a 2 s . c om watcher = FileSystems.getDefault().newWatchService(); log.debug("WatchService implementation: {}", watcher.getClass().getName()); } catch (IOException e) { throw new RuntimeException( "Unable to retrieve a WatchService instance. Monitoring can't be used in the current JVM.", e); } // Start monitoring repositories folder. LibraryManager libraryManager = LibraryManager.getInstance(); List<Repository> repositories = RepositoryService.getAllRepositories(); for (Repository repository : repositories) { checkInterrupted(); if (libraryManager.isRepositoryUpdatable(repository)) { Path path = repository.getFolder().toPath(); if (isPathFullyAccessible(path)) { log.info("Watching root path: {}", path); checkNewPath(path); } else { log.warn("Skipping unaccessible root path: {}", path); } } } }