List of usage examples for java.nio.file Files walk
public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException
From source file:squash.deployment.lambdas.utils.FileUtils.java
/** * Adds revving suffix to all filenames beneath a folder. * //ww w . j a v a2 s .com * <p>Adds revving suffix to all filenames beneath a folder, recursing into subfolders. * Only js and css files are revved. * * @param suffix the suffix to add to all filenames. * @param startFolder the folder at root of tree within which to suffix files * @param logger a CloudwatchLogs logger. * @throws IOException */ public static void appendRevvingSuffix(String suffix, Path startFolder, LambdaLogger logger) throws IOException { Files.walk(startFolder, FileVisitOption.FOLLOW_LINKS).filter(Files::isRegularFile).forEach(path -> { File file = path.toFile(); if (file.isDirectory()) { return; } String absolutePath = file.getAbsolutePath(); String fileExtension = FilenameUtils.getExtension(absolutePath); if (!fileExtension.equals("js") && !fileExtension.equals("css")) { // We rev only js and css return; } String suffixedName = FilenameUtils.getBaseName(absolutePath) + "_" + suffix + "." + fileExtension; File suffixedFile = new File(file.getParentFile(), suffixedName); file.renameTo(suffixedFile); logger.log("Appended suffix to file: " + absolutePath + ", giving: " + suffixedFile.getAbsolutePath()); }); }
From source file:org.apache.gobblin.config.store.zip.ZipFileConfigStore.java
/** * Retrieves all the children of the given {@link ConfigKeyPath} using {@link Files#walk} to list files *///from www . ja v a 2s. c om @Override public Collection<ConfigKeyPath> getChildren(ConfigKeyPath configKey, String version) throws VersionDoesNotExistException { Preconditions.checkNotNull(configKey, "configKey cannot be null!"); Preconditions.checkArgument(version.equals(getCurrentVersion())); List<ConfigKeyPath> children = new ArrayList<>(); Path datasetDir = getDatasetDirForKey(configKey); try { if (!Files.exists(this.fs.getPath(datasetDir.toString()))) { return children; } Stream<Path> files = Files.walk(datasetDir, 1); for (Iterator<Path> it = files.iterator(); it.hasNext();) { Path path = it.next(); if (Files.isDirectory(path) && !path.equals(datasetDir)) { children.add(configKey .createChild(StringUtils.removeEnd(path.getName(path.getNameCount() - 1).toString(), SingleLinkedListConfigKeyPath.PATH_DELIMETER))); } } return children; } catch (IOException e) { throw new RuntimeException( String.format("Error while getting children for configKey: \"%s\"", configKey), e); } }
From source file:org.ballerinalang.composer.service.workspace.local.LocalFSWorkspace.java
@Override public void delete(String path, String type) throws IOException { Path ioPath = Paths.get(path); if (FOLDER_TYPE.equals(type)) { Files.walk(ioPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()).map(Path::toFile) .forEach(File::delete); } else {// www . ja v a2 s . co m Files.delete(ioPath); } }
From source file:com.ejie.uda.jsonI18nEditor.Editor.java
public void importResources(Path dir) { Stream<Path> filter; try {/* w w w . j a va 2 s. c o m*/ if (!closeCurrentSession()) { return; } if (Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) { reset(); resourcesDir = dir; filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path)); } else { reset(); // Se ha arrastrado un fichero de 18n individual, se debe de obtener los recursos relacionados con el bundle al que pertenece. Pattern.matches(BUNDLE_REGEX, dir.getFileName().toString()); Pattern regex = Pattern.compile(BUNDLE_REGEX); resourcesDir = dir.getParent(); inputFile = dir; Matcher regexMatcher = regex.matcher(dir.getFileName().toString()); if (regexMatcher.find()) { this.bundle = regexMatcher.group(1); filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path, this.bundle)); } else { showError(MessageBundle.get("resources.open.error.multiple")); return; } // Pattern.matches("BUNDLE_REGEX", dir.getFileName().toString()); // showError(MessageBundle.get("resources.open.error.multiple")); // return; } filter.forEach(path -> { try { Resource resource = Resources.read(path); setupResource(resource); } catch (Exception e) { e.printStackTrace(); showError(MessageBundle.get("resources.open.error.single", path.toString())); } }); List<String> recentDirs = settings.getListProperty("history"); recentDirs.remove(dir); recentDirs.add(dir.toString()); if (recentDirs.size() > 5) { recentDirs.remove(0); } settings.setProperty("history", recentDirs); editorMenu.setRecentItems(Lists.reverse(recentDirs)); Map<String, String> keys = Maps.newTreeMap(); resources.forEach(resource -> keys.putAll(resource.getTranslations())); // resources.forEach(resource -> { // // // // }); List<String> keyList = Lists.newArrayList(keys.keySet()); translationTree.setModel(new TranslationTreeModel(keyList)); updateUI(); // for (String key : keyList) { // boolean anyEmpty = false; // // for (Resource resource : resources) { // if (StringUtils.isBlank(resource.getTranslation(key))){ // anyEmpty = true; // } // } // // TranslationTreeModel model = (TranslationTreeModel) translationTree.getModel(); // TranslationTreeNode node = model.getNodeByKey(key); // // node // } // keyList.stream().filter(key -> { // // resources.stream().filter(resource -> { // return StringUtils.isNotBlank(resource.getTranslation(key)); // }); // return true; // }); } catch (IOException e) { e.printStackTrace(); showError(MessageBundle.get("resources.open.error.multiple")); } }
From source file:org.ballerinalang.composer.service.fs.LocalFileSystem.java
@Override public void delete(String path) throws IOException { Path ioPath = Paths.get(path); if (ioPath.toFile().isDirectory()) { Files.walk(ioPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()).map(Path::toFile) .forEach(File::delete); } else {//from w w w. ja v a 2 s. c o m Files.delete(ioPath); } }
From source file:com.willwinder.universalgcodesender.utils.FirmwareUtils.java
/** * Copy any missing files from the the jar's resources/firmware_config/ dir * into the settings/firmware_config dir. *//* w ww .ja v a 2s.com*/ public synchronized static void initialize() { System.out.println("Initializing firmware... ..."); File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME); // Create directory if it's missing. if (!firmwareConfig.exists()) { firmwareConfig.mkdirs(); } FileSystem fileSystem = null; // Copy firmware config files. try { final String dir = "/resources/firmware_config/"; URI location = FirmwareUtils.class.getResource(dir).toURI(); Path myPath; if (location.getScheme().equals("jar")) { try { // In case the filesystem already exists. fileSystem = FileSystems.getFileSystem(location); } catch (FileSystemNotFoundException e) { // Otherwise create the new filesystem. fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap()); } myPath = fileSystem.getPath(dir); } else { myPath = Paths.get(location); } Stream<Path> files = Files.walk(myPath, 1); for (Path path : (Iterable<Path>) () -> files.iterator()) { System.out.println(path); final String name = path.getFileName().toString(); File fwConfig = new File(firmwareConfig, name); if (name.endsWith(".json")) { boolean copyFile = !fwConfig.exists(); ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path)); // If the file is outdated... ask the user (once). if (fwConfig.exists()) { ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig)); boolean outOfDate = current.getVersion() < jarSetting.getVersion(); if (outOfDate && !userNotified && !overwriteOldFiles) { int result = NarrowOptionPane.showNarrowConfirmDialog(200, Localization.getString("settings.file.outOfDate.message"), Localization.getString("settings.file.outOfDate.title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); overwriteOldFiles = result == JOptionPane.OK_OPTION; userNotified = true; } if (overwriteOldFiles) { copyFile = true; jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom; } } // Copy file from jar to firmware_config directory. if (copyFile) { try { save(fwConfig, jarSetting); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } } } } } catch (Exception ex) { String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"), ex.getLocalizedMessage()); GUIHelpers.displayErrorDialog(errorMessage); logger.log(Level.SEVERE, errorMessage, ex); } finally { if (fileSystem != null) { try { fileSystem.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Problem closing filesystem.", ex); } } } configFiles.clear(); for (File f : firmwareConfig.listFiles()) { try { ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class); //ConfigLoader config = new ConfigLoader(f); configFiles.put(config.getName(), new ConfigTuple(config, f)); } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) { GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath()); } } }
From source file:org.eclipse.jdt.ls.core.internal.managers.InvisibleProjectImporter.java
private static File findNearbyNonEmptyFile(File nioFile) throws IOException { java.nio.file.Path directory = nioFile.getParentFile().toPath(); try (Stream<java.nio.file.Path> walk = Files.walk(directory, 1)) { Optional<java.nio.file.Path> found = walk.filter(Files::isRegularFile).filter(file -> { try { return file.toString().endsWith(".java") && !Objects.equals(nioFile.getName(), file.toFile().getName()) && Files.size(file) > 0; } catch (IOException e) { return false; }/*from w w w .j a v a 2s . co m*/ }).findFirst(); if (found.isPresent()) { return found.get().toFile(); } } catch (IOException e) { } return null; }
From source file:com.massabot.codesender.utils.FirmwareUtils.java
public synchronized static void initialize() { System.out.println("Initializing firmware... ..."); File firmwareConfig = new File(SettingsFactory.getSettingsDirectory(), FIRMWARE_CONFIG_DIRNAME); // Create directory if it's missing. if (!firmwareConfig.exists()) { firmwareConfig.mkdirs();/* ww w . j av a2 s . c om*/ } FileSystem fileSystem = null; // Copy firmware config files. try { final String dir = "/resources/firmware_config/"; URI location = FirmwareUtils.class.getResource(dir).toURI(); Path myPath; if (location.getScheme().equals("jar")) { try { // In case the filesystem already exists. fileSystem = FileSystems.getFileSystem(location); } catch (FileSystemNotFoundException e) { // Otherwise create the new filesystem. fileSystem = FileSystems.newFileSystem(location, Collections.<String, String>emptyMap()); } myPath = fileSystem.getPath(dir); } else { myPath = Paths.get(location); } Stream<Path> files = Files.walk(myPath, 1); for (Path path : (Iterable<Path>) () -> files.iterator()) { System.out.println(path); final String name = path.getFileName().toString(); File fwConfig = new File(firmwareConfig, name); if (name.endsWith(".json")) { boolean copyFile = !fwConfig.exists(); ControllerSettings jarSetting = getSettingsForStream(Files.newInputStream(path)); // If the file is outdated... ask the user (once). if (fwConfig.exists()) { ControllerSettings current = getSettingsForStream(new FileInputStream(fwConfig)); boolean outOfDate = current.getVersion() < jarSetting.getVersion(); if (outOfDate && !userNotified && !overwriteOldFiles) { int result = NarrowOptionPane.showNarrowConfirmDialog(200, Localization.getString("settings.file.outOfDate.message"), Localization.getString("settings.file.outOfDate.title"), JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); overwriteOldFiles = result == JOptionPane.OK_OPTION; userNotified = true; } if (overwriteOldFiles) { copyFile = true; jarSetting.getProcessorConfigs().Custom = current.getProcessorConfigs().Custom; } } // Copy file from jar to firmware_config directory. if (copyFile) { try { save(fwConfig, jarSetting); } catch (IOException ex) { logger.log(Level.SEVERE, null, ex); } } } } } catch (Exception ex) { String errorMessage = String.format("%s %s", Localization.getString("settings.file.generalError"), ex.getLocalizedMessage()); GUIHelpers.displayErrorDialog(errorMessage); logger.log(Level.SEVERE, errorMessage, ex); } finally { if (fileSystem != null) { try { fileSystem.close(); } catch (IOException ex) { logger.log(Level.SEVERE, "Problem closing filesystem.", ex); } } } configFiles.clear(); for (File f : firmwareConfig.listFiles()) { try { ControllerSettings config = new Gson().fromJson(new FileReader(f), ControllerSettings.class); // ConfigLoader config = new ConfigLoader(f); configFiles.put(config.getName(), new ConfigTuple(config, f)); } catch (FileNotFoundException | JsonSyntaxException | JsonIOException ex) { GUIHelpers.displayErrorDialog("Unable to load configuration files: " + f.getAbsolutePath()); } } }
From source file:org.hyperledger.fabric.sdk.helper.SDKUtil.java
/** * Delete a file or directory//from w w w .j ava 2 s. co m * @param file {@link File} representing file or directory * @throws IOException */ public static void deleteFileOrDirectory(File file) throws IOException { if (file.exists()) { if (file.isDirectory()) { Path rootPath = Paths.get(file.getAbsolutePath()); Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(Path::toFile).forEach(File::delete); } else { file.delete(); } } else { throw new RuntimeException("File or directory does not exist"); } }
From source file:com.mesosphere.dcos.cassandra.executor.tasks.RestoreSnapshot.java
@Override public void run() { try {//from w w w . ja v a 2 s . c o m // Send TASK_RUNNING sendStatus(driver, Protos.TaskState.TASK_RUNNING, "Started restoring snapshot"); if (Objects.equals(context.getRestoreType(), new String("new"))) { final String keyspaceDirectory = context.getLocalLocation() + File.separator + context.getName() + File.separator + context.getNodeId(); final String ssTableLoaderBinary = CassandraPaths.create(version).bin().resolve("sstableloader") .toString(); final String cassandraYaml = CassandraPaths.create(version).cassandraConfig().toString(); final File keyspacesDirectory = new File(keyspaceDirectory); LOGGER.info("Keyspace Directory {} exists: {}", keyspaceDirectory, keyspacesDirectory.exists()); final File[] keyspaces = keyspacesDirectory.listFiles(); String libProcessAddress = System.getenv("LIBPROCESS_IP"); libProcessAddress = StringUtils.isBlank(libProcessAddress) ? InetAddress.getLocalHost().getHostAddress() : libProcessAddress; for (File keyspace : keyspaces) { final File[] columnFamilies = keyspace.listFiles(); final String keyspaceName = keyspace.getName(); if (keyspaceName.equals(StorageUtil.SCHEMA_FILE)) continue; LOGGER.info("Going to bulk load keyspace: {}", keyspaceName); for (File columnFamily : columnFamilies) { final String columnFamilyName = columnFamily.getName(); if (columnFamilyName.equals(StorageUtil.SCHEMA_FILE)) continue; LOGGER.info("Bulk loading... keyspace: {} column family: {}", keyspaceName, columnFamilyName); final String columnFamilyPath = columnFamily.getAbsolutePath(); final List<String> command = Arrays.asList(ssTableLoaderBinary, "-d", libProcessAddress, "-u", context.getUsername(), "-pw", context.getPassword(), "-f", cassandraYaml, columnFamilyPath); LOGGER.info("Executing command: {}", command); final ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { LOGGER.info(line); } int exitCode = process.waitFor(); LOGGER.info("Command exit code: {}", exitCode); // Send TASK_ERROR if (exitCode != 0) { final String errMessage = String.format("Error restoring snapshot. Exit code: %s", (exitCode + "")); LOGGER.error(errMessage); sendStatus(driver, Protos.TaskState.TASK_ERROR, errMessage); } LOGGER.info("Done bulk loading! keyspace: {} column family: {}", keyspaceName, columnFamilyName); } LOGGER.info("Successfully bulk loaded keyspace: {}", keyspaceName); } // cleanup downloaded snapshot directory recursively. Path rootPath = Paths.get(context.getLocalLocation() + File.separator + context.getName()); if (rootPath.toFile().exists()) { Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder()) .map(Path::toFile).forEach(File::delete); } } else { // run nodetool refresh rather than SSTableLoader, as on performance test // I/O stream was pretty slow between mesos container processes final String localLocation = context.getLocalLocation(); final List<String> keyspaces = cassandra.getNonSystemKeySpaces(); for (String keyspace : keyspaces) { final String keySpaceDirPath = localLocation + "/" + keyspace; File keySpaceDir = new File(keySpaceDirPath); File[] cfNames = keySpaceDir .listFiles((current, name) -> new File(current, name).isDirectory()); for (File cfName : cfNames) { String columnFamily = cfName.getName().substring(0, cfName.getName().indexOf("-")); cassandra.getProbe().loadNewSSTables(keyspace, columnFamily); LOGGER.info("Completed nodetool refresh for keyspace {} & columnfamily {}", keyspace, columnFamily); } } } final String message = "Finished restoring snapshot"; LOGGER.info(message); sendStatus(driver, Protos.TaskState.TASK_FINISHED, message); } catch (Throwable t) { // Send TASK_FAILED final String errorMessage = "Failed restoring snapshot. Reason: " + t; LOGGER.error(errorMessage, t); sendStatus(driver, Protos.TaskState.TASK_FAILED, errorMessage); } }