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

The following examples show how to use java.nio.file.Files#setPosixFilePermissions() . 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: 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 2
Source Project: copybara   File: FileUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tries to add the Posix permissions if the file belongs to a Posix filesystem. This is an
 * addition, which means that no permissions are removed.
 *
 * <p>For Windows type filesystems, it uses setReadable/setWritable/setExecutable, which is only
 * supported for the owner, and ignores the rest of permissions.
 */
public static void addPermissions(Path path, Set<PosixFilePermission> permissionsToAdd)
    throws IOException {
  if (path.getFileSystem().supportedFileAttributeViews().contains("posix")) {
    Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(path);
    permissions.addAll(permissionsToAdd);
    Files.setPosixFilePermissions(path, permissions);
  } else {
    File file = path.toFile();
    if (permissionsToAdd.contains(PosixFilePermission.OWNER_READ)) {
      if (!file.setReadable(true)) {
        throw new IOException("Could not set 'readable' permission for file: " + path);
      }
    }
    if (permissionsToAdd.contains(PosixFilePermission.OWNER_WRITE)) {
      if (!file.setWritable(true)) {
        throw new IOException("Could not set 'writable' permission for file: " + path);
      }
    }
    if (permissionsToAdd.contains(PosixFilePermission.OWNER_EXECUTE)) {
      if (!file.setExecutable(true)) {
        throw new IOException("Could not set 'executable' permission for file: " + path);
      }
    }
  }
}
 
Example 3
Source Project: emissary   File: WhatCommandIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = RuntimeException.class)
public void unreadableInput() throws Exception {
    // setup
    arguments.add(PROJECT_BASE_ARGS[0]);
    arguments.add(baseDir.toString());
    arguments.add(INPUT_ARGS[0]);
    Set<PosixFilePermission> perms = new HashSet<>();
    perms.add(PosixFilePermission.OWNER_WRITE);
    Files.setPosixFilePermissions(inputDir, perms);
    arguments.add(inputDir.toAbsolutePath().toString());
    command = WhatCommand.parse(WhatCommand.class, arguments);

    // test
    command.run(new JCommander());

    // verify
    exception.expectMessage("The option '-i' was configured with path '" + inputDir + "' which is not readable");
}
 
Example 4
Source Project: ambry   File: IndexSegment.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Persist the bloom filter.
 * @throws StoreException
 */
private void persistBloomFilter() throws StoreException {
  try {
    CrcOutputStream crcStream = new CrcOutputStream(new FileOutputStream(bloomFile));
    DataOutputStream stream = new DataOutputStream(crcStream);
    FilterFactory.serialize(bloomFilter, stream);
    long crcValue = crcStream.getValue();
    stream.writeLong(crcValue);
    stream.close();
    if (config.storeSetFilePermissionEnabled) {
      Files.setPosixFilePermissions(bloomFile.toPath(), config.storeDataFilePermission);
    }
  } catch (IOException e) {
    StoreErrorCodes errorCode = StoreException.resolveErrorCode(e);
    throw new StoreException(errorCode.toString() + " while trying to persist bloom filter", e, errorCode);
  }
}
 
Example 5
private static void makeFileNonReadable(String file) throws IOException {
    Path filePath = Paths.get(file);
    Set<String> supportedAttr = filePath.getFileSystem().supportedFileAttributeViews();

    if (supportedAttr.contains("posix")) {
        Files.setPosixFilePermissions(filePath, PosixFilePermissions.fromString("-w--w----"));
    } else if (supportedAttr.contains("acl")) {
        UserPrincipal fileOwner = Files.getOwner(filePath);

        AclFileAttributeView view = Files.getFileAttributeView(filePath, AclFileAttributeView.class);

        AclEntry entry = AclEntry.newBuilder()
                .setType(AclEntryType.DENY)
                .setPrincipal(fileOwner)
                .setPermissions(AclEntryPermission.READ_DATA)
                .build();

        List<AclEntry> acl = view.getAcl();
        acl.add(0, entry);
        view.setAcl(acl);
    }
}
 
Example 6
@Test
public void testCopyDirectory_posixPermissions() throws IOException {
  assumeTrue(!System.getProperty("os.name").startsWith("Windows"));

  Set<PosixFilePermission> permission = Sets.newHashSet();
  permission.add(PosixFilePermission.OWNER_READ);
  permission.add(PosixFilePermission.GROUP_READ);
  permission.add(PosixFilePermission.OTHERS_READ);
  permission.add(PosixFilePermission.OTHERS_EXECUTE);
  permission.add(PosixFilePermission.OTHERS_WRITE);

  Path src = testDir.newFolder("src").toPath();
  Path dest = testDir.newFolder("dest").toPath();

  Path rootFile = Files.createFile(src.resolve("root1.file"));
  Assert.assertNotEquals(
      "This test is useless - modified permissions are default permissions",
      Files.getPosixFilePermissions(rootFile),
      permission);
  Files.setPosixFilePermissions(rootFile, permission);

  FileUtil.copyDirectory(src, dest);

  Assert.assertEquals(
      permission, Files.getPosixFilePermissions(dest.resolve(src.relativize(rootFile))));
}
 
Example 7
private static String startServer(String authenticationType) throws  Exception {
  int port = NetworkUtils.getRandomPort();

  Configuration conf = new Configuration();
  conf.set(WebServerTask.HTTP_PORT_KEY, port);
  conf.set(WebServerTask.AUTHENTICATION_KEY, authenticationType);
  Writer writer = writer = new FileWriter(new File(System.getProperty(RuntimeModule.SDC_PROPERTY_PREFIX +
    RuntimeInfo.CONFIG_DIR), "sdc.properties"));
  conf.save(writer);
  writer.close();


  File realmFile = new File(System.getProperty(RuntimeModule.SDC_PROPERTY_PREFIX +
    RuntimeInfo.CONFIG_DIR), authenticationType + "-realm.properties");
  writer = new FileWriter(realmFile);
  writer.write("admin:   MD5:21232f297a57a5a743894a0e4a801fc3,user,email:,admin\n");
  writer.write("multiRoleUser:   MD5:21232f297a57a5a743894a0e4a801fc3,user,email:,creator,manager\n");
  writer.close();
  Files.setPosixFilePermissions(realmFile.toPath(), ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE,
    PosixFilePermission.OWNER_READ,
    PosixFilePermission.OWNER_WRITE));

  ObjectGraph dagger = ObjectGraph.create(MainStandalonePipelineManagerModule.class);

  runtimeInfo = dagger.get(RuntimeInfo.class);
  runtimeInfo.setAttribute(RuntimeInfo.LOG4J_CONFIGURATION_URL_ATTR, new URL("file://" + baseDir + "/log4j.properties"));

  server = dagger.get(TaskWrapper.class);
  server.init();
  server.run();

  return "http://127.0.0.1:" + port;
}
 
Example 8
Source Project: cloudstack   File: DiagnosticsHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static void setDirFilePermissions(Path path) throws java.io.IOException {
    Set<PosixFilePermission> perms = Files.readAttributes(path, PosixFileAttributes.class).permissions();
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.GROUP_EXECUTE);
    perms.add(PosixFilePermission.OTHERS_WRITE);
    perms.add(PosixFilePermission.OTHERS_READ);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);
    Files.setPosixFilePermissions(path, perms);
}
 
Example 9
Source Project: flink   File: JarDeleteHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
private void makeJarDirReadOnly() {
	try {
		Files.setPosixFilePermissions(jarDir, new HashSet<>(Arrays.asList(
			PosixFilePermission.OTHERS_READ,
			PosixFilePermission.GROUP_READ,
			PosixFilePermission.OWNER_READ,
			PosixFilePermission.OTHERS_EXECUTE,
			PosixFilePermission.GROUP_EXECUTE,
			PosixFilePermission.OWNER_EXECUTE)));
	} catch (final Exception e) {
		Assume.assumeNoException(e);
	}
}
 
Example 10
static final void setGettysburgAddressFileToReadOnly() {
  File file = getResourceFile("GettysburgAddress.txt");
  try {
  Files.setPosixFilePermissions(file.toPath(), PosixFilePermissions.fromString("r--r--r--"));
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 11
private static String buildScriptCommandLine() throws IOException {
    if (System.getProperties().getProperty("os.name").contains("Windows")) {
        return Paths.get(JavaMain.class.getResource("/script/demo.bat").getPath().substring(1)).toString();
    }
    Path result = Paths.get(JavaMain.class.getResource("/script/demo.sh").getPath());
    Files.setPosixFilePermissions(result, PosixFilePermissions.fromString("rwxr-xr-x"));
    return result.toString();
}
 
Example 12
Source Project: netbeans   File: PasswordFile.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Update password file permissions when finished.
 * <p/>
 * File should exist.
 */
private boolean finishFilePosix() {
    final String METHOD = "finishFilePosix";
    boolean success = false;
    try {
        Files.setPosixFilePermissions(file, FINAL_FILE_PERMISSIONS);
        success = true;
    } catch (UnsupportedOperationException uoe) {
        LOGGER.log(Level.INFO, METHOD, "unsupported", file.toString());
    } catch (IOException ioe) {
        LOGGER.log(Level.INFO, METHOD, "ioException", ioe);
    }
    return success;
}
 
Example 13
Source Project: nifi   File: RunNiFi.java    License: Apache License 2.0 5 votes vote down vote up
private synchronized void savePidProperties(final Properties pidProperties, final Logger logger) throws IOException {
    final String pid = pidProperties.getProperty(PID_KEY);
    if (!StringUtils.isBlank(pid)) {
        writePidFile(pid, logger);
    }

    final File statusFile = getStatusFile(logger);
    if (statusFile.exists() && !statusFile.delete()) {
        logger.warn("Failed to delete {}", statusFile);
    }

    if (!statusFile.createNewFile()) {
        throw new IOException("Failed to create file " + statusFile);
    }

    try {
        final Set<PosixFilePermission> perms = new HashSet<>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(statusFile.toPath(), perms);
    } catch (final Exception e) {
        logger.warn("Failed to set permissions so that only the owner can read status file {}; "
                + "this may allows others to have access to the key needed to communicate with NiFi. "
                + "Permissions should be changed so that only the owner can read this file", statusFile);
    }

    try (final FileOutputStream fos = new FileOutputStream(statusFile)) {
        pidProperties.store(fos, null);
        fos.getFD().sync();
    }

    logger.debug("Saved Properties {} to {}", new Object[]{pidProperties, statusFile});
}
 
Example 14
Source Project: jdk8u60   File: DflCache.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void makeMine(Path p) throws IOException {
    // chmod to owner-rw only, otherwise MIT krb5 rejects
    try {
        Set<PosixFilePermission> attrs = new HashSet<>();
        attrs.add(PosixFilePermission.OWNER_READ);
        attrs.add(PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(p, attrs);
    } catch (UnsupportedOperationException uoe) {
        // No POSIX permission. That's OK.
    }
}
 
Example 15
Source Project: nomulus   File: GpgSystemCommandRule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws IOException, InterruptedException {
  checkState(Objects.equals(cwd, DEV_NULL));
  String tmpRootDirString = System.getenv("TMPDIR");
  // Create the working directory for the forked process on Temp file system. Create under the
  // path specified by 'TMPDIR' envrionment variable if defined, otherwise create under the
  // runtime's default (typically /tmp).
  cwd =
      isNullOrEmpty(tmpRootDirString)
          ? File.createTempFile(TEMP_FILE_PREFIX, "")
          : File.createTempFile(TEMP_FILE_PREFIX, "", new File(tmpRootDirString));
  cwd.delete();
  cwd.mkdir();
  conf = new File(cwd, ".gnupg");
  conf.mkdir();
  Files.setPosixFilePermissions(conf.toPath(), PosixFilePermissions.fromString("rwx------"));
  env =
      new String[] {
        "PATH=" + System.getenv("PATH"), "GNUPGHOME=" + conf.getAbsolutePath(),
      };

  Process pid = exec("gpg", "--import");
  publicKeyring.copyTo(pid.getOutputStream());
  pid.getOutputStream().close();
  int returnValue = pid.waitFor();
  assertWithMessage(
          String.format("Failed to import public keyring: \n%s", slurp(pid.getErrorStream())))
      .that(returnValue)
      .isEqualTo(0);

  pid = exec("gpg", "--allow-secret-key-import", "--import");
  privateKeyring.copyTo(pid.getOutputStream());
  pid.getOutputStream().close();
  returnValue = pid.waitFor();
  assertWithMessage(
          String.format("Failed to import private keyring: \n%s", slurp(pid.getErrorStream())))
      .that(returnValue)
      .isEqualTo(0);
}
 
Example 16
/**
 * One test run.
 *
 * @param label test label
 * @param lc lib of client
 * @param ls lib of server
 * @param lb lib of backend
 */
private static void once(String label, String lc, String ls, String lb)
        throws Exception {

    Proc pc = proc(lc)
            .args("client", lc == null ? "j" : "n")
            .perm(new javax.security.auth.kerberos.ServicePermission(
                    "krbtgt/" + REALM + "@" + REALM, "initiate"))
            .perm(new javax.security.auth.kerberos.ServicePermission(
                    SERVER + "@" + REALM, "initiate"))
            .perm(new javax.security.auth.kerberos.DelegationPermission(
                    "\"" + SERVER + "@" + REALM + "\" " +
                            "\"krbtgt/" + REALM + "@" + REALM + "\""))
            .debug(label + "-C");
    if (lc == null) {
        // for Krb5LoginModule::promptForName
        pc.perm(new PropertyPermission("user.name", "read"));
    } else {
        Files.copy(Paths.get("base.ccache"), Paths.get(label + ".ccache"));
        Set<PosixFilePermission> perms = new HashSet<>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(Paths.get(label + ".ccache"),
                                      Collections.unmodifiableSet(perms));
        pc.env("KRB5CCNAME", label + ".ccache");
        // Do not try system ktab if ccache fails
        pc.env("KRB5_KTNAME", "none");
    }
    pc.start();

    Proc ps = proc(ls)
            .args("server", ls == null ? "j" : "n")
            .perm(new javax.security.auth.kerberos.ServicePermission(
                    SERVER + "@" + REALM, "accept"))
            .perm(new javax.security.auth.kerberos.ServicePermission(
                    BACKEND + "@" + REALM, "initiate"))
            .debug(label + "-S");
    if (ls == null) {
        ps.perm(new PrivateCredentialPermission(
                "javax.security.auth.kerberos.KeyTab * \"*\"", "read"))
            .perm(new java.io.FilePermission(KTAB_S, "read"));
    } else {
        ps.env("KRB5_KTNAME", KTAB_S);
    }
    ps.start();

    Proc pb = proc(lb)
            .args("backend", lb == null ? "j" : "n")
            .perm(new javax.security.auth.kerberos.ServicePermission(
                    BACKEND + "@" + REALM, "accept"))
            .debug(label + "-B");
    if (lb == null) {
        pb.perm(new PrivateCredentialPermission(
                "javax.security.auth.kerberos.KeyTab * \"*\"", "read"))
            .perm(new java.io.FilePermission(KTAB_B, "read"));
    } else {
        pb.env("KRB5_KTNAME", KTAB_B);
    }
    pb.start();

    // Client and server
    ps.println(pc.readData()); // AP-REQ
    pc.println(ps.readData()); // AP-REP

    ps.println(pc.readData()); // KRB-PRIV
    ps.println(pc.readData()); // KRB-SAFE

    // Server and backend
    pb.println(ps.readData()); // AP-REQ

    ps.println(pb.readData()); // KRB-PRIV
    ps.println(pb.readData()); // KRB-SAFE

    if ((pc.waitFor() | ps.waitFor() | pb.waitFor()) != 0) {
        throw new Exception("Process failed");
    }
}
 
Example 17
/**
 * One test run.
 *
 * @param label test label
 * @param lc lib of client
 * @param ls lib of server
 * @param lb lib of backend
 */
private static void once(String label, String lc, String ls, String lb)
        throws Exception {

    Proc pc = proc(lc)
            .args("client", lc == null ? "j" : "n")
            .perm(new javax.security.auth.kerberos.ServicePermission(
                    "krbtgt/" + REALM + "@" + REALM, "initiate"))
            .perm(new javax.security.auth.kerberos.ServicePermission(
                    SERVER + "@" + REALM, "initiate"))
            .perm(new javax.security.auth.kerberos.DelegationPermission(
                    "\"" + SERVER + "@" + REALM + "\" " +
                            "\"krbtgt/" + REALM + "@" + REALM + "\""))
            .debug(label + "-C");
    if (lc == null) {
        // for Krb5LoginModule::promptForName
        pc.perm(new PropertyPermission("user.name", "read"));
    } else {
        Files.copy(Paths.get("base.ccache"), Paths.get(label + ".ccache"));
        Set<PosixFilePermission> perms = new HashSet<>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(Paths.get(label + ".ccache"),
                                      Collections.unmodifiableSet(perms));
        pc.env("KRB5CCNAME", label + ".ccache");
        // Do not try system ktab if ccache fails
        pc.env("KRB5_KTNAME", "none");
    }
    pc.start();

    Proc ps = proc(ls)
            .args("server", ls == null ? "j" : "n")
            .perm(new javax.security.auth.kerberos.ServicePermission(
                    SERVER + "@" + REALM, "accept"))
            .perm(new javax.security.auth.kerberos.ServicePermission(
                    BACKEND + "@" + REALM, "initiate"))
            .debug(label + "-S");
    if (ls == null) {
        ps.perm(new PrivateCredentialPermission(
                "javax.security.auth.kerberos.KeyTab * \"*\"", "read"))
            .perm(new java.io.FilePermission(KTAB_S, "read"));
    } else {
        ps.env("KRB5_KTNAME", KTAB_S);
    }
    ps.start();

    Proc pb = proc(lb)
            .args("backend", lb == null ? "j" : "n")
            .perm(new javax.security.auth.kerberos.ServicePermission(
                    BACKEND + "@" + REALM, "accept"))
            .debug(label + "-B");
    if (lb == null) {
        pb.perm(new PrivateCredentialPermission(
                "javax.security.auth.kerberos.KeyTab * \"*\"", "read"))
            .perm(new java.io.FilePermission(KTAB_B, "read"));
    } else {
        pb.env("KRB5_KTNAME", KTAB_B);
    }
    pb.start();

    // Client and server
    ps.println(pc.readData()); // AP-REQ
    pc.println(ps.readData()); // AP-REP

    ps.println(pc.readData()); // KRB-PRIV
    ps.println(pc.readData()); // KRB-SAFE

    // Server and backend
    pb.println(ps.readData()); // AP-REQ

    ps.println(pb.readData()); // KRB-PRIV
    ps.println(pb.readData()); // KRB-SAFE

    if ((pc.waitFor() | ps.waitFor() | pb.waitFor()) != 0) {
        throw new Exception("Process failed");
    }
}
 
Example 18
private void makeFileReadable(Path file) throws Exception {
  if (Platform.detect() == Platform.WINDOWS) {
    return;
  }
  Files.setPosixFilePermissions(file, EnumSet.of(OWNER_READ));
}
 
Example 19
private Path writePrivateKey(String fileName, String key) throws IOException {
    Path privateKey = Files.write(sshDir.resolve(fileName), Collections.singleton(key));
    return SystemUtils.IS_OS_WINDOWS
            ? privateKey
            : Files.setPosixFilePermissions(privateKey, new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)));
}
 
Example 20
private void extractZip( String zipFilePath, String outputDirPath ) {

        ZipArchiveEntry zipEntry = null;
        File outputDir = new File(outputDirPath);
        outputDir.mkdirs();//check if the dir is created

        try (ZipFile zipFile = new ZipFile(zipFilePath)) {
            Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
            int unixPermissions = 0;

            while (entries.hasMoreElements()) {
                zipEntry = entries.nextElement();
                if (log.isDebugEnabled()) {
                    log.debug("Extracting " + zipEntry.getName());
                }
                File entryDestination = new File(outputDirPath, zipEntry.getName());

                unixPermissions = zipEntry.getUnixMode();
                if (zipEntry.isDirectory()) {
                    entryDestination.mkdirs();
                } else {
                    entryDestination.getParentFile().mkdirs();
                    InputStream in = null;
                    OutputStream out = null;

                    in = zipFile.getInputStream(zipEntry);
                    out = new BufferedOutputStream(new FileOutputStream(entryDestination));

                    IoUtils.copyStream(in, out);
                }
                if (OperatingSystemType.getCurrentOsType() != OperatingSystemType.WINDOWS) {//check if the OS is UNIX
                    // set file/dir permissions, after it is created
                    Files.setPosixFilePermissions(entryDestination.getCanonicalFile().toPath(),
                                                  getPosixFilePermission(unixPermissions));
                }
            }
        } catch (Exception e) {
            String errorMsg = "Unable to unzip " + ((zipEntry != null)
                                                    ? zipEntry.getName() + " from "
                                                    : "")
                              + zipFilePath + ".Target directory '" + outputDirPath
                              + "' is in inconsistent state.";
            throw new FileSystemOperationException(errorMsg, e);
        }

    }