Java Code Examples for java.nio.file.attribute.PosixFilePermissions#asFileAttribute()

The following examples show how to use java.nio.file.attribute.PosixFilePermissions#asFileAttribute() . 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: KafkaConsumerGroupClientImpl.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 7 votes vote down vote up
private File flushPropertiesToTempFile(Map<String, Object> configProps) throws IOException {
  FileAttribute<Set<PosixFilePermission>> attributes
      = PosixFilePermissions.asFileAttribute(new HashSet<>(
          Arrays.asList(PosixFilePermission.OWNER_WRITE,
                        PosixFilePermission.OWNER_READ)));
  File configFile = Files.createTempFile("ksqlclient", "properties", attributes).toFile();
  configFile.deleteOnExit();

  try (FileOutputStream outputStream = new FileOutputStream(configFile)) {
    Properties clientProps = new Properties();
    for (Map.Entry<String, Object> property
        : configProps.entrySet()) {
      clientProps.put(property.getKey(), property.getValue());
    }
    clientProps.store(outputStream, "Configuration properties of KSQL AdminClient");
  }
  return configFile;
}
 
Example 2
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 7 votes vote down vote up
@Test
public void testCreateDirectory_withInitialAttributes() throws IOException {
  FileAttribute<Set<PosixFilePermission>> permissions =
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx"));

  Files.createDirectory(path("/foo"), permissions);

  assertThatPath("/foo")
      .isDirectory()
      .and()
      .attribute("posix:permissions")
      .is(permissions.value());

  Files.createDirectory(path("/normal"));

  assertThatPath("/normal")
      .isDirectory()
      .and()
      .attribute("posix:permissions")
      .isNot(permissions.value());
}
 
Example 3
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateSymbolicLink_withInitialAttributes() throws IOException {
  FileAttribute<Set<PosixFilePermission>> permissions =
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx"));

  Files.createSymbolicLink(path("/foo"), path("bar"), permissions);

  assertThatPath("/foo", NOFOLLOW_LINKS)
      .isSymbolicLink()
      .and()
      .attribute("posix:permissions")
      .is(permissions.value());

  Files.createSymbolicLink(path("/normal"), path("bar"));

  assertThatPath("/normal", NOFOLLOW_LINKS)
      .isSymbolicLink()
      .and()
      .attribute("posix:permissions")
      .isNot(permissions.value());
}
 
Example 4
Source File: Standard.java    From presto with Apache License 2.0 6 votes vote down vote up
public static void enablePrestoJavaDebugger(DockerContainer container, int debugPort)
{
    try {
        FileAttribute<Set<PosixFilePermission>> rwx = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx"));
        Path script = Files.createTempFile("enable-java-debugger", ".sh", rwx);
        Files.writeString(
                script,
                format(
                        "#!/bin/bash\n" +
                                "printf '%%s\\n' '%s' >> '%s'\n",
                        "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=0.0.0.0:" + debugPort,
                        CONTAINER_PRESTO_JVM_CONFIG),
                UTF_8);
        container.withCopyFileToContainer(MountableFile.forHostPath(script), "/docker/presto-init.d/enable-java-debugger.sh");

        // expose debug port unconditionally when debug is enabled
        exposePort(container, debugPort);
    }
    catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 5
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
private File createTempFileInSystemDir(String prefix, String suffix) throws IOException {
    if (isWindows()) {
        return Files.createTempFile(prefix, suffix).toFile();
    }
    Set<PosixFilePermission> ownerOnly = PosixFilePermissions.fromString("rw-------");
    FileAttribute fileAttribute = PosixFilePermissions.asFileAttribute(ownerOnly);
    return Files.createTempFile(prefix, suffix, fileAttribute).toFile();
}
 
Example 6
Source File: JImageExtractTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testExtractToReadOnlyDir() throws IOException {
    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("r-xr--r--");
    FileAttribute<Set<PosixFilePermission>> atts = PosixFilePermissions.asFileAttribute(perms);
    Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName(), atts);
    jimage("extract", "--dir", tmp.toString(), getImagePath())
            .assertFailure()
            .assertShowsError();
}
 
Example 7
Source File: ValidDirectoryWritableTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void notWritable() throws IOException {
  final FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(EnumSet.of(
      PosixFilePermission.OWNER_READ
  ));
  final Path path = createTempDirectory(attr);

  assertThrows(ConfigException.class, () -> {
    this.validator.ensureValid("testing", path.toString());
  });
}
 
Example 8
Source File: ValidFileWritableTest.java    From connect-utils with Apache License 2.0 5 votes vote down vote up
@Test
public void notWritable() throws IOException {
  final FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(EnumSet.of(
      PosixFilePermission.OWNER_READ
  ));
  final Path path = createTempFile(attr);

  assertThrows(ConfigException.class, () -> {
    this.validator.ensureValid("testing", path.toString());
  });
}
 
Example 9
Source File: TestCacheUtil.java    From rubix with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void initializeCacheDirectories() throws IOException
{
  Set<PosixFilePermission> perms =
          PosixFilePermissions.fromString("rwx------");
  FileAttribute<Set<PosixFilePermission>> attr =
          PosixFilePermissions.asFileAttribute(perms);
  Files.createDirectories(Paths.get(cacheTestDirPrefix), attr);
  for (int i = 0; i < maxDisks; i++) {
    Files.createDirectories(Paths.get(cacheTestDirPrefix, String.valueOf(i)));
  }
}
 
Example 10
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testOpenChannel_withInitialAttributes_fileExists() throws IOException {
  Files.createFile(path("/foo"));

  FileAttribute<Set<PosixFilePermission>> permissions =
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx"));
  Files.newByteChannel(path("/foo"), ImmutableSet.of(WRITE, CREATE), permissions).close();

  assertThatPath("/foo")
      .isRegularFile()
      .and()
      .attribute("posix:permissions")
      .isNot(permissions.value());
}
 
Example 11
Source File: DataStore.java    From datacollector with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an output stream for the requested file.
 *
 * After completing the write the contents must be committed using the {@link #commit(java.io.OutputStream)}
 * method and the stream must be released using the {@link #release()} method.
 *
 * Example usage:
 *
 * DataStore dataStore = new DataStore(...);
 * try (OutputStream os = dataStore.getOutputStream()) {
 *   os.write(..);
 *   dataStore.commit(os);
 * } catch (IOException e) {
 *   ...
 * } finally {
 *   dataStore.release();
 * }
 *
 * @return
 * @throws IOException
 */
public OutputStream getOutputStream() throws IOException {
  acquireLock();
  try {
    isClosed = false;
    forWrite = true;
    LOG.trace("Starts write '{}'", file);
    verifyAndRecover();
    FileAttribute permissions = DEFAULT_PERMISSIONS;
    if (Files.exists(file)) {
      permissions = PosixFilePermissions.asFileAttribute(Files.getPosixFilePermissions(file));
      Files.move(file, fileOld);
      LOG.trace("Starting write, move '{}' to '{}'", file, fileOld);
    }
    Files.createFile(fileTmp, permissions);
    OutputStream os = new ProxyOutputStream(new FileOutputStream(fileTmp.toFile())) {
      @Override
      public void close() throws IOException {
        if (isClosed) {
          return;
        }
        try {
          super.close();
        } finally {
          isClosed = true;
          stream = null;
        }
        LOG.trace("Finishes write '{}'", file);
      }
    };
    stream = os;
    return os;
  } catch (Exception ex) {
    release();
    throw ex;
  }
}
 
Example 12
Source File: EtcdContainer.java    From jetcd with Apache License 2.0 5 votes vote down vote up
private static Path createDataDirectory(String name) {
    try {
        final String prefix = "jetcd_test_" + name + "_";
        final FileAttribute<?> attribute = PosixFilePermissions.asFileAttribute(EnumSet.allOf(PosixFilePermission.class));

        // https://github.com/etcd-io/jetcd/issues/489
        // Resolve symlink (/var -> /private/var) to don't fail for Mac OS because of docker thing with /var/folders
        return Files.createTempDirectory(prefix, attribute).toRealPath();
    } catch (IOException e) {
        throw new ContainerLaunchException("Error creating data directory", e);
    }
}
 
Example 13
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testOpenChannel_withInitialAttributes_createNewFile() throws IOException {
  FileAttribute<Set<PosixFilePermission>> permissions =
      PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxrwxrwx"));
  Files.newByteChannel(path("/foo"), ImmutableSet.of(WRITE, CREATE), permissions).close();

  assertThatPath("/foo")
      .isRegularFile()
      .and()
      .attribute("posix:permissions")
      .is(permissions.value());
}
 
Example 14
Source File: ProcessFactoryImplTest.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpawnWithPersistentOutputFile() {

    class TemporaryFile implements AutoCloseable {
        private final Path path;
        private TemporaryFile() {
            String outputFileName = ProcessFactoryImplTest.class.getSimpleName() + "-temporary-test-file.out";
            FileAttribute<Set<PosixFilePermission>> fileAttribute = PosixFilePermissions.asFileAttribute(
                    PosixFilePermissions.fromString("rw-------"));
            path = uncheck(() -> Files.createTempFile(outputFileName, ".out", fileAttribute));
        }
        @Override public void close() { uncheck(() -> Files.deleteIfExists(path)); }
    }

    try (TemporaryFile outputPath = new TemporaryFile()) {
        CommandLine commandLine = mock(CommandLine.class);
        when(commandLine.getArguments()).thenReturn(List.of("program"));
        when(commandLine.programName()).thenReturn("program");
        when(commandLine.getOutputFile()).thenReturn(Optional.of(outputPath.path));
        try (ChildProcess2Impl child = processFactory.spawn(commandLine)) {
            assertEquals(outputPath.path, child.getOutputPath());
            assertTrue(Files.exists(outputPath.path));
            assertEquals("rw-------", new UnixPath(outputPath.path).getPermissions());
        }

        assertTrue(Files.exists(outputPath.path));
    }

}
 
Example 15
Source File: RunNiFi.java    From nifi with Apache License 2.0 5 votes vote down vote up
private Path createSensitiveKeyFile(File confDir) {
    Path sensitiveKeyFile = Paths.get(confDir+"/sensitive.key");

    final boolean isPosixSupported = FileSystems.getDefault().supportedFileAttributeViews().contains("posix");
    try {
        if (isPosixSupported) {
            // Initially create file with the empty permission set (so nobody can get a file descriptor on it):
            Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
            FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
            sensitiveKeyFile = Files.createFile(sensitiveKeyFile, attr);

            // Then, once created, add owner-only rights:
            perms.add(PosixFilePermission.OWNER_WRITE);
            perms.add(PosixFilePermission.OWNER_READ);
            attr = PosixFilePermissions.asFileAttribute(perms);
            Files.setPosixFilePermissions(sensitiveKeyFile, perms);
        } else {
            // If Posix is not supported (e.g. Windows) then create the key file without permission settings.
            cmdLogger.info("Current file system does not support Posix, using default permission settings.");
            sensitiveKeyFile = Files.createFile(sensitiveKeyFile);
        }

    } catch (final FileAlreadyExistsException faee) {
        cmdLogger.error("The sensitive.key file {} already exists. That shouldn't have been. Aborting.", sensitiveKeyFile);
        System.exit(1);
    } catch (final Exception e) {
        cmdLogger.error("Other failure relating to setting permissions on {}. "
                + "(so that only the owner can read it). "
                + "This is fatal to the bootstrap process for security reasons. Exception was: {}", sensitiveKeyFile, e);
        System.exit(1);
    }
    return sensitiveKeyFile;
}
 
Example 16
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 4 votes vote down vote up
/**
 * Create temporary file that is aware of the specific limitations
 * of command line git.
 *
 * For example, no temporary file name (Windows or Unix) may
 * include a percent sign in its path because ssh uses the percent
 * sign character as the start of token indicator for token
 * expansion.
 *
 * As another example, windows temporary files may not contain a
 * space, an open parenthesis, or a close parenthesis anywhere in
 * their path, otherwise they break ssh argument passing through
 * the GIT_SSH or SSH_ASKPASS environment variable.
 *
 * Package protected for testing.  Not to be used outside this class
 *
 * @param prefix file name prefix for the generated temporary file (will be preceeded by "jenkins-gitclient-")
 * @param suffix file name suffix for the generated temporary file
 * @return temporary file
 * @throws IOException on error
 */
File createTempFile(String prefix, String suffix) throws IOException {
    String common_prefix = "jenkins-gitclient-";
    if (prefix == null) {
        prefix = common_prefix;
    } else {
        prefix = common_prefix + prefix;
    }

    if (workspace == null) {
        return createTempFileInSystemDir(prefix, suffix);
    }
    File workspaceTmp = new File(workspace.getAbsolutePath() + "@tmp");
    if (!workspaceTmp.isDirectory() && !workspaceTmp.mkdirs()) {
        if (!workspaceTmp.isDirectory()) {
            return createTempFileInSystemDir(prefix, suffix);
        }
    }
    Path tmpPath = Paths.get(workspaceTmp.getAbsolutePath());
    if (workspaceTmp.getAbsolutePath().contains("%")) {
        // Avoid ssh token expansion on all platforms
        return createTempFileInSystemDir(prefix, suffix);
    }
    if (isWindows()) {
        /* Windows git fails its call to GIT_SSH if its absolute
         * path contains a space or parenthesis or pipe or question mark or asterisk.
         * Use system temp dir instead of workspace temp dir.
         */
        if (workspaceTmp.getAbsolutePath().matches(".*[ ()|?*].*")) {
            return createTempFileInSystemDir(prefix, suffix);
        }
        return Files.createTempFile(tmpPath, prefix, suffix).toFile();
    } else if (workspaceTmp.getAbsolutePath().contains("%")) {
        /* Avoid Linux expansion of % in ssh arguments */
        return createTempFileInSystemDir(prefix, suffix);
    }
    // Unix specific
    if (workspaceTmp.getAbsolutePath().contains("`")) {
        // Avoid backquote shell expansion
        return createTempFileInSystemDir(prefix, suffix);
    }
    Set<PosixFilePermission> ownerOnly = PosixFilePermissions.fromString("rw-------");
    FileAttribute fileAttribute = PosixFilePermissions.asFileAttribute(ownerOnly);
    return Files.createTempFile(tmpPath, prefix, suffix, fileAttribute).toFile();
}
 
Example 17
Source File: UnixPath.java    From vespa with Apache License 2.0 4 votes vote down vote up
public UnixPath createNewFile(String permissions) {
    FileAttribute<?> attribute = PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(permissions));
    uncheck(() -> Files.createFile(path, attribute));
    return this;
}
 
Example 18
Source File: ProcessFactoryImpl.java    From vespa with Apache License 2.0 4 votes vote down vote up
@Override
public ChildProcess2Impl spawn(CommandLine commandLine) {
    List<String> arguments = commandLine.getArguments();
    if (arguments.isEmpty()) {
        throw new IllegalArgumentException("No arguments specified - missing program to spawn");
    }

    ProcessBuilder processBuilder = new ProcessBuilder(arguments);

    if (commandLine.getRedirectStderrToStdoutInsteadOfDiscard()) {
        processBuilder.redirectErrorStream(true);
    } else {
        processBuilder.redirectError(ProcessBuilder.Redirect.to(DEV_NULL));
    }

    // The output is redirected to a file (temporary or user-defined) because:
    //  - We could read continuously from process.getInputStream, but that may block
    //    indefinitely with a faulty program.
    //  - If we don't read continuously from process.getInputStream, then because
    //    the underlying channel may be a pipe, the child may be stopped because the pipe
    //    is full.
    //  - To honor the timeout, no API can be used that may end up blocking indefinitely.
    //
    // Therefore, we redirect the output to a file and use waitFor w/timeout. This also
    // has the benefit of allowing for inspection of the file during execution, and
    // allowing the inspection of the file if it e.g. gets too large to hold in-memory.

    FileAttribute<Set<PosixFilePermission>> fileAttribute = PosixFilePermissions.asFileAttribute(
            PosixFilePermissions.fromString("rw-------"));

    Path outputFile = commandLine.getOutputFile()
                                 .map(file -> {
                                     uncheck(() -> Files.deleteIfExists(file));
                                     uncheck(() -> Files.createFile(file, fileAttribute));
                                     return file;
                                 })
                                 .orElseGet(() -> {
                                     String temporaryFilePrefix =
                                             ProcessFactoryImpl.class.getSimpleName() + "-" + commandLine.programName() + "-";

                                     return uncheck(() -> Files.createTempFile(
                                             temporaryFilePrefix,
                                             ".out",
                                             fileAttribute));
                                 });

    try {
        processBuilder.redirectOutput(outputFile.toFile());
        ProcessApi2 process = processStarter.start(processBuilder);
        return new ChildProcess2Impl(commandLine, process, outputFile, timer);
    } catch (RuntimeException | Error throwable) {
        try {
            if (commandLine.getOutputFile().isEmpty())
                Files.delete(outputFile);
        } catch (IOException ioException) {
            logger.log(Level.WARNING, "Failed to delete temporary file at " +
                                         outputFile, ioException);
        }
        throw throwable;
    }

}
 
Example 19
Source File: FileContentStore.java    From alfresco-simple-content-stores with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a file for the specifically provided content URL. The URL may not already be in use.
 * <p>
 * The store prefix is stripped off the URL and the rest of the URL used directly to create a file.
 *
 * @param newContentUrl
 *            the specific URL to use, which may not be in use
 * @return a new and unique file
 * @throws IOException
 *             if the file or parent directories couldn't be created or if the URL is already in use.
 * @throws UnsupportedOperationException
 *             if the store is read-only
 *
 * @see #setReadOnly(boolean)
 */
protected File createNewFile(final String newContentUrl) throws IOException
{
    if (this.readOnly)
    {
        throw new UnsupportedOperationException("This store is currently read-only: " + this);
    }

    LOGGER.debug("Creating new file for {}", newContentUrl);
    final Path filePath = this.makeFilePath(newContentUrl);

    if (Files.exists(filePath))
    {
        throw new ContentIOException("When specifying a URL for new content, the URL may not be in use already. \n" + "   store: "
                + this + "\n" + "   new URL: " + newContentUrl);
    }

    final Path parentPath = filePath.getParent();
    // unlikely to be null but possible due to API definition
    if (parentPath != null)
    {
        try
        {
            // ensure to inherit through all folder permissions from root
            final Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(this.rootDirectory.toPath());
            final FileAttribute<Set<PosixFilePermission>> permissionAttribute = PosixFilePermissions.asFileAttribute(permissions);

            Files.createDirectories(parentPath, permissionAttribute);
        }
        catch (final UnsupportedOperationException ex)
        {
            LOGGER.debug(
                    "File system does not support posix file attributes - unable to ensure folder path permissions are consistent with root directory");
            Files.createDirectories(parentPath);
        }
    }
    Files.createFile(filePath);
    LOGGER.debug("Created content file {}", filePath);

    return filePath.toFile();
}
 
Example 20
Source File: TestTask.java    From celos with Apache License 2.0 4 votes vote down vote up
private static FileAttribute<Set<PosixFilePermission>> getTempDirAttributes() {
    return PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-xr-x"));
}