List of usage examples for java.nio.file Files list
public static Stream<Path> list(Path dir) throws IOException
From source file:org.wso2.carbon.uuf.internal.io.reference.ArtifactComponentReference.java
@Override public Stream<FileReference> getI18nFiles() { Path lang = componentDirectory.resolve(DIR_NAME_LANGUAGE); if (!Files.exists(lang)) { return Stream.<FileReference>empty(); }//from w ww . ja va 2 s .c om try { return Files.list(lang) .filter(path -> Files.isRegularFile(path) && "properties".equals(getExtension(path))) .map(path -> new ArtifactFileReference(path, appReference)); } catch (IOException e) { throw new FileOperationException("An error occurred while listing language files in '" + lang + "'.", e); } }
From source file:fr.ortolang.diffusion.client.cmd.CheckBagCommand.java
@Override public void execute(String[] args) { CommandLineParser parser = new DefaultParser(); CommandLine cmd;/*w w w. j ava 2 s . c o m*/ String root = ""; try { cmd = parser.parse(options, args); if (cmd.hasOption("h")) { help(); } if (cmd.hasOption("f")) { fix = true; } if (cmd.hasOption("p")) { root = cmd.getOptionValue("p"); } else { help(); } String[] credentials = getCredentials(cmd); String username = credentials[0]; String password = credentials[1]; client = OrtolangClient.getInstance(); if (username.length() > 0) { client.getAccountManager().setCredentials(username, password); client.login(username); } System.out.println("Connected as user: " + client.connectedProfile()); if (!Files.exists(Paths.get(root))) { errors.append("-> Le chemin de base (").append(root).append(") n'existe pas\r\n"); } else { if (!Files.exists(Paths.get(root, "data", "publication.properties"))) { errors.append("-> publication.properties NOT found\r\n"); } if (!Files.exists(Paths.get(root, "data", "workspace.properties"))) { errors.append("-> workspace.properties NOT found\r\n"); } else { checkWorkspaceProperties(Paths.get(root, "data", "workspace.properties")); } if (Files.exists(Paths.get(root, "data", "snapshots"))) { Files.list(Paths.get(root, "data", "snapshots")).forEach(this::checkSnapshotMetadata); Files.list(Paths.get(root, "data", "snapshots")).forEach(this::checkPermissions); } if (Files.exists(Paths.get(root, "data", "head"))) { checkSnapshotMetadata(Paths.get(root, "data", "head")); } } if (errors.length() > 0) { System.out.println("## Some errors has been found : "); System.out.print(errors.toString()); if (fix) { System.out.println("## Some errors has been fixed : "); System.out.print(fixed.toString()); } } else { System.out.println("No error found."); } } catch (ParseException | IOException e) { System.out.println("Failed to parse command line properties: " + e.getMessage()); help(); } catch (OrtolangClientException | OrtolangClientAccountException e) { System.out.println("Unexpected error !!"); e.printStackTrace(); } }
From source file:com.qwazr.server.InFileSessionPersistenceManager.java
@Override public Map<String, PersistentSession> loadSessionAttributes(final String deploymentName, final ClassLoader classLoader) { final Path deploymentDir = sessionDir.resolve(deploymentName); if (!Files.exists(deploymentDir) || !Files.isDirectory(deploymentDir)) return null; try {/*from w w w . j a v a 2 s .c o m*/ final long time = System.currentTimeMillis(); final Map<String, PersistentSession> finalMap = new HashMap<>(); try (final Stream<Path> stream = Files.list(deploymentDir)) { stream.filter(p -> Files.isRegularFile(p)).forEach(sessionPath -> { final File sessionFile = sessionPath.toFile(); final PersistentSession persistentSession = readSession(sessionFile); if (persistentSession != null && persistentSession.getExpiration().getTime() > time) finalMap.put(sessionFile.getName(), persistentSession); try { FileUtils.deleteDirectory(sessionPath); } catch (IOException e) { LOGGER.log(Level.WARNING, e, () -> "Cannot delete session file " + sessionFile); } }); } return finalMap.isEmpty() ? null : finalMap; } catch (IOException e) { LOGGER.log(Level.WARNING, e, () -> "Cannot read sessions in " + deploymentDir); return null; } }
From source file:org.apache.storm.localizer.LocalizedResource.java
private static List<String> readKeysFromDir(Path dir) throws IOException { if (!Files.exists(dir)) { return Collections.emptyList(); }/*from w w w. j av a 2 s .c o m*/ return Files.list(dir).map((p) -> p.getFileName().toString()) .filter((name) -> name.toLowerCase().endsWith(CURRENT_BLOB_SUFFIX)).map((key) -> { int p = key.lastIndexOf('.'); if (p > 0) { key = key.substring(0, p); } return key; }).collect(Collectors.toList()); }
From source file:org.cirdles.webServices.calamari.PrawnFileHandlerService.java
public Path generateReports(String myFileName, InputStream prawnFile, boolean useSBM, boolean userLinFits, String firstLetterRM) throws IOException, JAXBException, SAXException { String fileName = myFileName; if (myFileName == null) { fileName = DEFAULT_PRAWNFILE_NAME; }/*from ww w . j av a 2 s . co m*/ Path uploadDirectory = Files.createTempDirectory("upload"); Path prawnFilePath = uploadDirectory.resolve("prawn-file.xml"); Files.copy(prawnFile, prawnFilePath); Path calamarirReportsFolderAlias = Files.createTempDirectory("reports-destination"); File reportsDestinationFile = calamarirReportsFolderAlias.toFile(); reportsEngine.setFolderToWriteCalamariReports(reportsDestinationFile); // this gives reportengine the name of the Prawnfile for use in report names prawnFileHandler.initReportsEngineWithCurrentPrawnFileName(fileName); prawnFileHandler.writeReportsFromPrawnFile(prawnFilePath.toString(), useSBM, userLinFits, firstLetterRM); Files.delete(prawnFilePath); Path reportsFolder = Paths.get(reportsEngine.getFolderToWriteCalamariReportsPath()).getParent() .toAbsolutePath(); Path reports = Files.list(reportsFolder).findFirst().orElseThrow(() -> new IllegalStateException()); Path reportsZip = zip(reports); recursiveDelete(reports); return reportsZip; }
From source file:pe.chalk.takoyaki.Takoyaki.java
public synchronized Takoyaki init() throws IOException, JSONException, ReflectiveOperationException { if (this.getLogger() != null) return this; this.addTargetClasses(NaverCafe.class, NamuWiki.class); Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown)); this.logger = new Logger(); this.getLogger().addStream(new LoggerStream(TextFormat.Type.ANSI, System.out)); this.getLogger().addStream(new LoggerStream(TextFormat.Type.NONE, new PrintStream(new FileOutputStream("Takoyaki.log", true), true, "UTF-8"))); this.getLogger().info(" : " + Takoyaki.VERSION); try {/*from w w w .ja v a 2 s . c o m*/ final Path propertiesPath = Paths.get("Takoyaki.json"); if (!Files.exists(propertiesPath)) { this.getLogger().info("? ?: " + propertiesPath.toString()); Files.write(propertiesPath, Takoyaki.DEFAULT_CONFIG, StandardCharsets.UTF_8); } this.getLogger().info("? : " + propertiesPath); final JSONObject properties = new JSONObject( Files.lines(propertiesPath, StandardCharsets.UTF_8).collect(Collectors.joining())); Utils.buildStream(JSONObject.class, properties.getJSONArray("targets")).map(Target::create) .forEach(this::addTarget); final Path pluginsPath = Paths.get("plugins"); if (!Files.exists(pluginsPath)) Files.createDirectories(pluginsPath); List<String> excludedPlugins = Utils .buildStream(String.class, properties.getJSONObject("options").getJSONArray("excludedPlugins")) .collect(Collectors.toList()); new PluginLoader().load(Files.list(pluginsPath) .filter(PluginLoader.PLUGIN_FILTER.apply(excludedPlugins)).collect(Collectors.toList())) .forEach(this::addPlugin); } catch (Exception e) { this.getLogger().error(e.getClass().getName() + ": " + e.getMessage()); throw e; } return this; }
From source file:com.google.cloud.runtimes.builder.buildsteps.docker.StageDockerArtifactBuildStep.java
private Path searchForArtifactInDir(Path directory) throws ArtifactNotFoundException, TooManyArtifactsException, IOException { logger.info("Searching for a deployable artifact in {}", directory.toString()); if (!Files.isDirectory(directory)) { throw new IllegalArgumentException(String.format("%s is not a valid directory.", directory)); }// w w w .j av a 2 s .c om List<Path> validArtifacts = Files.list(directory) // filter out files that don't end in .war or .jar .filter((path) -> { String extension = com.google.common.io.Files.getFileExtension(path.toString()); return extension.equals("war") || extension.equals("jar"); }).collect(Collectors.toList()); if (validArtifacts.size() < 1) { throw new ArtifactNotFoundException(); } else if (validArtifacts.size() > 1) { throw new TooManyArtifactsException(validArtifacts); } else { return validArtifacts.get(0); } }
From source file:org.opennms.upgrade.implementations.DataCollectionConfigMigrator17Offline.java
/** * Checks if is configuration valid.//from ww w . j av a2s. c o m * * @return true, if is configuration valid * @throws OnmsUpgradeException the OpenNMS upgrade exception */ private boolean isConfigValid() throws OnmsUpgradeException { File configDirectory = new File(sourceFile.getParentFile().getAbsolutePath(), "datacollection"); try { DefaultDataCollectionConfigDao dao = new DefaultDataCollectionConfigDao(); dao.setConfigDirectory(configDirectory.getAbsolutePath()); dao.setConfigResource(new FileSystemResource(sourceFile)); dao.setReloadCheckInterval(new Long(0)); dao.afterPropertiesSet(); } catch (IllegalArgumentException e) { log("Found a problem: %s\n", e.getMessage()); Matcher m = pattern.matcher(e.getMessage()); if (m.find()) { try { Iterator<Path> paths = Files.list(configDirectory.toPath()) .filter(f -> f.getFileName().toString().toLowerCase().endsWith(".xml")).iterator(); for (; paths.hasNext();) { String group = getGroupForResourceType(paths.next().toFile(), m.group(1)); if (group != null) { updateDataCollectionConfig(m.group(2), group); return false; } } } catch (Exception ex) { throw new OnmsUpgradeException("Can't get datacollection-group files", ex); } } } catch (Exception e) { throw new OnmsUpgradeException("Can't process " + sourceFile, e); } return true; }
From source file:org.sonar.java.it.JavaRulingTest.java
private static void prepareDumpOldFolder() { Path allRulesFolder = Paths.get("src/test/resources"); if (SUBSET_OF_ENABLED_RULES.isEmpty()) { effectiveDumpOldFolder = allRulesFolder.toAbsolutePath(); } else {// w ww. ja v a 2 s . c om effectiveDumpOldFolder = TMP_DUMP_OLD_FOLDER.getRoot().toPath().toAbsolutePath(); Try.of(() -> Files.list(allRulesFolder)).orElseThrow(Throwables::propagate) .filter(p -> p.toFile().isDirectory()).forEach(srcProjectDir -> copyDumpSubset(srcProjectDir, effectiveDumpOldFolder.resolve(srcProjectDir.getFileName()))); } }
From source file:org.ballerinalang.composer.service.fs.LocalFileSystem.java
/** * {@inheritDoc}/*from w w w . jav a2 s.com*/ */ @Override public JsonArray listFilesInPath(String path, List<String> extensions) throws IOException { Path ioPath = Paths.get(path); JsonArray dirs = new JsonArray(); Iterator<Path> iterator = Files.list(ioPath).sorted().iterator(); while (iterator.hasNext()) { Path next = iterator.next(); if ((Files.isDirectory(next) || Files.isRegularFile(next)) && !Files.isHidden(next) && !isWindowsSystemFile(next)) { JsonObject jsnObj = getJsonObjForFile(next, extensions); if (Files.isRegularFile(next)) { Path fileName = next.getFileName(); SuffixFileFilter fileFilter = new SuffixFileFilter(extensions, INSENSITIVE); if (null != fileName && fileFilter.accept(next.toFile())) { jsnObj.addProperty(FILE_FULL_PATH, next.toString()); jsnObj.addProperty(FILE_NAME, FilenameUtils.getBaseName(next.toString())); jsnObj.addProperty(FILE_PATH, FilenameUtils.getFullPath(next.toString())); jsnObj.addProperty(EXTENSION, FilenameUtils.getExtension(next.toString())); dirs.add(jsnObj); } } else { dirs.add(jsnObj); } } } return dirs; }