List of usage examples for java.nio.file FileVisitResult CONTINUE
FileVisitResult CONTINUE
To view the source code for java.nio.file FileVisitResult CONTINUE.
Click Source Link
From source file:lc.kra.servlet.FileManagerServlet.java
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) *//*from w w w.jav a 2 s .c o m*/ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Files files = null; File file = null, parent; String path = request.getParameter("path"), type = request.getContentType(), search = request.getParameter("search"), mode; if (path == null || !(file = new File(path)).exists()) files = new Roots(); else if (request.getParameter("zip") != null) { File zipFile = File.createTempFile(file.getName() + "-", ".zip"); if (file.isFile()) ZipUtil.addEntry(zipFile, file.getName(), file); else if (file.isDirectory()) ZipUtil.pack(file, zipFile); downloadFile(response, zipFile, permamentName(zipFile.getName()), "application/zip"); } else if (request.getParameter("delete") != null) { if (file.isFile()) file.delete(); else if (file.isDirectory()) { java.nio.file.Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { java.nio.file.Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { java.nio.file.Files.delete(dir); return FileVisitResult.CONTINUE; } }); } } else if ((mode = request.getParameter("mode")) != null) { boolean add = mode.startsWith("+"); if (mode.indexOf('r') > -1) file.setReadable(add); if (mode.indexOf('w') > -1) file.setWritable(add); if (mode.indexOf('x') > -1) file.setExecutable(add); } else if (file.isFile()) downloadFile(response, file); else if (file.isDirectory()) { if (search != null && !search.isEmpty()) files = new Search(file.toPath(), search); else if (type != null && type.startsWith("multipart/form-data")) { for (Part part : request.getParts()) { String name; if ((name = partFileName(part)) == null) //retrieves <input type="file" name="...">, no other (e.g. input) form fields continue; if (request.getParameter("unzip") == null) try (OutputStream output = new FileOutputStream(new File(file, name))) { copyStream(part.getInputStream(), output); } else ZipUtil.unpack(part.getInputStream(), file); } } else files = new Directory(file); } else throw new ServletException("Unknown type of file or folder."); if (files != null) { final PrintWriter writer = response.getWriter(); writer.println( "<!DOCTYPE html><html><head><style>*,input[type=\"file\"]::-webkit-file-upload-button{font-family:monospace}</style></head><body>"); writer.println("<p>Current directory: " + files + "</p><pre>"); if (!(files instanceof Roots)) { writer.print( "<form method=\"post\"><label for=\"search\">Search Files:</label> <input type=\"text\" name=\"search\" id=\"search\" value=\"" + (search != null ? search : "") + "\"> <button type=\"submit\">Search</button></form>"); writer.print( "<form method=\"post\" enctype=\"multipart/form-data\"><label for=\"upload\">Upload Files:</label> <button type=\"submit\">Upload</button> <button type=\"submit\" name=\"unzip\">Upload & Unzip</button> <input type=\"file\" name=\"upload[]\" id=\"upload\" multiple></form>"); writer.println(); } if (files instanceof Directory) { writer.println("+ <a href=\"?path=" + URLEncoder.encode(path, ENCODING) + "\">.</a>"); if ((parent = file.getParentFile()) != null) writer.println("+ <a href=\"?path=" + URLEncoder.encode(parent.getAbsolutePath(), ENCODING) + "\">..</a>"); else writer.println("+ <a href=\"?path=\">..</a>"); } for (File child : files.listFiles()) { writer.print(child.isDirectory() ? "+ " : " "); writer.print("<a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING) + "\" title=\"" + child.getAbsolutePath() + "\">" + child.getName() + "</a>"); if (child.isDirectory()) writer.print(" <a href=\"?path=" + URLEncoder.encode(child.getAbsolutePath(), ENCODING) + "&zip\" title=\"download\">⇩</a>"); if (search != null && !search.isEmpty()) writer.print(" <a href=\"?path=" + URLEncoder.encode(child.getParentFile().getAbsolutePath(), ENCODING) + "\" title=\"go to parent folder\">🗁</a>"); writer.println(); } writer.print("</pre></body></html>"); writer.flush(); } }
From source file:fr.ortolang.diffusion.runtime.engine.task.ImportReferentialEntityTask.java
@Override public void executeTask(DelegateExecution execution) throws RuntimeEngineTaskException { checkParameters(execution);/*ww w . j a va 2 s.co m*/ String referentialPathParam = execution.getVariable(REFERENTIAL_PATH_PARAM_NAME, String.class); report = new StringBuilder(); File referentialPathFile = new File(referentialPathParam); if (referentialPathFile.exists()) { final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:*.{json}"); final Path referentialPath = Paths.get(referentialPathParam); try { Files.walkFileTree(referentialPath, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path filepath, BasicFileAttributes attrs) throws IOException { Path filename = filepath.getFileName(); if (filename != null && matcher.matches(filename)) { File jsonFile = filepath.toFile(); String content = StreamUtils.getContent(jsonFile); if (content == null) { // LOGGER.log(Level.SEVERE, "Referential entity content is empty for file " + jsonFile); report.append(" - referential entity content is empty for file ").append(jsonFile) .append("\r\n"); partial = true; return FileVisitResult.CONTINUE; } String type = extractField(content, "type"); if (type == null) { // LOGGER.log(Level.SEVERE, "Referential entity type unknown for file " + jsonFile); report.append(" - referential entity type unknown for file ").append(jsonFile) .append("\r\n"); partial = true; return FileVisitResult.CONTINUE; } String name = jsonFile.getName().substring(0, jsonFile.getName().length() - 5); try { boolean exist = exists(name); if (!exist) { createReferentialEntity(name, type, content); report.append(" + referential entity created : ").append(name).append("\r\n"); } else { updateReferentialEntity(name, type, content); report.append(" + referential entity updated : ").append(name).append("\r\n"); } } catch (RuntimeEngineTaskException e) { // LOGGER.log(Level.SEVERE, " unable to import referential entity ("+type+") named "+name, e); report.append(" - unable to import referential entity '").append(name) .append("' : ").append(e.getMessage()).append("\r\n"); partial = true; return FileVisitResult.CONTINUE; } } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); } catch (Exception e) { // LOGGER.log(Level.SEVERE, " unable to import referential : " + referentialPathFile, e); report.append("Enable to import referential ").append(referentialPathFile).append(" caused by : ") .append(e.getMessage()).append("\r\n"); partial = true; } } else { // LOGGER.log(Level.SEVERE, "Referential folder doesn't exists : " + referentialPathFile); report.append("Referential folder doesn't exists at ").append(referentialPathFile).append("\r\n"); partial = true; } if (partial) { throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(), "Some entities has not been imported (see trace for detail)")); } else { throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessLogEvent(execution.getProcessBusinessKey(), "All entities imported succesfully")); } throwRuntimeEngineEvent(RuntimeEngineEvent.createProcessTraceEvent(execution.getProcessBusinessKey(), "Report: \r\n" + report.toString(), null)); }
From source file:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java
@AfterClass public static void tearDown() throws Exception { undeploy(DEPLOYMENT_NAME);// ww w. jav a2s . com // Clear the temporary directory and delete it Files.walkFileTree(TEMP_DIR, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); Files.deleteIfExists(TEMP_DIR); }
From source file:org.dragoneronca.util.Configuration.java
/** * Init logger and configuration properties. * <p/>/* w w w.ja va 2s . c o m*/ * The configuration directory should contain at least: <ul> <li>file * "environment.properties"</li> <li>file "log4j.properties"</li> <li>file * "log4j-debug.properties"</li> </ul> * * @param confDir path to the configuration directory */ public Configuration(Path confDir) { String productLogConfig = confDir.toAbsolutePath().toString() + File.separator + PRODUCT_LOG_CONFIG; String developLogConfig = confDir.toAbsolutePath().toString() + File.separator + DEVELOP_LOG_CONFIG; // default configuration for log4j LogManager.resetConfiguration(); if (Files.exists(Paths.get(productLogConfig))) { PropertyConfigurator.configure(productLogConfig); } else { BasicConfigurator.configure(); Logger.getRootLogger().setLevel(Level.INFO); LOG.warn("Impossible to load configuration for log4j: " + productLogConfig); LOG.warn("Using basic configuration for log4j"); } try { Files.walkFileTree(confDir, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Matcher confMatcher = CONF_PATTERN.matcher(file.getFileName().toString()); if (confMatcher.matches()) { LOG.info("Loading configuration file: " + file.toAbsolutePath().toString()); try { configurationMap.put(confMatcher.group("name"), new PropertiesConfiguration(file.toAbsolutePath().toString())); } catch (ConfigurationException e) { LOG.warn("Exception while loading: " + file.getFileName().toString()); } } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { LOG.error("Impossible to load configuration files", e); System.exit(-1); } PropertiesConfiguration envConf = configurationMap.get(ENV_CONF); if (envConf != null) { String envVar = envConf.getString(ENV_VAR); if (envVar != null) { Environment tmpEnv = Environment.getByName(envVar); if (tmpEnv != null) { environment = tmpEnv; } else { environment = Environment.PRODUCTION; LOG.warn("Invalid value for the environment variable in configuration file: " + "config/environment.properties " + "- Only \"development\" and \"production\" are allowed"); } } else { environment = Environment.PRODUCTION; LOG.warn("Missing environment variable in configuration file: " + "config/environment.properties"); } } else { environment = Environment.PRODUCTION; LOG.warn("Missing environment configuration file, create: " + "config/environment.properties"); } // advanced logger configuration if (environment.equals(Environment.DEVELOPMENT)) { LogManager.resetConfiguration(); if (Files.exists(Paths.get(developLogConfig))) { PropertyConfigurator.configure(developLogConfig); } else { LOG.warn("Impossible to load development configuration for log4j: " + developLogConfig); LOG.warn("Using the previous configuration for log4j"); } } }
From source file:org.zaproxy.admin.VerifyCoreZapVersionsEntries.java
private static void readZapVersionsFiles() throws Exception { Optional<String> path = Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator)) .filter(e -> e.endsWith("/ZapVersionsTests")).findFirst(); assertThat(path).as("The ZapVersionsTests directory was not found on the classpath.").isPresent(); zapVersionsfiles = new ArrayList<>(); Files.walkFileTree(Paths.get(path.get()), new SimpleFileVisitor<Path>() { @Override//from ww w. j ava 2s. c om public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { String fileName = file.getFileName().toString(); if (fileName.startsWith("ZapVersions") && fileName.endsWith(".xml")) { zapVersionsfiles.add(file); } return FileVisitResult.CONTINUE; } }); Collections.sort(zapVersionsfiles); }
From source file:org.apdplat.superword.tools.WordClassifierForWebster.java
public static void parseZip(String zipFile) { LOGGER.info("?ZIP" + zipFile); try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifierForWebster.class.getClassLoader())) { for (Path path : fs.getRootDirectories()) { LOGGER.info("?" + path); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override//from w ww .j a v a 2 s.c o m public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { LOGGER.info("?" + file); // ? Path temp = Paths.get("target/origin-html-temp.txt"); Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING); parseFile(temp.toFile().getAbsolutePath()); return FileVisitResult.CONTINUE; } }); } } catch (Exception e) { LOGGER.error("?", e); } }
From source file:org.phenotips.variantstore.shared.ResourceManager.java
/** * Copy resources recursively from a path on the filesystem to the destination folder. * * @param source/*from ww w. j av a 2s . c o m*/ * @param dest * @throws IOException */ private static void copyResourcesFromFilesystem(final Path source, final Path dest) throws IOException { Files.walkFileTree(source, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path relative = source.relativize(file); Files.copy(file, dest.resolve(relative)); return FileVisitResult.CONTINUE; } @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Path relative = source.relativize(dir); Files.createDirectory(dest.resolve(relative)); return FileVisitResult.CONTINUE; } }); }
From source file:org.apdplat.superword.tools.WordClassifierForOxford.java
public static void parseZip(String zipFile) { LOGGER.info("?ZIP" + zipFile); try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifierForOxford.class.getClassLoader())) { for (Path path : fs.getRootDirectories()) { LOGGER.info("?" + path); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override//from w w w . j a v a 2s. c o m public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { LOGGER.info("?" + file); // ? Path temp = Paths.get("target/origin-html-temp.txt"); Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING); parseFile(temp.toFile().getAbsolutePath()); return FileVisitResult.CONTINUE; } }); } } catch (Exception e) { LOGGER.error("?", e); } }
From source file:org.apache.jmeter.report.dashboard.TemplateVisitor.java
@Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Depending on file extension, copy or process file String extension = FilenameUtils.getExtension(file.toString()); if (TEMPLATED_FILE_EXT.equalsIgnoreCase(extension)) { // Process template file String templatePath = source.relativize(file).toString(); Template template = configuration.getTemplate(templatePath); Path newPath = target.resolve(FilenameUtils.removeExtension(templatePath)); try (FileOutputStream stream = new FileOutputStream(newPath.toString()); Writer writer = new OutputStreamWriter(stream, StandardCharsets.UTF_8); BufferedWriter bufferedWriter = new BufferedWriter(writer)) { template.process(data, bufferedWriter); } catch (TemplateException ex) { throw new IOException(ex); }/*from w w w.j a va2s . c o m*/ } else { // Copy regular file Path newFile = target.resolve(source.relativize(file)); Files.copy(file, newFile, StandardCopyOption.REPLACE_EXISTING); } return FileVisitResult.CONTINUE; }
From source file:org.talend.dataprep.dataset.store.content.file.LocalFileContentStore.java
@Override public void clear() { try {//from w w w .j av a 2s .c o m Path path = FileSystems.getDefault().getPath(storeLocation); if (!path.toFile().exists()) { return; } Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { // .nfs files are handled by the OS and can be deleted after the visitor started. // Exceptions on such files can be safely ignored if (file.getFileName().toFile().getName().startsWith(".nfs")) { //$NON-NLS-1$ LOGGER.warn("unable to delete {}", file.getFileName(), exc); return FileVisitResult.CONTINUE; } throw exc; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { // Skip NFS file content if (!file.getFileName().toFile().getName().startsWith(".nfs")) { //$NON-NLS-1$ Files.delete(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException { if (e == null) { return FileVisitResult.CONTINUE; } else { // directory iteration failed throw e; } } }); } catch (IOException e) { LOGGER.error("Unable to clear local data set content.", e); throw new TDPException(DataSetErrorCodes.UNABLE_TO_CLEAR_DATASETS, e); } }