java.nio.file.attribute.BasicFileAttributes Java Examples

The following examples show how to use java.nio.file.attribute.BasicFileAttributes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FileTesting.java    From catalyst with Apache License 2.0 7 votes vote down vote up
public static void cleanFiles() {
  Path directory = Paths.get("target/test-files/");
  try {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Files.delete(file);
        return FileVisitResult.CONTINUE;
      }

      @Override
      public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        Files.delete(dir);
        return FileVisitResult.CONTINUE;
      }
    });
  } catch (Exception ignore) {
  }
}
 
Example #2
Source File: PhraseExtractor.java    From superword with Apache License 2.0 6 votes vote down vote up
public static Set<String> parseZip(String zipFile){
    Set<String> data = new HashSet<>();
    LOGGER.info("开始解析ZIP文件:"+zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), PhraseExtractor.class.getClassLoader())) {
        for(Path path : fs.getRootDirectories()){
            LOGGER.info("处理目录:"+path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>(){

                @Override
                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);
                    data.addAll(parseFile(temp.toFile().getAbsolutePath()));
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    }catch (Exception e){
        LOGGER.error("解析文本出错", e);
    }
    return data;
}
 
Example #3
Source File: WorkspaceWatcher.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void registerAll(final Path start) {
    // register directory and sub-directories
    try {
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                    throws IOException {
                if (ignorePaths.contains(dir)) {
                    return FileVisitResult.SKIP_SUBTREE;
                } else {
                    register(dir);
                    return FileVisitResult.CONTINUE;
                }
            }
        });
    } catch (IOException e) {
        // ignore to keep sample readable
    }
}
 
Example #4
Source File: TempDir.java    From vertx-starter with Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws Exception {
  Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      Files.delete(file);
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
      Files.delete(dir);
      return FileVisitResult.CONTINUE;
    }
  });
}
 
Example #5
Source File: SourcePathTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method is primarily used to give visual confirmation that a test case
 * generated files when the compilation succeeds and so generates no other output,
 * such as error messages.
 */
List<Path> showFiles(Path dir) throws IOException {
    List<Path> files = new ArrayList<>();
    Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                throws IOException {
            if (Files.isRegularFile(file)) {
                out.println("Found " + file);
                files.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
    });
    return files;
}
 
Example #6
Source File: WordClassifier.java    From superword with Apache License 2.0 6 votes vote down vote up
public static void parseZip(String zipFile){
    LOGGER.info("开始解析ZIP文件:"+zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) {
        for(Path path : fs.getRootDirectories()){
            LOGGER.info("处理目录:"+path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>(){

                @Override
                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);
    }
}
 
Example #7
Source File: BasicFileAttributesDemo.java    From yfs with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    Path path = Paths.get("resources/lorem-ipsum.txt");
    BasicFileAttributes attr;
    try {
        attr = Files.readAttributes(path, BasicFileAttributes.class);
        String outFormat = "%-20s: %s%n";
        System.out.printf(outFormat, "creationTime", attr.creationTime());
        System.out.printf(outFormat, "lastAccessTime", attr.lastAccessTime());
        System.out.printf(outFormat, "lastModifiedTime", attr.lastModifiedTime());

        System.out.printf(outFormat, "isRegularFile", attr.isRegularFile());
        System.out.printf(outFormat, "isDirectory", attr.isDirectory());
        System.out.printf(outFormat, "isSymbolicLink", attr.isSymbolicLink());
        System.out.printf(outFormat, "size", attr.size());

        System.out.printf("%n### bulk access to file attributes%n");
        Map<String, Object> attrBulk;
        attrBulk = Files.readAttributes(path, "basic:*", NOFOLLOW_LINKS);
        for (String key : attrBulk.keySet()) {
            System.out.printf("%s:%-16s: %s%n", "basic", key, attrBulk.get(key));
        }
    } catch (IOException ex) {
        System.err.println("failed to obtain BasicFileAttributes " + ex.getMessage());
    }

}
 
Example #8
Source File: FileUtils.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
/**
 * Delete fully the given path.
 *
 * (1) If it is a file, the file will be deleted.
 *
 * (2) If it is a directory, the directory and all its contents will be recursively deleted.
 *     If an exception is thrown, the directory may possibly be partially deleted.*
 *
 * (3) If it is a symlink, the symlink will be deleted but the symlink target will not be deleted.
 */
static void deleteFully(Path p) throws IOException {
  if (!Files.exists(p, LinkOption.NOFOLLOW_LINKS)) {
    LOG.trace("deleteFully: {} does not exist.", p);
    return;
  }
  Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      delete(file);
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
      if (e != null) {
        // directory iteration failed
        throw e;
      }
      delete(dir);
      return FileVisitResult.CONTINUE;
    }
  });
}
 
Example #9
Source File: BlobContainerTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testContainerVisitor() throws Exception {
    File blobsPath = temporaryFolder.newFolder();
    BlobContainer blobContainer = new BlobContainer(blobsPath.toPath());
    blobContainer.getFile(digest("Content A")).createNewFile();
    blobContainer.getFile(digest("Content B")).createNewFile();
    blobContainer.getFile(digest("Content C")).createNewFile();

    final AtomicInteger blobsCount = new AtomicInteger(0);
    blobContainer.visitBlobs(new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            blobsCount.getAndIncrement();
            return FileVisitResult.CONTINUE;
        }
    });

    assertThat(blobsCount.get(), is(3));
}
 
Example #10
Source File: JavacFileManager.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public ArchiveContainer(Path archivePath) throws IOException, ProviderNotFoundException, SecurityException {
    this.archivePath = archivePath;
    if (multiReleaseValue != null && archivePath.toString().endsWith(".jar")) {
        Map<String,String> env = Collections.singletonMap("multi-release", multiReleaseValue);
        FileSystemProvider jarFSProvider = fsInfo.getJarFSProvider();
        Assert.checkNonNull(jarFSProvider, "should have been caught before!");
        this.fileSystem = jarFSProvider.newFileSystem(archivePath, env);
    } else {
        this.fileSystem = FileSystems.newFileSystem(archivePath, null);
    }
    packages = new HashMap<>();
    for (Path root : fileSystem.getRootDirectories()) {
        Files.walkFileTree(root, EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                        if (isValid(dir.getFileName())) {
                            packages.put(new RelativeDirectory(root.relativize(dir).toString()), dir);
                            return FileVisitResult.CONTINUE;
                        } else {
                            return FileVisitResult.SKIP_SUBTREE;
                        }
                    }
                });
    }
}
 
Example #11
Source File: FileScanner.java    From jesterj with Apache License 2.0 6 votes vote down vote up
/**
 * A default, reusable and overridable means of adding file attributes to a document
 *
 * @param attributes The attributes of the scanned file as returned by
 *                   {@link java.nio.file.Files#getFileAttributeView(Path, Class, LinkOption...)}
 * @param doc        The document representing the scanned file to which attributes should be added.
 */
default void addAttrs(BasicFileAttributes attributes, DocumentImpl doc) {
  if (attributes != null) {
    FileTime modifiedTime = attributes.lastModifiedTime();
    FileTime accessTime = attributes.lastAccessTime();
    FileTime creationTime = attributes.creationTime();
    if (modifiedTime != null) {
      doc.put("modified", String.valueOf(modifiedTime.toMillis()));
    }
    if (accessTime != null) {
      doc.put("accessed", String.valueOf(accessTime.toMillis()));
    }
    if (creationTime != null) {
      doc.put("created", String.valueOf(creationTime.toMillis()));
    }
    doc.put("file_size", String.valueOf(attributes.size()));
  }
}
 
Example #12
Source File: EndorsedExtDirs.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
static void testNonEmptySystemExtDirs() throws Exception {
    String home = System.getProperty("java.home");
    Path ext = Paths.get(home, "lib", "ext");
    String extDirs = System.getProperty("java.ext.dirs");
    String[] dirs = extDirs.split(File.pathSeparator);
    long count = 0;
    for (String d : dirs) {
        Path path = Paths.get(d);
        if (Files.notExists(path) || path.equals(ext)) continue;
        count += Files.find(path, 1, (Path p, BasicFileAttributes attr)
                                   -> p.getFileName().toString().endsWith(".jar"))
                      .count();
    }
    if (count > 0) {
        fatalError("-XX:+CheckEndorsedAndExtDirs");
    }
}
 
Example #13
Source File: HaloUtils.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取文件创建时间
 *
 * @param srcPath 文件绝对路径
 *
 * @return 时间
 */
public static Date getCreateTime(String srcPath) {
    final Path path = Paths.get(srcPath);
    final BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
    BasicFileAttributes attr;
    try {
        attr = basicview.readAttributes();
        final Date createDate = new Date(attr.creationTime().toMillis());
        return createDate;
    } catch (Exception e) {
        e.printStackTrace();
    }
    final Calendar cal = Calendar.getInstance();
    cal.set(1970, 0, 1, 0, 0, 0);
    return cal.getTime();
}
 
Example #14
Source File: HaloUtils.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 获取文件创建时间
 *
 * @param srcPath 文件绝对路径
 * @return 时间
 */
public static Date getCreateTime(String srcPath) {
    Path path = Paths.get(srcPath);
    BasicFileAttributeView basicview = Files.getFileAttributeView(path, BasicFileAttributeView.class,
            LinkOption.NOFOLLOW_LINKS);
    BasicFileAttributes attr;
    try {
        attr = basicview.readAttributes();
        Date createDate = new Date(attr.creationTime().toMillis());
        return createDate;
    } catch (Exception e) {
        e.printStackTrace();
    }
    Calendar cal = Calendar.getInstance();
    cal.set(1970, 0, 1, 0, 0, 0);
    return cal.getTime();
}
 
Example #15
Source File: ZipArchive.java    From buck with Apache License 2.0 6 votes vote down vote up
public Set<String> getDirNames() throws IOException {
  ImmutableSet.Builder<String> contents = ImmutableSet.builder();
  Files.walkFileTree(
      root,
      new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
          // Skip leading and trailing slashes. Java 8 returns trailing slashes, whereas Java 11
          // does not. Both return leading slashes.
          String dirName = dir.toString().substring(1);
          dirName = dirName.endsWith("/") ? dirName.substring(0, dirName.length() - 1) : dirName;
          contents.add(dirName);
          return FileVisitResult.CONTINUE;
        }
      });
  return contents.build();
}
 
Example #16
Source File: AbstractFileSearch.java    From steady with Apache License 2.0 6 votes vote down vote up
/**
 * Starts searching for files in the given path, up to the specified depth.
 *
 * @param _p the FS path to search in
 * @param _depth the depth of nested directories to search in
 * @return a set of paths for all files found
 */
public Set<Path> search(@NotNull Path _p, int _depth) {
	try {
		if(Files.isDirectory(_p))
			Files.walkFileTree(_p, new HashSet<FileVisitOption>(), _depth, this);
		else if(Files.isRegularFile(_p))
			this.visitFile(_p, Files.readAttributes(_p, BasicFileAttributes.class));
	} catch (Exception e) {
		AbstractFileSearch.getLog().error("Error while analyzing path [" + _p + "]: " + e.getMessage());
       }
	if(_p.isAbsolute())
		AbstractFileSearch.getLog().info("Found [" + this.files.size() + "] files in absolute path [" + _p.toAbsolutePath() + "]");
	else
		AbstractFileSearch.getLog().info("Found [" + this.files.size() + "] files in relative path [" + _p + "], i.e., absolute path [" + _p.toAbsolutePath() + "]");
	return this.files;
}
 
Example #17
Source File: LicenseCommand.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static void printJavaLicenseFiles(OutErr outErr, Path bundledJdkOrJre) {
  try {
    Files.walkFileTree(
        bundledJdkOrJre,
        new SimpleFileVisitor<Path>() {
          @Override
          public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
              throws IOException {
            if (JAVA_LICENSE_FILES.contains(path.getFileName().toString())) {
              outErr.printOutLn(path + ":\n");
              Files.copy(path, outErr.getOutputStream());
              outErr.printOutLn("\n");
            }
            return super.visitFile(path, basicFileAttributes);
          }
        });
  } catch (IOException e) {
    throw new UncheckedIOException(
        "I/O error while trying to print license file of bundled JDK or JRE: " + e.getMessage(),
        e);
  }
}
 
Example #18
Source File: Desugar.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Recursively delete a directory. */
private static void deleteTree(final Path directory) throws IOException {
  if (directory.toFile().exists()) {
    Files.walkFileTree(
        directory,
        new SimpleFileVisitor<Path>() {
          @Override
          public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
              throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
          }

          @Override
          public FileVisitResult postVisitDirectory(Path dir, IOException exc)
              throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
          }
        });
  }
}
 
Example #19
Source File: Finder.java    From XHAIL with GNU General Public License v3.0 6 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
	Objects.nonNull(file);
	Objects.nonNull(attrs);
	Path found = file.getFileName();
	for (String name : matchers.keySet())
		if (!results.containsKey(name)) {
			PathMatcher matcher = matchers.get(name);
			if (null != found && matcher.matches(found) && Files.isExecutable(file) && check(file, name, version)) {
				results.put(name, file);
				if (results.size() == matchers.size())
					return FileVisitResult.TERMINATE;
			}
		}
	return FileVisitResult.CONTINUE;
}
 
Example #20
Source File: AESKeyFileEncrypterFactoryTest.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@After
public void tearDown() throws Exception
{
    Files.walkFileTree(_tmpDir,
                       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;
                           }
                       });
}
 
Example #21
Source File: MCRSwordUtil.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
public static List<MCRValidationResult> validateZipFile(final MCRFileValidator validator, Path zipFile)
    throws IOException, URISyntaxException {
    try (FileSystem zipfs = FileSystems.newFileSystem(new URI("jar:" + zipFile.toUri()), new HashMap<>())) {
        final Path sourcePath = zipfs.getPath("/");
        ArrayList<MCRValidationResult> validationResults = new ArrayList<>();
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                MCRValidationResult validationResult = validator.validate(file);
                if (!validationResult.isValid()) {
                    validationResults.add(validationResult);
                }

                return FileVisitResult.CONTINUE;
            }
        });
        return validationResults;
    }
}
 
Example #22
Source File: MCRJSONFileVisitor.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private void writePathInfo(Path path, BasicFileAttributes attrs) throws IOException {
    MCRPath mcrPath = MCRPath.toMCRPath(path);
    MCRPath relativePath = mcrPath.getRoot().relativize(mcrPath);
    boolean isRoot = mcrPath.getNameCount() == 0;
    jw.name("type").value(attrs.isDirectory() ? "directory" : "file");
    if (isRoot) {
        jw.name("mycoreobject").value(objId);
        jw.name("mycorederivate").value(mcrPath.getOwner());
    }
    jw.name("name").value(isRoot ? "" : mcrPath.getFileName().toString());
    jw.name("path")
        .value(attrs.isDirectory() ? toStringValue(relativePath) : SEPARATOR_STRING + relativePath);
    if (!isRoot) {
        jw.name("parentPath").value(toStringValue(relativePath.getParent()));
    }
    addBasicAttributes(path, attrs);
}
 
Example #23
Source File: FileDirectoryTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void requireThatExistingDirWithInvalidContentIsDeleted() throws IOException {
    FileDirectory fileDirectory = new FileDirectory(temporaryFolder.getRoot());

    String subdirName = "subdir";
    File subDirectory = new File(temporaryFolder.getRoot(), subdirName);
    createFileInSubDir(subDirectory, "foo", "some content");
    FileReference fileReference = fileDirectory.addFile(subDirectory);
    File dir = fileDirectory.getFile(fileReference);
    assertTrue(dir.exists());
    File foo = new File(dir, "foo");
    assertTrue(foo.exists());
    FileTime fooCreatedTimestamp = Files.readAttributes(foo.toPath(), BasicFileAttributes.class).creationTime();
    assertFalse(new File(dir, "doesnotexist").exists());
    assertEquals("bebc5a1aee74223d", fileReference.value());

    // Remove a file, directory should be deleted before adding a new file
    try { Thread.sleep(1000);} catch (InterruptedException e) {/*ignore */} // Needed since we have timestamp resolution of 1 second
    Files.delete(Paths.get(fileDirectory.getPath(fileReference)).resolve("subdir").resolve("foo"));
    fileReference = fileDirectory.addFile(subDirectory);
    dir = fileDirectory.getFile(fileReference);
    File foo2 = new File(dir, "foo");
    assertTrue(dir.exists());
    assertTrue(foo2.exists());
    FileTime foo2CreatedTimestamp = Files.readAttributes(foo2.toPath(), BasicFileAttributes.class).creationTime();
    // Check that creation timestamp is newer than the old one to be sure that a new file was written
    assertTrue(foo2CreatedTimestamp.compareTo(fooCreatedTimestamp) > 0);
    assertFalse(new File(dir, "doesnotexist").exists());
    assertEquals("bebc5a1aee74223d", fileReference.value());
}
 
Example #24
Source File: RootAffixExtractor.java    From superword with Apache License 2.0 5 votes vote down vote up
public static Map<Word, Set<Word>> parseZip(String zipFile){
    Map<Word, Set<Word>> roots = new HashMap<>();
    LOGGER.info("开始解析ZIP文件:"+zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) {
        for(Path path : fs.getRootDirectories()){
            LOGGER.info("处理目录:"+path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>(){

                @Override
                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);
                    Map<Word, Set<Word>> rs = parseFile(temp.toFile().getAbsolutePath());
                    for(Word ra : rs.keySet()){
                        roots.putIfAbsent(ra, new HashSet<>());
                        roots.get(ra).addAll(rs.get(ra));
                    }
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    }catch (Exception e){
        LOGGER.error("解析文本出错", e);
    }
    return roots;
}
 
Example #25
Source File: DocumentationManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static String generateFileDoc(@Nonnull PsiFile psiFile, boolean withUrl) {
  VirtualFile file = PsiUtilCore.getVirtualFile(psiFile);
  File ioFile = file == null || !file.isInLocalFileSystem() ? null : VfsUtilCore.virtualToIoFile(file);
  BasicFileAttributes attr = null;
  try {
    attr = ioFile == null ? null : Files.readAttributes(Paths.get(ioFile.toURI()), BasicFileAttributes.class);
  }
  catch (Exception ignored) {
  }
  if (attr == null) return null;
  FileType type = file.getFileType();
  String typeName = type == UnknownFileType.INSTANCE ? "Unknown" : type == PlainTextFileType.INSTANCE ? "Text" : type instanceof ArchiveFileType ? "Archive" : type.getId();
  String languageName = type.isBinary() ? "" : psiFile.getLanguage().getDisplayName();
  return (withUrl ? DocumentationMarkup.DEFINITION_START + file.getPresentableUrl() + DocumentationMarkup.DEFINITION_END + DocumentationMarkup.CONTENT_START : "") +
         getVcsStatus(psiFile.getProject(), file) +
         getScope(psiFile.getProject(), file) +
         "<p><span class='grayed'>Size:</span> " +
         StringUtil.formatFileSize(attr.size()) +
         "<p><span class='grayed'>Type:</span> " +
         typeName +
         (type.isBinary() || typeName.equals(languageName) ? "" : " (" + languageName + ")") +
         "<p><span class='grayed'>Modified:</span> " +
         DateFormatUtil.formatDateTime(attr.lastModifiedTime().toMillis()) +
         "<p><span class='grayed'>Created:</span> " +
         DateFormatUtil.formatDateTime(attr.creationTime().toMillis()) +
         (withUrl ? DocumentationMarkup.CONTENT_END : "");
}
 
Example #26
Source File: MCRMailEventHandler.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private void handlePathEvent(MCREvent evt, Path file, BasicFileAttributes attrs) {
    if (!(file instanceof MCRPath)) {
        return;
    }
    MCRPath path = MCRPath.toMCRPath(file);
    MCRContent xml;
    try {
        xml = new MCRJDOMContent(MCRPathXML.getFileXML(path, attrs));
        handleEvent(evt, xml, path.toString());
    } catch (IOException e) {
        LOGGER.error("Error while generating mail for {}", file, e);
    }
}
 
Example #27
Source File: AtriumTools.java    From atrium-odl with Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
	Path targetPath = dst.resolve(src.relativize(dir));
	if (!Files.exists(targetPath)) {
		Files.createDirectory(targetPath);
	}
	return FileVisitResult.CONTINUE;
}
 
Example #28
Source File: FileTreeCreatorVC10.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes attrs)
      throws IOException {
   Boolean hide = false;
   // TODO remove attrs, if path is matched in this dir, then it is too in every subdir.
   // And we will check anyway
   DirAttributes newAttr = attributes.peek().clone();

   // check per config ignorePaths!
   for (BuildConfig cfg : allConfigs) {
      if (cfg.matchesIgnoredPath(path.toAbsolutePath().toString())) {
         newAttr.setIgnore(cfg);
      }

      // Hide is always on all configs. And additional files are never hiddden
      if (cfg.matchesHidePath(path.toAbsolutePath().toString())) {
         hide = true;
         break;
      }
   }

   if (!hide) {
      String name = startDir.relativize(path.toAbsolutePath()).toString();
      if (!"".equals(name)) {
         wg10.addFilter(name);
      }

      attributes.push(newAttr);
      return super.preVisitDirectory(path, attrs);
   } else {
      return FileVisitResult.SKIP_SUBTREE;
   }
}
 
Example #29
Source File: LoadIssueCategoriesRuleProvider.java    From windup with Eclipse Public License 1.0 5 votes vote down vote up
private void loadIssueCategories(RuleLoaderContext ruleLoaderContext)
{
    if (ruleLoaderContext.getRulePaths() == null)
        return;

    final List<Path> filePaths = new ArrayList<>();
    ruleLoaderContext.getRulePaths().forEach((path) -> {
        try
        {
            if (!Files.exists(path) || !Files.isReadable(path))
                return;

            Files.walkFileTree(path, new SimpleFileVisitor<Path>()
            {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
                {
                    if (Files.isReadable(file) && Files.isRegularFile(file) &&
                            file.getFileName().toString().toLowerCase().endsWith(WINDUP_CATEGORIES_XML_SUFFIX))
                        filePaths.add(file);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
        catch (IOException e)
        {
            throw new WindupException("I/O Error during search for issue category files, due to: " + e.getMessage(), e);
        }
    });

    filePaths.forEach((path) -> loadIssueCategory(ruleLoaderContext, path));
}
 
Example #30
Source File: SimpleFileVisitor.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Invoked for a file in a directory.
 *
 * <p> Unless overridden, this method returns {@link FileVisitResult#CONTINUE
 * CONTINUE}.
 */
@Override
public FileVisitResult visitFile(T file, BasicFileAttributes attrs)
    throws IOException
{
    Objects.requireNonNull(file);
    Objects.requireNonNull(attrs);
    return FileVisitResult.CONTINUE;
}