Java Code Examples for java.nio.file.Files#setAttribute()

The following examples show how to use java.nio.file.Files#setAttribute() . These examples are extracted from open source projects. 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 Project: logging-log4j2   File: FileManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected OutputStream createOutputStream() throws IOException {
    final String filename = getFileName();
    LOGGER.debug("Now writing to {} at {}", filename, new Date());
    final File file = new File(filename);
    final FileOutputStream fos = new FileOutputStream(file, isAppend);
    if (file.exists() && file.length() == 0) {
        try {
            FileTime now = FileTime.fromMillis(System.currentTimeMillis());
            Files.setAttribute(file.toPath(), "creationTime", now);
        } catch (Exception ex) {
            LOGGER.warn("Unable to set current file tiem for {}", filename);
        }
        writeHeader(fos);
    }
    defineAttributeView(Paths.get(filename));
    return fos;
}
 
Example 2
Source Project: ariADDna   File: BlockMerge.java    License: Apache License 2.0 6 votes vote down vote up
public File concateBlockInFile(Metafile metafile, Set<Block> blockSet) throws IOException {
    File localFile = localService.getLocalFileByUuid(metafile.getFileUuid());
    FileOutputStream outputStream = new FileOutputStream(localFile);

    //int off = 0;
    for (Block block : blockSet) {

        int size = block.getPayload().length;
        outputStream.write(block.getPayload(), 0, size);
        //off += size;
    }
    Map<String, String> attributes = metafile.getProperties();
    for (Map.Entry<String, String> entry : attributes.entrySet()) {
        Path path = localFile.toPath();
        Files.setAttribute(path, entry.getKey(), entry.getValue());
    }
    return localFile;
}
 
Example 3
@Override
public void setAttribute(Path file, String attribute, Object value, LinkOption... options)
    throws IOException
{
    triggerEx(file, "setAttribute");
    Files.setAttribute(unwrap(file), attribute, value, options);
}
 
Example 4
@Override
public void setAttribute(Path file, String attribute, Object value, LinkOption... options)
    throws IOException
{
    triggerEx(file, "setAttribute");
    Files.setAttribute(unwrap(file), attribute, value, options);
}
 
Example 5
@Override
public void setAttribute(Path file, String attribute, Object value, LinkOption... options)
    throws IOException
{
    triggerEx(file, "setAttribute");
    Files.setAttribute(unwrap(file), attribute, value, options);
}
 
Example 6
private void makeFile(Path filePath, String text, long time) throws IOException
{
    Files.createDirectories(filePath.getParent());
    Files.write(
        filePath,
        text.getBytes()
    );
    Files.setAttribute(
        filePath,
        "lastModifiedTime",
        FileTime.fromMillis(time)
    );
}
 
Example 7
Source Project: proxyee-down   File: FileUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建文件夹,如果目标存在则删除
 */
public static File createDir(String path, boolean isHidden) throws IOException {
  File file = new File(path);
  deleteIfExists(file);
  File newFile = new File(path);
  newFile.mkdir();
  if (OsUtil.isWindows()) {
    Files.setAttribute(newFile.toPath(), "dos:hidden", isHidden);
  }
  return file;
}
 
Example 8
Source Project: pdown-core   File: FileUtil.java    License: MIT License 5 votes vote down vote up
/**
 * 创建文件夹,如果目标存在则删除
 */
public static File createDir(String path, boolean isHidden) throws IOException {
  File file = new File(path);
  deleteIfExists(file);
  File newFile = new File(path);
  newFile.mkdir();
  if (OsUtil.isWindows()) {
    Files.setAttribute(newFile.toPath(), "dos:hidden", isHidden);
  }
  return file;
}
 
Example 9
Source Project: jsr203-hadoop   File: TestFiles.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void setAttribute() throws IOException {
  Path rootPath = Paths.get(clusterUri);
  Path path = Files.createTempFile(rootPath, "test", "tmp");
  Object att = Files.getAttribute(path, "hadoop:replication");
  Assert.assertNotNull(att);
  Files.setAttribute(path, "hadoop:replication", att);
}
 
Example 10
Source Project: update4j   File: FileUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void windowsHidden(Path file, boolean hidden) {
    if (OS.CURRENT != OS.WINDOWS)
        return;

    try {
        Files.setAttribute(file, "dos:hidden", hidden);
    } catch (Exception e) {
    }
}
 
Example 11
@Override
public void setFileMode(Path path, int mode, LinkOption... linkOption) throws IOException
{
    //i.e. (mode & 07000) != 0;
    boolean requiresUnix = (mode & (FileOps.S_ISUID | FileOps.S_ISGID | FileOps.S_ISVTX)) != 0;
    if (requiresUnix) {
        throw new IOException("unsupported operation");
    }
    Set<PosixFilePermission> perms = modeToPosixFilePermissions(mode);
    Files.setAttribute(path, "posix:permissions", perms, linkOption);
}
 
Example 12
@Override
public boolean setReadable(final String fileName, final boolean readable,
                           final boolean ownerOnly) {
    try {
        Path path = Paths.get(fileName);
        Files.setAttribute(path, "dos:readonly", readable);
    } catch (IOException e) {
        return false;
    }
    return true;
}
 
Example 13
@Override
public void setAttribute(Path file, String attribute, Object value, LinkOption... options)
    throws IOException
{
    triggerEx(file, "setAttribute");
    Files.setAttribute(unwrap(file), attribute, value, options);
}
 
Example 14
@Override
public void setAttribute(Path file, String attribute, Object value, LinkOption... options)
    throws IOException
{
    triggerEx(file, "setAttribute");
    Files.setAttribute(unwrap(file), attribute, value, options);
}
 
Example 15
@Override
public void saveConfiguration(File file) throws IOException {
  try {
    // write sensitive parameters only to the local config file
    final boolean skipSensitive = !file.equals(MZmineConfiguration.CONFIG_FILE);

    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

    Document configuration = dBuilder.newDocument();
    Element configRoot = configuration.createElement("configuration");
    configuration.appendChild(configRoot);

    Element prefElement = configuration.createElement("preferences");
    configRoot.appendChild(prefElement);
    preferences.setSkipSensitiveParameters(skipSensitive);
    preferences.saveValuesToXML(prefElement);

    Element lastFilesElement = configuration.createElement("lastprojects");
    configRoot.appendChild(lastFilesElement);
    lastProjects.saveValueToXML(lastFilesElement);

    Element modulesElement = configuration.createElement("modules");
    configRoot.appendChild(modulesElement);

    // traverse modules
    for (MZmineModule module : MZmineCore.getAllModules()) {

      String className = module.getClass().getName();

      Element moduleElement = configuration.createElement("module");
      moduleElement.setAttribute("class", className);
      modulesElement.appendChild(moduleElement);

      Element paramElement = configuration.createElement("parameters");
      moduleElement.appendChild(paramElement);

      ParameterSet moduleParameters = getModuleParameters(module.getClass());
      moduleParameters.setSkipSensitiveParameters(skipSensitive);
      moduleParameters.saveValuesToXML(paramElement);
    }

    // save encryption key to local config only
    // ATTENTION: this should to be written after all other configs
    final SimpleParameterSet encSet = new SimpleParameterSet(new Parameter[] {globalEncrypter});
    encSet.setSkipSensitiveParameters(skipSensitive);
    encSet.saveValuesToXML(prefElement);

    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer transformer = transfac.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    // Create parent folder if it does not exist
    File confParent = file.getParentFile();
    if ((confParent != null) && (!confParent.exists())) {
      confParent.mkdirs();
    }

    // Java fails to write into hidden files on Windows, see
    // https://bugs.openjdk.java.net/browse/JDK-8047342
    if (file.exists() && System.getProperty("os.name").toLowerCase().contains("windows")) {
      if ((Boolean) Files.getAttribute(file.toPath(), "dos:hidden", LinkOption.NOFOLLOW_LINKS)) {
        Files.setAttribute(file.toPath(), "dos:hidden", Boolean.FALSE, LinkOption.NOFOLLOW_LINKS);
      }
    }

    StreamResult result = new StreamResult(new FileOutputStream(file));
    DOMSource source = new DOMSource(configuration);
    transformer.transform(source, result);

    // make user home config file invisible on windows
    if ((!skipSensitive) && (System.getProperty("os.name").toLowerCase().contains("windows"))) {
      Files.setAttribute(file.toPath(), "dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS);
    }

    logger.info("Saved configuration to file " + file);
  } catch (Exception e) {
    throw new IOException(e);
  }
}
 
Example 16
Source Project: buck   File: DirArtifactCacheTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testDeleteAfterStoreIfFull() throws IOException {
  Path fileX = tmpDir.newFile("x");
  Path fileY = tmpDir.newFile("y");
  Path fileZ = tmpDir.newFile("z");

  fileHashLoader =
      new FakeFileHashCache(
          ImmutableMap.of(
              fileX, HashCode.fromInt(0),
              fileY, HashCode.fromInt(1),
              fileZ, HashCode.fromInt(2)));

  // The reason max size is 9 bytes is because a 1-byte entry actually takes 6 bytes to store.
  // If the cache trims the size down to 2/3 (6 bytes) every time it hits the max it means after
  // every store only the most recent artifact should be left.
  dirArtifactCache =
      newDirArtifactCache(/* maxCacheSizeBytes */ Optional.of(9L), CacheReadMode.READWRITE);

  Files.write(fileX, "x".getBytes(UTF_8));
  Files.write(fileY, "y".getBytes(UTF_8));
  Files.write(fileZ, "z".getBytes(UTF_8));

  BuildRule inputRuleX = new BuildRuleForTest(fileX);
  BuildRule inputRuleY = new BuildRuleForTest(fileY);
  BuildRule inputRuleZ = new BuildRuleForTest(fileZ);
  ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
  graphBuilder.addToIndex(inputRuleX);
  graphBuilder.addToIndex(inputRuleY);
  graphBuilder.addToIndex(inputRuleZ);

  DefaultRuleKeyFactory fakeRuleKeyFactory =
      new TestDefaultRuleKeyFactory(fileHashLoader, graphBuilder);

  RuleKey ruleKeyX = fakeRuleKeyFactory.build(inputRuleX);
  RuleKey ruleKeyY = fakeRuleKeyFactory.build(inputRuleY);
  RuleKey ruleKeyZ = fakeRuleKeyFactory.build(inputRuleZ);

  dirArtifactCache.store(
      ArtifactInfo.builder().addRuleKeys(ruleKeyX).build(),
      BorrowablePath.notBorrowablePath(fileX));
  assertEquals(
      CacheResultType.HIT,
      Futures.getUnchecked(
              dirArtifactCache.fetchAsync(null, ruleKeyX, LazyPath.ofInstance(fileX)))
          .getType());

  Files.setAttribute(
      dirArtifactCache.getPathForRuleKey(ruleKeyX, Optional.empty()),
      "lastAccessTime",
      FileTime.fromMillis(0));
  Files.setAttribute(
      dirArtifactCache.getPathForRuleKey(ruleKeyX, Optional.of(".metadata")),
      "lastAccessTime",
      FileTime.fromMillis(0));

  dirArtifactCache.store(
      ArtifactInfo.builder().addRuleKeys(ruleKeyY).build(),
      BorrowablePath.notBorrowablePath(fileY));
  assertEquals(
      CacheResultType.MISS,
      Futures.getUnchecked(
              dirArtifactCache.fetchAsync(null, ruleKeyX, LazyPath.ofInstance(fileX)))
          .getType());
  assertEquals(
      CacheResultType.HIT,
      Futures.getUnchecked(
              dirArtifactCache.fetchAsync(null, ruleKeyY, LazyPath.ofInstance(fileY)))
          .getType());

  Files.setAttribute(
      dirArtifactCache.getPathForRuleKey(ruleKeyY, Optional.empty()),
      "lastAccessTime",
      FileTime.fromMillis(1000));
  Files.setAttribute(
      dirArtifactCache.getPathForRuleKey(ruleKeyY, Optional.of(".metadata")),
      "lastAccessTime",
      FileTime.fromMillis(1000));

  dirArtifactCache.store(
      ArtifactInfo.builder().addRuleKeys(ruleKeyZ).build(),
      BorrowablePath.notBorrowablePath(fileZ));

  assertEquals(
      CacheResultType.MISS,
      Futures.getUnchecked(
              dirArtifactCache.fetchAsync(null, ruleKeyX, LazyPath.ofInstance(fileX)))
          .getType());
  assertEquals(
      CacheResultType.MISS,
      Futures.getUnchecked(
              dirArtifactCache.fetchAsync(null, ruleKeyY, LazyPath.ofInstance(fileY)))
          .getType());
  assertEquals(
      CacheResultType.HIT,
      Futures.getUnchecked(
              dirArtifactCache.fetchAsync(null, ruleKeyZ, LazyPath.ofInstance(fileZ)))
          .getType());
}
 
Example 17
@Override
public void setAttribute(Path file, String attribute, Object value,
		LinkOption... options) throws IOException {
	Files.setAttribute(EncryptedFileSystem.dismantle(file), attribute,
			value, options);
}
 
Example 18
@Override
public void setGroupId(Path path, int gid, LinkOption... linkOption) throws IOException
{
    Files.setAttribute(path, "unix:gid", gid, linkOption);
}
 
Example 19
@Override
public void setUserId(Path path, int uid, LinkOption... linkOption) throws IOException
{
    Files.setAttribute(path, "unix:uid", uid, linkOption);
}
 
Example 20
Source Project: ecs-sync   File: PreserveFiltersTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
    public void testRestoreSymLink() throws Exception {
        // can only change ownership if root
        boolean isRoot = "root".equals(System.getProperty("user.name"));
        if (isRoot) log.warn("detected root execution");

        String file = "concrete-file", link = "sym-link";
        int gid = 10;
        // write concrete file
        try (OutputStream out = new FileOutputStream(new File(sourceDir, file))) {
            StreamUtil.copy(new RandomInputStream(1024), out, 1024);
        }

        Files.createSymbolicLink(Paths.get(sourceDir.getPath(), link), Paths.get(file));

        if (isRoot) {
            Files.setAttribute(Paths.get(sourceDir.getPath(), file), "unix:gid", gid, LinkOption.NOFOLLOW_LINKS);
            Files.setAttribute(Paths.get(sourceDir.getPath(), link), "unix:gid", gid, LinkOption.NOFOLLOW_LINKS);
        }

        Date fileMtime = new Date(Files.getLastModifiedTime(Paths.get(sourceDir.getPath(), file)).toMillis());
        Date linkMtime = new Date(Files.getLastModifiedTime(Paths.get(sourceDir.getPath(), link), LinkOption.NOFOLLOW_LINKS).toMillis());

        Thread.sleep(5000);

        FilesystemConfig fsConfig = new FilesystemConfig();
        fsConfig.setPath(sourceDir.getPath());
        TestConfig testConfig = new TestConfig().withReadData(true).withDiscardData(false);
        PreserveFileAttributesConfig preserveConfig = new PreserveFileAttributesConfig();

        EcsSync sync = new EcsSync();
        sync.setSyncConfig(new SyncConfig().withSource(fsConfig).withTarget(testConfig)
                .withFilters(Collections.singletonList(preserveConfig)));
        sync.run();

        TestStorage testStorage = (TestStorage) sync.getTarget();

        Assert.assertEquals(2, sync.getStats().getObjectsComplete());
        Assert.assertEquals(0, sync.getStats().getObjectsFailed());

        fsConfig.setPath(targetDir.getPath());

        sync = new EcsSync();
        sync.setSyncConfig(new SyncConfig().withTarget(fsConfig)
                .withFilters(Collections.singletonList(new RestoreFileAttributesConfig())));
        sync.setSource(testStorage);
        sync.run();

        Assert.assertEquals(2, sync.getStats().getObjectsComplete());
        Assert.assertEquals(0, sync.getStats().getObjectsFailed());

        Thread.sleep(2000); // make sure cache is settled (avoid stale attributes)

        if (isRoot) {
            Assert.assertEquals(gid, Files.getAttribute(Paths.get(targetDir.getPath(), file), "unix:gid", LinkOption.NOFOLLOW_LINKS));
            Assert.assertEquals(gid, Files.getAttribute(Paths.get(targetDir.getPath(), link), "unix:gid", LinkOption.NOFOLLOW_LINKS));
        }

        Date tFileMtime = new Date(Files.getLastModifiedTime(Paths.get(targetDir.getPath(), file)).toMillis());
        Date tLinkMtime = new Date(Files.getLastModifiedTime(Paths.get(targetDir.getPath(), link), LinkOption.NOFOLLOW_LINKS).toMillis());

        Assert.assertEquals(fileMtime.getTime() / 10, tFileMtime.getTime() / 10);
//        Assert.assertEquals(linkMtime, tLinkMtime); // TODO: figure out a way to set mtime on a link in Java
    }