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

The following examples show how to use java.nio.file.Files#getFileAttributeView() . 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
public boolean setMetadata(Path file, String key, String value) {

        if (supportsUserDefinedAttributes(file)) {
            UserDefinedFileAttributeView view = Files.getFileAttributeView(file, UserDefinedFileAttributeView.class);
            try {
                if (value != null) {
                    view.write(key, Charset.defaultCharset().encode(value));
                } else {
                    view.delete(key);
                }
                return true;
            } catch (IOException e) {
                return false;
            }
        }
        return false;
    }
 
Example 2
@Test
public void testOnCreateValidationForNonWritableStorePath() throws Exception
{
    if (Files.getFileAttributeView(_workDir.toPath(), PosixFileAttributeView.class) != null)
    {
        File file = new File(_workDir, getTestName());
        file.mkdirs();
        if (file.setWritable(false, false))
        {
            String nodeName = getTestName();
            Map<String, Object> nodeData = new HashMap<>();
            nodeData.put(VirtualHostNode.NAME, nodeName);
            nodeData.put(VirtualHostNode.TYPE, DerbyVirtualHostNodeImpl.VIRTUAL_HOST_NODE_TYPE);
            nodeData.put(DerbyVirtualHostNodeImpl.STORE_PATH, file.getAbsolutePath());
            try
            {
                _broker.createChild(VirtualHostNode.class, nodeData);
                fail("Cannot create store for the non writable store path");
            }
            catch (IllegalConfigurationException e)
            {
                // pass
            }
        }
    }
}
 
Example 3
Source Project: helm-maven-plugin   File: InitMojo.java    License: MIT License 6 votes vote down vote up
private void addExecPermission(final Path helm) throws IOException {
	Set<String> fileAttributeView = FileSystems.getDefault().supportedFileAttributeViews();

	if (fileAttributeView.contains("posix")) {
		final Set<PosixFilePermission> permissions;
		try {
			permissions = Files.getPosixFilePermissions(helm);
		} catch (UnsupportedOperationException e) {
			getLog().debug("Exec file permission is not set", e);
			return;
		}
		permissions.add(PosixFilePermission.OWNER_EXECUTE);
		Files.setPosixFilePermissions(helm, permissions);

	} else if (fileAttributeView.contains("acl")) {
		String username = System.getProperty("user.name");
		UserPrincipal userPrincipal = FileSystems.getDefault().getUserPrincipalLookupService().lookupPrincipalByName(username);
		AclEntry aclEntry = AclEntry.newBuilder().setPermissions(AclEntryPermission.EXECUTE).setType(AclEntryType.ALLOW).setPrincipal(userPrincipal).build();

		AclFileAttributeView acl = Files.getFileAttributeView(helm, AclFileAttributeView.class, LinkOption.NOFOLLOW_LINKS);
		List<AclEntry> aclEntries = acl.getAcl();
		aclEntries.add(aclEntry);
		acl.setAcl(aclEntries);
	}
}
 
Example 4
Source Project: qpid-broker-j   File: FileHelperTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWriteFileSafely() throws Exception
{
    Path path = _fileHelper.createNewFile(_testFile, TEST_FILE_PERMISSIONS);
    _fileHelper.writeFileSafely(path, new BaseAction<File, IOException>()
    {
        @Override
        public void performAction(File file) throws IOException
        {
            Files.write(file.toPath(), "test".getBytes("UTF8"));
            assertEquals("Unexpected name", _testFile.getAbsolutePath() + ".tmp", file.getPath());
        }
    });

    assertTrue("File was not created", path.toFile().exists());

    if (Files.getFileAttributeView(path, PosixFileAttributeView.class) != null)
    {
        assertPermissions(path);
    }

    String content =  new String(Files.readAllBytes(path), "UTF-8");
    assertEquals("Unexpected file content", "test", content);
}
 
Example 5
Source Project: blog-sharon   File: HaloUtils.java    License: 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 6
private void makeKeyFileReadOnly(File file) throws IOException
{
    if(isPosixFileSystem(file))
    {
        Files.setPosixFilePermissions(file.toPath(), EnumSet.of(PosixFilePermission.OWNER_READ));
    }
    else if(isAclFileSystem(file))
    {
        AclFileAttributeView attributeView = Files.getFileAttributeView(file.toPath(), AclFileAttributeView.class);
        ArrayList<AclEntry> acls = new ArrayList<>(attributeView.getAcl());
        ListIterator<AclEntry> iter = acls.listIterator();
        file.setReadOnly();
        while(iter.hasNext())
        {
            AclEntry acl = iter.next();
            Set<AclEntryPermission> originalPermissions = acl.permissions();
            Set<AclEntryPermission> updatedPermissions = EnumSet.copyOf(originalPermissions);

            if(updatedPermissions.removeAll(EnumSet.of(AclEntryPermission.APPEND_DATA,
                                                       AclEntryPermission.DELETE,
                                                       AclEntryPermission.EXECUTE,
                                                       AclEntryPermission.WRITE_ACL,
                                                       AclEntryPermission.WRITE_DATA,
                                                       AclEntryPermission.WRITE_ATTRIBUTES,
                                                       AclEntryPermission.WRITE_NAMED_ATTRS,
                                                       AclEntryPermission.WRITE_OWNER)))
            {
                AclEntry.Builder builder = AclEntry.newBuilder(acl);
                builder.setPermissions(updatedPermissions);
                iter.set(builder.build());
            }
        }
        attributeView.setAcl(acls);
    }
    else
    {
        throw new IllegalArgumentException(ILLEGAL_ARG_EXCEPTION);
    }
}
 
Example 7
private static List<FileAttribute<Set<PosixFilePermission>>> getPosixAttributes(Path file) throws IOException {
    if (Files.exists(file) && supportsFileOwnerAttributeView(file, PosixFileAttributeView.class)) {
        PosixFileAttributeView posixView = Files.getFileAttributeView(file, PosixFileAttributeView.class);
        if (posixView != null) {
            return Collections.singletonList(PosixFilePermissions.asFileAttribute(posixView.readAttributes().permissions()));
        }
    }
    return Collections.emptyList();
}
 
Example 8
@Override
public <V extends FileAttributeView> V getFileAttributeView(Path file,
                                                            Class<V> type,
                                                            LinkOption... options)
{
    return Files.getFileAttributeView(unwrap(file), type, options);
}
 
Example 9
@Test
public void testPolicy() throws Exception {
    //System.setProperty("log4j2.debug", "true");
    //System.setProperty("log4j2.StatusLogger.level", "trace");
    final Configuration configuration = new DefaultConfiguration();
    final Path target = Paths.get(TARGET_FILE);
    target.toFile().getParentFile().mkdirs();
    final long timeStamp = System.currentTimeMillis() - (1000 * 60 * 60 * 24);
    final String expectedDate = formatter.format(timeStamp);
    final String rolledFileName = ROLLED_FILE_PREFIX + expectedDate + ROLLED_FILE_SUFFIX;
    final Path rolled = Paths.get(rolledFileName);
    final long copied;
    try (final InputStream is = new ByteArrayInputStream(TEST_DATA.getBytes("UTF-8"))) {
        copied = Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING);
    }
    final long size = Files.size(target);
    assertTrue(size > 0);
    assertEquals(copied, size);

    final FileTime fileTime = FileTime.fromMillis(timeStamp);
    final BasicFileAttributeView attrs = Files.getFileAttributeView(target, BasicFileAttributeView.class);
    attrs.setTimes(fileTime, fileTime, fileTime);
    final PatternLayout layout = PatternLayout.newBuilder().setPattern("%msg").setConfiguration(configuration)
            .build();
    final RolloverStrategy strategy = DefaultRolloverStrategy.newBuilder().setCompressionLevelStr("0")
            .setStopCustomActionsOnError(true).setConfig(configuration).build();
    final OnStartupTriggeringPolicy policy = OnStartupTriggeringPolicy.createPolicy(1);
    try (final RollingFileManager manager = RollingFileManager.getFileManager(TARGET_FILE, TARGET_PATTERN, true,
            false, policy, strategy, null, layout, 8192, true, false, null, null, null, configuration)) {
        manager.initialize();
        final String files = Arrays.toString(new File(TARGET_FOLDER).listFiles());
        assertTrue(target.toString() + ", files = " + files, Files.exists(target));
        assertEquals(target.toString(), 0, Files.size(target));
        assertTrue("Missing: " + rolled.toString() + ", files on disk = " + files, Files.exists(rolled));
        assertEquals(rolled.toString(), size, Files.size(rolled));
    }
}
 
Example 10
Source Project: logging-log4j2   File: FileUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Define file posix attribute view on a path/file.
 *
 * @param path Target path
 * @param filePermissions Permissions to apply
 * @param fileOwner File owner
 * @param fileGroup File group
 * @throws IOException If IO error during definition of file attribute view
 */
public static void defineFilePosixAttributeView(final Path path,
        final Set<PosixFilePermission> filePermissions,
        final String fileOwner,
        final String fileGroup) throws IOException {
    final PosixFileAttributeView view = Files.getFileAttributeView(path, PosixFileAttributeView.class);
    if (view != null) {
        final UserPrincipalLookupService lookupService = FileSystems.getDefault()
                .getUserPrincipalLookupService();
        if (fileOwner != null) {
            final UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(fileOwner);
            if (userPrincipal != null) {
                // If not sudoers member, it will throw Operation not permitted
                // Only processes with an effective user ID equal to the user ID
                // of the file or with appropriate privileges may change the ownership of a file.
                // If _POSIX_CHOWN_RESTRICTED is in effect for path
                view.setOwner(userPrincipal);
            }
        }
        if (fileGroup != null) {
            final GroupPrincipal groupPrincipal = lookupService.lookupPrincipalByGroupName(fileGroup);
            if (groupPrincipal != null) {
                // The current user id should be members of this group,
                // if not will raise Operation not permitted
                view.setGroup(groupPrincipal);
            }
        }
        if (filePermissions != null) {
            view.setPermissions(filePermissions);
        }
    }
}
 
Example 11
Source Project: n4js   File: CommandRebuildTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void setFileCreationDate(Path filePath) throws IOException {
	BasicFileAttributeView attributes = Files.getFileAttributeView(filePath, BasicFileAttributeView.class);
	FileTime time = FileTime.fromMillis(FILE_TIME_MILLISECONDS);
	attributes.setTimes(time, time, time);

	FileTime fileTime = Files.readAttributes(filePath, BasicFileAttributes.class).lastModifiedTime();
	assertEquals(FILE_TIME_MILLISECONDS, fileTime.toMillis());
}
 
Example 12
Source Project: lucene-solr   File: SolrCLI.java    License: Apache License 2.0 5 votes vote down vote up
public static String userForDir(Path pathToDir) {
  try {
    FileOwnerAttributeView ownerAttributeView = Files.getFileAttributeView(pathToDir, FileOwnerAttributeView.class);
    return ownerAttributeView.getOwner().getName();
  } catch (IOException e) {
    return "N/A";
  }
}
 
Example 13
/**
 * Sets the creationTime attribute
 */
private static void setCreationTime(Path file, FileTime time) throws IOException {
    BasicFileAttributeView view =
        Files.getFileAttributeView(file, BasicFileAttributeView.class);
    view.setTimes(null, null, time);
}
 
Example 14
private boolean isPosixFileSystem(File file) throws IOException
{
    return Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class) != null;
}
 
Example 15
@Override
public void testCopy() throws Exception {
	super.testCopy();
	
	CloverURI source;
	CloverURI target;
	CopyResult result;
	
	source = relativeURI("W.TMP");
	if (manager.exists(source)) { // case insensitive file system
		target = relativeURI("w.tmp");
		result = manager.copy(source, target);
		assertFalse(result.success());
		assertTrue(manager.exists(source));
	}
	
	{
		// CLO-4658:
		source = relativeURI("unreadable.tmp");
		target = relativeURI("unreadable_destination/");
		manager.create(source);
		manager.create(target);
		File file = new File(source.getAbsoluteURI().getSingleURI().toURI());
		Path path = file.toPath();
		assertTrue(file.exists());
		if (!file.setReadable(false)) {
			AclFileAttributeView view = Files.getFileAttributeView(path, AclFileAttributeView.class);
			UserPrincipal owner = view.getOwner();
			List<AclEntry> acl = view.getAcl();
			for (ListIterator<AclEntry> it = acl.listIterator(); it.hasNext(); ) {
				AclEntry entry = it.next();
				if (entry.principal().equals(owner)) {
					Set<AclEntryPermission> permissions = entry.permissions();
					permissions.remove(AclEntryPermission.READ_DATA);
					AclEntry.Builder builder = AclEntry.newBuilder(entry);
					builder.setPermissions(permissions);
					it.set(builder.build());
					break;
				}
			}
			view.setAcl(acl);
		}
		assertFalse(Files.isReadable(path));
		result = manager.copy(source, target);
		assertFalse(result.success());
		assertFalse(manager.exists(relativeURI("unreadable_destination/unreadable.tmp")));
	}
	
}
 
Example 16
/**
 * Sets the creationTime attribute
 */
private static void setCreationTime(Path file, FileTime time) throws IOException {
    BasicFileAttributeView view =
        Files.getFileAttributeView(file, BasicFileAttributeView.class);
    view.setTimes(null, null, time);
}
 
Example 17
Source Project: ecs-sync   File: PreserveFilters.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void filter(ObjectContext objectContext) {
    getNext().filter(objectContext);

    File file = target.createFile(objectContext.getTargetId());
    if (file == null) throw new RuntimeException("could not get target file");
    Path path = file.toPath();

    ObjectMetadata metadata = objectContext.getObject().getMetadata();
    boolean link = AbstractFilesystemStorage.TYPE_LINK.equals(metadata.getContentType());

    // set file times
    // Note: directory times may be overwritten if any children are modified
    if (!link) { // cannot set times for symlinks in Java
        setFileTimesCompat(path, metadata);
        setFileTimes(path, metadata);
    }

    // uid/gid
    String uid = metadata.getUserMetadataValue(META_OWNER);
    String gid = metadata.getUserMetadataValue(META_GROUP);

    // mode
    String mode = metadata.getUserMetadataValue(META_PERMISSIONS);

    // owner/group names (legacy)
    String ownerName = metadata.getUserMetadataValue(OLD_META_POSIX_OWNER);
    String groupOwnerName = metadata.getUserMetadataValue(OLD_META_POSIX_GROUP_OWNER);

    // permissions (legacy)
    Set<PosixFilePermission> permissions = null;
    if (metadata.getUserMetadataValue(OLD_META_POSIX_MODE) != null)
        permissions = PosixFilePermissions.fromString(metadata.getUserMetadataValue(OLD_META_POSIX_MODE));

    LinkOption[] linkOptions = link ? new LinkOption[]{LinkOption.NOFOLLOW_LINKS} : new LinkOption[0];

    try {
        PosixFileAttributeView attributeView = Files.getFileAttributeView(path, PosixFileAttributeView.class, linkOptions);

        // set permission bits
        // cannot set mode of symlinks in Java
        if (mode != null && !link) {
            log.debug("setting mode of {} to {}", path.toString(), mode);
            Files.setAttribute(path, "unix:mode", Integer.parseInt(mode, 8));
        } else if (permissions != null && !link) {
            log.debug("setting permissions of {} to {}", path.toString(), metadata.getUserMetadataValue(OLD_META_POSIX_MODE));
            attributeView.setPermissions(permissions);
        }

        // set ownership
        // uid/gid takes priority
        if (uid != null) {
            log.debug("setting ownership of {} to {}.{}", path.toString(), uid, gid);
            Files.setAttribute(path, "unix:uid", Integer.parseInt(uid), linkOptions);
            Files.setAttribute(path, "unix:gid", Integer.parseInt(gid), linkOptions);
        } else {
            UserPrincipalLookupService lookupService = path.getFileSystem().getUserPrincipalLookupService();

            // set owner/group-owner (look up principals first)
            if (ownerName != null) {
                log.debug("setting ownership of {} to {}", path.toString(), ownerName);
                attributeView.setOwner(lookupService.lookupPrincipalByName(ownerName));
            }
            if (groupOwnerName != null) {
                log.debug("setting group-ownership of {} to {}", path.toString(), groupOwnerName);
                attributeView.setGroup(lookupService.lookupPrincipalByGroupName(groupOwnerName));
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("could not write file attributes for " + path.toString(), e);
    }

    PreserveFileAttributesFilter.removeMetadata(objectContext.getObject());
    removeLegacyMetadata(objectContext.getObject());
}
 
Example 18
public static void main(String[] args)
    throws InterruptedException, IOException {

    // Use 'which' to verify that 'nc' is available and skip the test
    // if it is not.
    Process proc = Runtime.getRuntime().exec("which nc");
    InputStream stdout = proc.getInputStream();
    int b = stdout.read();
    proc.destroy();
    if (b == -1) {
        System.err.println("Netcat command unavailable; skipping test.");
        return;
    }

    // Create a new sub-directory of the nominal test directory in which
    // 'nc' will create the socket file.
    String testSubDir = System.getProperty("test.dir", ".")
        + File.separator + TEST_SUB_DIR;
    Path socketTestDir = Paths.get(testSubDir);
    Files.createDirectory(socketTestDir);

    // Set the path of the socket file.
    String socketFilePath = testSubDir + File.separator
        + SOCKET_FILE_NAME;

    // Create a process which executes the nc (netcat) utility to create
    // a socket file at the indicated location.
    FileSystem fs = FileSystems.getDefault();
    try (WatchService ws = fs.newWatchService()) {
        // Watch the test sub-directory to receive notification when an
        // entry, i.e., the socket file, is added to the sub-directory.
        WatchKey wk = socketTestDir.register(ws,
                StandardWatchEventKinds.ENTRY_CREATE);

        // Execute the 'nc' command.
        proc = Runtime.getRuntime().exec(CMD_BASE + " " + socketFilePath);

        // Wait until the socket file is created.
        WatchKey key = ws.take();
        if (key != wk) {
            throw new RuntimeException("Unknown entry created - expected: "
                + wk.watchable() + ", actual: " + key.watchable());
        }
        wk.cancel();
    }

    // Verify that the socket file in fact exists.
    Path socketPath = fs.getPath(socketFilePath);
    if (!Files.exists(socketPath)) {
        throw new RuntimeException("Socket file " + socketFilePath
            + " was not created by \"nc\" command.");
    }

    // Retrieve the most recent access and modification times of the
    // socket file; print the values.
    BasicFileAttributeView attributeView = Files.getFileAttributeView(
            socketPath, BasicFileAttributeView.class);
    BasicFileAttributes oldAttributes = attributeView.readAttributes();
    FileTime oldAccessTime = oldAttributes.lastAccessTime();
    FileTime oldModifiedTime = oldAttributes.lastModifiedTime();
    System.out.println("Old times: " + oldAccessTime
        + " " + oldModifiedTime);

    // Calculate the time to which the access and modification times of the
    // socket file will be changed.
    FileTime newFileTime =
        FileTime.fromMillis(oldAccessTime.toMillis() + 1066);

    try {
        // Set the access and modification times of the socket file.
        attributeView.setTimes(newFileTime, newFileTime, null);

        // Retrieve the updated access and modification times of the
        // socket file; print the values.
        FileTime newAccessTime = null;
        FileTime newModifiedTime = null;
        BasicFileAttributes newAttributes = attributeView.readAttributes();
        newAccessTime = newAttributes.lastAccessTime();
        newModifiedTime = newAttributes.lastModifiedTime();
        System.out.println("New times: " + newAccessTime + " "
            + newModifiedTime);

        // Verify that the updated times have the expected values.
        if ((newAccessTime != null && !newAccessTime.equals(newFileTime))
            || (newModifiedTime != null
                && !newModifiedTime.equals(newFileTime))) {
            throw new RuntimeException("Failed to set correct times.");
        }
    } finally {
        // Destry the process running netcat and delete the socket file.
        proc.destroy();
        Files.delete(socketPath);
    }
}
 
Example 19
Source Project: tutorials   File: BasicAttribsIntegrationTest.java    License: MIT License 4 votes vote down vote up
@BeforeClass
public static void setup() throws IOException {
    Path home = Paths.get(HOME);
    BasicFileAttributeView basicView = Files.getFileAttributeView(home, BasicFileAttributeView.class);
    basicAttribs = basicView.readAttributes();
}
 
Example 20
/**
 * Sets the creationTime attribute
 */
private static void setCreationTime(Path file, FileTime time) throws IOException {
    BasicFileAttributeView view =
        Files.getFileAttributeView(file, BasicFileAttributeView.class);
    view.setTimes(null, null, time);
}