Java Code Examples for java.nio.file.attribute.BasicFileAttributes#isRegularFile()

The following examples show how to use java.nio.file.attribute.BasicFileAttributes#isRegularFile() . 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: FsBlobContainer.java    From crate with Apache License 2.0 7 votes vote down vote up
@Override
public Map<String, BlobMetaData> listBlobsByPrefix(String blobNamePrefix) throws IOException {
    // If we get duplicate files we should just take the last entry
    Map<String, BlobMetaData> builder = new HashMap<>();

    blobNamePrefix = blobNamePrefix == null ? "" : blobNamePrefix;
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, blobNamePrefix + "*")) {
        for (Path file : stream) {
            final BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
            if (attrs.isRegularFile()) {
                builder.put(file.getFileName().toString(), new PlainBlobMetaData(file.getFileName().toString(), attrs.size()));
            }
        }
    }
    return unmodifiableMap(builder);
}
 
Example 2
Source File: FsBlobContainer.java    From Elasticsearch with Apache License 2.0 7 votes vote down vote up
@Override
public ImmutableMap<String, BlobMetaData> listBlobsByPrefix(String blobNamePrefix) throws IOException {
    // using MapBuilder and not ImmutableMap.Builder as it seems like File#listFiles might return duplicate files!
    MapBuilder<String, BlobMetaData> builder = MapBuilder.newMapBuilder();

    blobNamePrefix = blobNamePrefix == null ? "" : blobNamePrefix;
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, blobNamePrefix + "*")) {
        for (Path file : stream) {
            final BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
            if (attrs.isRegularFile()) {
                builder.put(file.getFileName().toString(), new PlainBlobMetaData(file.getFileName().toString(), attrs.size()));
            }
        }
    }
    return builder.immutableMap();
}
 
Example 3
Source File: ExplodedImage.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
Node findModulesNode(String str) {
    PathNode node = nodes.get(str);
    if (node != null) {
        return node;
    }
    // lazily created "/modules/xyz/abc/" Node
    // This is mapped to default file system path "<JDK_MODULES_DIR>/xyz/abc"
    Path p = underlyingPath(str);
    if (p != null) {
        try {
            BasicFileAttributes attrs = Files.readAttributes(p, BasicFileAttributes.class);
            if (attrs.isRegularFile()) {
                Path f = p.getFileName();
                if (f.toString().startsWith("_the."))
                    return null;
            }
            node = new PathNode(str, p, attrs);
            nodes.put(str, node);
            return node;
        } catch (IOException x) {
            // does not exists or unable to determine
        }
    }
    return null;
}
 
Example 4
Source File: MCRDirectory.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the MCRFile or MCRDirectory that is represented by the given
 * FileObject, which is a direct child of the directory FileObject this
 * MCRDirectory is stored in.
 * 
 * @return an MCRFile or MCRDirectory child
 */
@Override
protected MCRStoredNode buildChildNode(Path fo) {
    if (fo == null) {
        return null;
    }
    if (!this.path.equals(fo.getParent())) {
        throw new IllegalArgumentException(fo + " is not a direct child of " + this.path + ".");
    }
    BasicFileAttributes attrs;
    try {
        attrs = Files.readAttributes(fo, BasicFileAttributes.class);
    } catch (IOException e) {
        //does not exist
        return null;
    }

    Element childData = getChildData(fo.getFileName().toString());
    if (attrs.isRegularFile()) {
        return new MCRFile(this, fo, childData);
    } else {
        return new MCRDirectory(this, fo, childData);
    }
}
 
Example 5
Source File: MCRCStoreIFS2.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private void updateMD5(Path path, BasicFileAttributes attrs) {
    if (!attrs.isRegularFile()) {
        return;
    }
    if (!(attrs instanceof MCRFileAttributes)) {
        LOGGER.warn("Cannot handle update of {} with file attribut class {}", path, attrs.getClass());
        return;
    }
    String md5 = ((MCRFileAttributes) attrs).md5sum();
    try {
        Path physicalPath = MCRPath.toMCRPath(path).toPhysicalPath();
        if (physicalPath.startsWith(baseDir)) {
            getFile(path).ifPresent(f -> updateMD5(f, path, md5));
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 6
Source File: ControllerOS7.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attr) {
  if (attr.isSymbolicLink()) {
    countSyms++;
  } else if (attr.isRegularFile()) {
    countFiles++;
  } else {
    countOther++;
  }
  if (countFiles % 10000 == 0) {
    double took = (System.currentTimeMillis() - start);
    double rate = countFiles / took;
    double drate = countDirs / took;
  }
  return FileVisitResult.CONTINUE;
}
 
Example 7
Source File: MCRPathXML.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private static void addBasicAttributes(Element root, BasicFileAttributes attr, MCRPath path) throws IOException {
    addString(root, "size", String.valueOf(attr.size()), false);
    addDate(root, "created", attr.creationTime());
    addDate(root, "lastModified", attr.lastModifiedTime());
    addDate(root, "lastAccessed", attr.lastAccessTime());
    if (attr.isRegularFile()) {
        addString(root, "contentType", MCRContentTypes.probeContentType(path), false);
    }
}
 
Example 8
Source File: LauncherHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Scan an element on a module path. The element is a directory
 * of modules, an exploded module, or a JAR file.
 */
void scan(Path entry) {
    BasicFileAttributes attrs;
    try {
        attrs = Files.readAttributes(entry, BasicFileAttributes.class);
    } catch (NoSuchFileException ignore) {
        return;
    } catch (IOException ioe) {
        ostream.println(entry + " " + ioe);
        errorFound = true;
        return;
    }

    String fn = entry.getFileName().toString();
    if (attrs.isRegularFile() && fn.endsWith(".jar")) {
        // JAR file, explicit or automatic module
        scanModule(entry).ifPresent(this::process);
    } else if (attrs.isDirectory()) {
        Path mi = entry.resolve(MODULE_INFO);
        if (Files.exists(mi)) {
            // exploded module
            scanModule(entry).ifPresent(this::process);
        } else {
            // directory of modules
            scanDirectory(entry);
        }
    }
}
 
Example 9
Source File: DeckFileVisitor.java    From magarena with GNU General Public License v3.0 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
    if (matcher.matches(file) && attrs.isRegularFile()) {
        files.add(file.toFile());
    }
    return FileVisitResult.CONTINUE;
}
 
Example 10
Source File: BasicFileAttributeManager.java    From yajsync with GNU General Public License v3.0 5 votes vote down vote up
private int toMode(BasicFileAttributes attrs)
{
    if (attrs.isDirectory()) {
        return FileOps.S_IFDIR | _defaultDirectoryPermissions;
    } else if (attrs.isRegularFile()) {
        return FileOps.S_IFREG | _defaultFilePermissions;
    } else if (attrs.isSymbolicLink()) {
        return FileOps.S_IFLNK | _defaultFilePermissions;
    } else {
        return FileOps.S_IFUNK;
    }
}
 
Example 11
Source File: Tools.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
        throws IOException {
    if (attributes.isRegularFile()) {
        delete(file);
    }
    return FileVisitResult.CONTINUE;
}
 
Example 12
Source File: SafeFiles.java    From util with Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    if (attrs.isRegularFile()) { // no symlinks, pipes, or device nodes please
        fsync(file);
        fileCount++;
    }

    return FileVisitResult.CONTINUE;
}
 
Example 13
Source File: AtriumTools.java    From atrium-odl with Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
	if (attributes.isRegularFile()) {
		delete(file);
	}
	return FileVisitResult.CONTINUE;
}
 
Example 14
Source File: HttpServer.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
void handlePluginSite(HttpRequest request, HttpChannel channel) throws IOException {
    if (disableSites) {
        channel.sendResponse(new BytesRestResponse(FORBIDDEN));
        return;
    }
    if (request.method() == RestRequest.Method.OPTIONS) {
        // when we have OPTIONS request, simply send OK by default (with the Access Control Origin header which gets automatically added)
        channel.sendResponse(new BytesRestResponse(OK));
        return;
    }
    if (request.method() != RestRequest.Method.GET) {
        channel.sendResponse(new BytesRestResponse(FORBIDDEN));
        return;
    }
    // TODO for a "/_plugin" endpoint, we should have a page that lists all the plugins?

    String path = request.rawPath().substring("/_plugin/".length());
    int i1 = path.indexOf('/');
    String pluginName;
    String sitePath;
    if (i1 == -1) {
        pluginName = path;
        sitePath = null;
        // If a trailing / is missing, we redirect to the right page #2654
        String redirectUrl = request.rawPath() + "/";
        BytesRestResponse restResponse = new BytesRestResponse(RestStatus.MOVED_PERMANENTLY, "text/html", "<head><meta http-equiv=\"refresh\" content=\"0; URL=" + redirectUrl + "\"></head>");
        restResponse.addHeader("Location", redirectUrl);
        channel.sendResponse(restResponse);
        return;
    } else {
        pluginName = path.substring(0, i1);
        sitePath = path.substring(i1 + 1);
    }

    // we default to index.html, or what the plugin provides (as a unix-style path)
    // this is a relative path under _site configured by the plugin.
    if (sitePath.length() == 0) {
        sitePath = "index.html";
    } else {
        // remove extraneous leading slashes, its not an absolute path.
        while (sitePath.length() > 0 && sitePath.charAt(0) == '/') {
            sitePath = sitePath.substring(1);
        }
    }
    final Path siteFile = environment.pluginsFile().resolve(pluginName).resolve("_site");

    final String separator = siteFile.getFileSystem().getSeparator();
    // Convert file separators.
    sitePath = sitePath.replace("/", separator);
    
    Path file = siteFile.resolve(sitePath);

    // return not found instead of forbidden to prevent malicious requests to find out if files exist or dont exist
    if (!Files.exists(file) || FileSystemUtils.isHidden(file) || !file.toAbsolutePath().normalize().startsWith(siteFile.toAbsolutePath().normalize())) {
        channel.sendResponse(new BytesRestResponse(NOT_FOUND));
        return;
    }

    BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
    if (!attributes.isRegularFile()) {
        // If it's not a dir, we send a 403
        if (!attributes.isDirectory()) {
            channel.sendResponse(new BytesRestResponse(FORBIDDEN));
            return;
        }
        // We don't serve dir but if index.html exists in dir we should serve it
        file = file.resolve("index.html");
        if (!Files.exists(file) || FileSystemUtils.isHidden(file) || !Files.isRegularFile(file)) {
            channel.sendResponse(new BytesRestResponse(FORBIDDEN));
            return;
        }
    }

    try {
        byte[] data = Files.readAllBytes(file);
        channel.sendResponse(new BytesRestResponse(OK, guessMimeType(sitePath), data));
    } catch (IOException e) {
        channel.sendResponse(new BytesRestResponse(INTERNAL_SERVER_ERROR));
    }
}
 
Example 15
Source File: CompileRustCrates.java    From java-rust-example with GNU General Public License v3.0 4 votes vote down vote up
private static boolean isDylib(Path path, BasicFileAttributes attributes) {
    String pathString = path.toString();
    String pathExtension = pathString.substring(pathString.lastIndexOf("."));
    List<String> dylibExtensions = asList(".dylib", ".so", ".dll");
    return attributes.isRegularFile() && dylibExtensions.contains(pathExtension);
}
 
Example 16
Source File: ModulePath.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Reads a packaged or exploded module, returning a {@code ModuleReference}
 * to the module. Returns {@code null} if the entry is not recognized.
 *
 * @throws IOException if an I/O error occurs
 * @throws FindException if an error occurs parsing its module descriptor
 */
private ModuleReference readModule(Path entry, BasicFileAttributes attrs)
    throws IOException
{
    try {

        // exploded module
        if (attrs.isDirectory()) {
            return readExplodedModule(entry); // may return null
        }

        // JAR or JMOD file
        if (attrs.isRegularFile()) {
            String fn = entry.getFileName().toString();
            boolean isDefaultFileSystem = isDefaultFileSystem(entry);

            // JAR file
            if (fn.endsWith(".jar")) {
                if (isDefaultFileSystem) {
                    return readJar(entry);
                } else {
                    // the JAR file is in a custom file system so
                    // need to copy it to the local file system
                    Path tmpdir = Files.createTempDirectory("mlib");
                    Path target = Files.copy(entry, tmpdir.resolve(fn));
                    return readJar(target);
                }
            }

            // JMOD file
            if (isDefaultFileSystem && isLinkPhase && fn.endsWith(".jmod")) {
                return readJMod(entry);
            }
        }

        return null;

    } catch (InvalidModuleDescriptorException e) {
        throw new FindException("Error reading module: " + entry, e);
    }
}
 
Example 17
Source File: ModulePath.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Reads a packaged or exploded module, returning a {@code ModuleReference}
 * to the module. Returns {@code null} if the entry is not recognized.
 *
 * @throws IOException if an I/O error occurs
 * @throws FindException if an error occurs parsing its module descriptor
 */
private ModuleReference readModule(Path entry, BasicFileAttributes attrs)
    throws IOException
{
    try {

        // exploded module
        if (attrs.isDirectory()) {
            return readExplodedModule(entry); // may return null
        }

        // JAR or JMOD file
        if (attrs.isRegularFile()) {
            String fn = entry.getFileName().toString();
            boolean isDefaultFileSystem = isDefaultFileSystem(entry);

            // JAR file
            if (fn.endsWith(".jar")) {
                if (isDefaultFileSystem) {
                    return readJar(entry);
                } else {
                    // the JAR file is in a custom file system so
                    // need to copy it to the local file system
                    Path tmpdir = Files.createTempDirectory("mlib");
                    Path target = Files.copy(entry, tmpdir.resolve(fn));
                    return readJar(target);
                }
            }

            // JMOD file
            if (isDefaultFileSystem && isLinkPhase && fn.endsWith(".jmod")) {
                return readJMod(entry);
            }
        }

        return null;

    } catch (InvalidModuleDescriptorException e) {
        throw new FindException("Error reading module: " + entry, e);
    }
}
 
Example 18
Source File: PollingScanDiskSpaceMonitor.java    From samza with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the total size in bytes used by the specified paths. This function guarantees that it
 * will not double count overlapping portions of the path set. For example, with a trivial
 * overlap of /A and /A, it will count /A only once. It also handles other types of overlaps
 * similarly, such as counting /A/B only once given the paths /A and /A/B.
 * <p>
 * This function is exposed as package private to simplify testing various cases without involving
 * an executor. Alternatively this could have been pulled out to a utility class, but it would
 * unnecessarily pollute the global namespace.
 */
static long getSpaceUsed(Set<Path> paths) {
  ArrayDeque<Path> pathStack = new ArrayDeque<>();

  for (Path path : paths) {
    pathStack.push(path);
  }

  // Track the directories we've visited to ensure we're not double counting. It would be
  // preferable to resolve overlap once at startup, but the problem is that the filesystem may
  // change over time and, in fact, at startup I found that the rocks DB store directory was not
  // created by the time the disk space monitor was started.
  Set<Path> visited = new HashSet<>();
  long totalBytes = 0;
  while (!pathStack.isEmpty()) {
    try {
      // We need to resolve to the real path to ensure that we don't inadvertently double count
      // due to different paths to the same directory (e.g. /A and /A/../A).
      Path current = pathStack.pop().toRealPath();

      if (visited.contains(current)) {
        continue;
      }
      visited.add(current);

      BasicFileAttributes currentAttrs = Files.readAttributes(current,
                                                              BasicFileAttributes.class);
      if (currentAttrs.isDirectory()) {
        try (DirectoryStream<Path> directoryListing = Files.newDirectoryStream(current)) {
          for (Path child : directoryListing) {
            pathStack.push(child);
          }
        }
      } else if (currentAttrs.isRegularFile()) {
        totalBytes += currentAttrs.size();
      }
    } catch (IOException e) {
      // If we can't stat the file, just ignore it. This can happen, for example, if we scan
      // a directory, but by the time we get to stat'ing the file it has been deleted (e.g.
      // due to compaction, rotation, etc.).
    }
  }

  return totalBytes;
}
 
Example 19
Source File: JavaIoFileSystem.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the status of a file. See {@link Path#stat(Symlinks)} for
 * specification.
 *
 * <p>The default implementation of this method is a "lazy" one, based on
 * other accessor methods such as {@link #isFile}, etc. Subclasses may provide
 * more efficient specializations. However, we still try to follow Unix-like
 * semantics of failing fast in case of non-existent files (or in case of
 * permission issues).
 */
@Override
protected FileStatus stat(final Path path, final boolean followSymlinks) throws IOException {
  java.nio.file.Path nioPath = getNioPath(path);
  final BasicFileAttributes attributes;
  try {
    attributes =
        Files.readAttributes(nioPath, BasicFileAttributes.class, linkOpts(followSymlinks));
  } catch (java.nio.file.FileSystemException e) {
    throw new FileNotFoundException(path + ERR_NO_SUCH_FILE_OR_DIR);
  }
  FileStatus status =  new FileStatus() {
    @Override
    public boolean isFile() {
      return attributes.isRegularFile() || isSpecialFile();
    }

    @Override
    public boolean isSpecialFile() {
      return attributes.isOther();
    }

    @Override
    public boolean isDirectory() {
      return attributes.isDirectory();
    }

    @Override
    public boolean isSymbolicLink() {
      return attributes.isSymbolicLink();
    }

    @Override
    public long getSize() throws IOException {
      return attributes.size();
    }

    @Override
    public long getLastModifiedTime() throws IOException {
      return attributes.lastModifiedTime().toMillis();
    }

    @Override
    public long getLastChangeTime() {
      // This is the best we can do with Java NIO...
      return attributes.lastModifiedTime().toMillis();
    }

    @Override
    public long getNodeId() {
      // TODO(bazel-team): Consider making use of attributes.fileKey().
      return -1;
    }
  };

  return status;
}
 
Example 20
Source File: MCRNode.java    From mycore with GNU General Public License v3.0 2 votes vote down vote up
/**
 * For file nodes, returns the file content size in bytes, otherwise returns
 * 0.
 * 
 * @return the file size in bytes
 */
public long getSize() throws IOException {
    BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
    return attr.isRegularFile() ? attr.size() : 0;
}