Example usage for java.nio.file.attribute PosixFilePermission OWNER_WRITE

List of usage examples for java.nio.file.attribute PosixFilePermission OWNER_WRITE

Introduction

In this page you can find the example usage for java.nio.file.attribute PosixFilePermission OWNER_WRITE.

Prototype

PosixFilePermission OWNER_WRITE

To view the source code for java.nio.file.attribute PosixFilePermission OWNER_WRITE.

Click Source Link

Document

Write permission, owner.

Usage

From source file:net.krotscheck.util.ResourceUtilTest.java

/**
 * Assert that we can read a resource as a string.
 *
 * @throws Exception Should not be thrown.
 *//*from  w  w w.ja  v  a  2 s. com*/
@Test
public void testGetResourceAsString() throws Exception {
    String name = "/valid-resource-file.txt";
    String content = ResourceUtil.getResourceAsString(name);

    Assert.assertEquals("valid resource content", content);

    String invalidName = "/invalid-resource-file.txt";
    String invalidContent = ResourceUtil.getResourceAsString(invalidName);

    Assert.assertEquals("", invalidContent);

    // Make the file write only
    File resource = ResourceUtil.getFileForResource(name);
    Set<PosixFilePermission> oldPerms = Files.getPosixFilePermissions(resource.toPath());
    Set<PosixFilePermission> perms = new HashSet<>();
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);
    perms.add(PosixFilePermission.OTHERS_WRITE);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);

    // Write only...
    Files.setPosixFilePermissions(resource.toPath(), perms);
    String writeOnlyName = "/valid-resource-file.txt";
    String writeOnlyContent = ResourceUtil.getResourceAsString(writeOnlyName);
    Assert.assertEquals("", writeOnlyContent);

    Files.setPosixFilePermissions(resource.toPath(), oldPerms);

}

From source file:net.spinetrak.rpitft.command.Command.java

private String init(final String script_) {
    final String VAR_TMP = "/var/tmp";
    InputStream scriptIn = null;//from   w ww.j av  a  2s  .  c  om
    OutputStream scriptOut = null;
    final File script = new File(VAR_TMP + script_);
    final String dir = script.getParent();
    if (null != dir) {
        if (!new File(dir).mkdirs()) {
            LOGGER.error("Unable to create dirs for " + dir);
        }
    }
    try {
        scriptIn = Command.class.getResourceAsStream(script_);
        scriptOut = new FileOutputStream(script);

        IOUtils.copy(scriptIn, scriptOut);

        final Set<PosixFilePermission> perms = new HashSet<>();
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        perms.add(PosixFilePermission.GROUP_EXECUTE);
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.GROUP_WRITE);

        Files.setPosixFilePermissions(Paths.get(script.getAbsolutePath()), perms);
    } catch (final IOException ex_) {
        LOGGER.error(ex_.getMessage());
    } finally {
        if (scriptIn != null) {
            try {
                scriptIn.close();
            } catch (final IOException ex_) {
                LOGGER.error(ex_.getMessage());
            }
        }
        if (scriptOut != null) {
            try {
                scriptOut.close();
            } catch (final IOException ex_) {
                LOGGER.error(ex_.getMessage());
            }
        }
    }
    return script.getAbsolutePath();
}

From source file:com.streamsets.pipeline.stage.origin.spooldir.TestWholeFileSpoolDirSource.java

@Test
public void testWholeFileRecordsForFile() throws Exception {
    Path sourcePath = Paths.get(testDir + "/source.txt");
    Files.write(sourcePath, "Sample Text 1".getBytes());
    Files.setAttribute(sourcePath, "posix:permissions",
            ImmutableSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE,
                    PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_READ));

    SpoolDirSource source = createSource();
    PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source).addOutputLane("lane")
            .setOnRecordError(OnRecordError.TO_ERROR).build();

    final List<Record> records = Collections.synchronizedList(new ArrayList<>(10));
    AtomicInteger batchCount = new AtomicInteger(0);

    runner.runInit();/* w  ww .jav  a  2 s.  co m*/
    try {
        runner.runProduce(new HashMap<>(), 10, output2 -> {
            synchronized (records) {
                records.addAll(output2.getRecords().get("lane"));
            }
            batchCount.incrementAndGet();
            runner.setStop();
        });

        runner.waitOnProduce();

        Assert.assertNotNull(records);
        Assert.assertEquals(1, records.size());
        Record record = records.get(0);

        Assert.assertTrue(record.has(FileRefUtil.FILE_INFO_FIELD_PATH));
        Assert.assertTrue(record.has(FileRefUtil.FILE_REF_FIELD_PATH));

        Assert.assertEquals(Field.Type.FILE_REF, record.get(FileRefUtil.FILE_REF_FIELD_PATH).getType());
        Assert.assertEquals(Field.Type.MAP, record.get(FileRefUtil.FILE_INFO_FIELD_PATH).getType());

        Map<String, Object> metadata = Files.readAttributes(sourcePath, "posix:*");
        Assert.assertTrue(record.get(FileRefUtil.FILE_INFO_FIELD_PATH).getValueAsMap().keySet()
                .containsAll(metadata.keySet()));

        //Check permissions
        Assert.assertTrue(record.has(FileRefUtil.FILE_INFO_FIELD_PATH + "/" + SpoolDirRunnable.PERMISSIONS));
        Assert.assertEquals("rwxr-----", record
                .get(FileRefUtil.FILE_INFO_FIELD_PATH + "/" + SpoolDirRunnable.PERMISSIONS).getValueAsString());

        Assert.assertEquals(Field.Type.FILE_REF, record.get(FileRefUtil.FILE_REF_FIELD_PATH).getType());
        Assert.assertEquals(Field.Type.MAP, record.get(FileRefUtil.FILE_INFO_FIELD_PATH).getType());

    } finally {
        runner.runDestroy();
    }
}

From source file:org.roda.core.plugins.ReplicationPluginTest.java

@BeforeClass
public void setUp() throws Exception {
    basePath = TestsHelper.createBaseTempDir(getClass(), true,
            PosixFilePermissions.asFileAttribute(new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE,
                    PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_EXECUTE))));

    boolean deploySolr = true;
    boolean deployLdap = true;
    boolean deployFolderMonitor = true;
    boolean deployOrchestrator = true;
    boolean deployPluginManager = true;
    boolean deployDefaultResources = false;

    // embedded Apache Solr
    RodaCoreFactory.instantiateTest(deploySolr, deployLdap, deployFolderMonitor, deployOrchestrator,
            deployPluginManager, deployDefaultResources, SolrType.EMBEDDED);

    // // HTTP Apache Solr
    // RodaCoreFactory.instantiateTest(deploySolr, deployLdap,
    // deployFolderMonitor, deployOrchestrator,
    // deployPluginManager, deployDefaultResources, SolrType.HTTP);

    // // Cloud Apache Solr
    // RodaCoreFactory.instantiateTest(deploySolr, deployLdap,
    // deployFolderMonitor, deployOrchestrator,
    // deployPluginManager, deployDefaultResources, SolrType.HTTP_CLOUD);

    model = RodaCoreFactory.getModelService();
    index = RodaCoreFactory.getIndexService();
    storage = RodaCoreFactory.getStorageService();

    testPath = TestsHelper.createBaseTempDir(getClass(), true,
            PosixFilePermissions.asFileAttribute(new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE,
                    PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_EXECUTE))));

    Files.createDirectories(//from  ww w . j  a  v  a  2s  . com
            testPath.resolve(RodaConstants.CORE_STORAGE_FOLDER).resolve(RodaConstants.STORAGE_CONTAINER_AIP));
    Files.createDirectories(testPath.resolve(RodaConstants.CORE_STORAGE_FOLDER)
            .resolve(RodaConstants.STORAGE_CONTAINER_PRESERVATION)
            .resolve(RodaConstants.STORAGE_CONTAINER_PRESERVATION_AGENTS));

    LOGGER.info("Running {} tests under storage {}", getClass().getSimpleName(), basePath);
}

From source file:com.streamsets.pipeline.stage.BaseHiveIT.java

/**
 * Start all required mini clusters.//from  ww w  .jav a 2  s.co  m
 */
@BeforeClass
public static void setUpClass() throws Exception {
    // Conf dir
    new File(confDir).mkdirs();

    // HDFS
    File minidfsDir = new File("target/minidfs").getAbsoluteFile();
    if (!minidfsDir.exists()) {
        Assert.assertTrue(minidfsDir.mkdirs());
    }
    Set<PosixFilePermission> set = new HashSet<>();
    set.add(PosixFilePermission.OWNER_EXECUTE);
    set.add(PosixFilePermission.OWNER_READ);
    set.add(PosixFilePermission.OWNER_WRITE);
    set.add(PosixFilePermission.OTHERS_READ);
    java.nio.file.Files.setPosixFilePermissions(minidfsDir.toPath(), set);
    System.setProperty(MiniDFSCluster.PROP_TEST_BUILD_DATA, minidfsDir.getPath());
    final Configuration conf = new HdfsConfiguration();
    conf.set("hadoop.proxyuser." + System.getProperty("user.name") + ".hosts", "*");
    conf.set("hadoop.proxyuser." + System.getProperty("user.name") + ".groups", "*");
    miniDFS = new MiniDFSCluster.Builder(conf).build();
    miniDFS.getFileSystem().setPermission(new Path("/"), FsPermission.createImmutable((short) 0777));
    writeConfiguration(miniDFS.getConfiguration(0), confDir + "/core-site.xml");
    writeConfiguration(miniDFS.getConfiguration(0), confDir + "/hdfs-site.xml");
    writeConfiguration(miniDFS.getConfiguration(0), confDir + "/mapred-site.xml");
    writeConfiguration(miniDFS.getConfiguration(0), confDir + "/yarn-site.xml");

    // Configuration for both HMS and HS2
    final HiveConf hiveConf = new HiveConf(miniDFS.getConfiguration(0), HiveConf.class);
    hiveConf.set(HiveConf.ConfVars.METASTORECONNECTURLKEY.varname,
            "jdbc:derby:;databaseName=target/metastore_db;create=true");
    hiveConf.set(HiveConf.ConfVars.METASTOREURIS.varname,
            Utils.format("thrift://{}:{}", HOSTNAME, METASTORE_PORT));
    hiveConf.set(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_BIND_HOST.varname, "localhost");
    hiveConf.setInt(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_PORT.varname, HIVE_SERVER_PORT);

    // Hive metastore
    Callable<Void> metastoreService = new Callable<Void>() {
        public Void call() throws Exception {
            try {
                HiveMetaStore.startMetaStore(METASTORE_PORT, ShimLoader.getHadoopThriftAuthBridge(), hiveConf);
                while (true)
                    ;
            } catch (Throwable e) {
                throw new Exception("Error starting metastore", e);
            }
        }
    };
    hiveMetastoreExecutor.submit(metastoreService);
    NetworkUtils.waitForStartUp(HOSTNAME, METASTORE_PORT, MINICLUSTER_BOOT_RETRY, MINICLUSTER_BOOT_SLEEP);

    // HiveServer 2
    hiveServer2 = new HiveServer2();
    hiveServer2.init(hiveConf);
    hiveServer2.start();
    writeConfiguration(hiveServer2.getHiveConf(), confDir + "/hive-site.xml");
    NetworkUtils.waitForStartUp(HOSTNAME, HIVE_SERVER_PORT, MINICLUSTER_BOOT_RETRY, MINICLUSTER_BOOT_SLEEP);

    // JDBC Connection to Hive
    Class.forName(HIVE_JDBC_DRIVER);
    hiveConnection = HiveMetastoreUtil.getHiveConnection(getHiveJdbcUrl(),
            HadoopSecurityUtil.getLoginUser(conf));
    hiveQueryExecutor = new HiveQueryExecutor(hiveConnection);
}

From source file:com.twosigma.beaker.r.rest.RShellRest.java

private String makeTemp(String base, String suffix) throws IOException {
    File dir = new File(System.getenv("beaker_tmp_dir"));
    File tmp = File.createTempFile(base, suffix, dir);
    if (!windows()) {
        Set<PosixFilePermission> perms = EnumSet.of(PosixFilePermission.OWNER_READ,
                PosixFilePermission.OWNER_WRITE);
        Files.setPosixFilePermissions(tmp.toPath(), perms);
    }// w  w w. j  a va  2s  .  c om
    return tmp.getAbsolutePath();
}

From source file:ch.psi.zmq.receiver.FileReceiver.java

/**
 * Receive ZMQ messages with pilatus-1.0 header type and write the data part
 * to disk/*from w ww .  java  2 s .c o m*/
 */
public void receive(Integer numImages) {

    try {
        done = false;
        counter = 0;
        counterDropped = 0;
        receive = true;
        context = ZMQ.context(1);
        socket = context.socket(ZMQ.PULL);
        socket.connect("tcp://" + hostname + ":" + port);

        ObjectMapper mapper = new ObjectMapper();
        TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
        };
        String path = "";

        // User lookup service
        UserPrincipalLookupService lookupservice = FileSystems.getDefault().getUserPrincipalLookupService();

        Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>();
        perms.add(PosixFilePermission.OWNER_READ);
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.GROUP_READ);
        perms.add(PosixFilePermission.GROUP_WRITE);

        while (receive) {
            try {
                byte[] message = socket.recv();
                byte[] content = null;
                if (socket.hasReceiveMore()) {
                    content = socket.recv();
                }
                logger.info("Message received: " + new String(message));

                Map<String, Object> h = mapper.readValue(message, typeRef);

                if (!"pilatus-1.0".equals(h.get("htype"))) {
                    logger.warning("Message type [" + h.get("htype") + "] not supported - ignore message");
                    continue;
                }

                String username = (String) h.get("username");

                // Save content to file (in basedir)
                String p = (String) h.get("path");
                if (!p.startsWith("/")) {
                    p = basedir + "/" + p;
                }
                File f = new File(p);
                // if(!f.exists()){
                if (!path.equals(p)) {
                    if (username == null) {
                        logger.info("Create directory " + p + "");
                        f.mkdirs();
                    } else {
                        logger.info("Create directory " + p + " for user " + username);
                        try {
                            Set<PosixFilePermission> permissions = new HashSet<PosixFilePermission>();
                            permissions.add(PosixFilePermission.OWNER_READ);
                            permissions.add(PosixFilePermission.OWNER_WRITE);
                            permissions.add(PosixFilePermission.OWNER_EXECUTE);
                            permissions.add(PosixFilePermission.GROUP_READ);
                            permissions.add(PosixFilePermission.GROUP_WRITE);
                            permissions.add(PosixFilePermission.GROUP_EXECUTE);
                            // username and groupname is the same by
                            // convention
                            mkdir(f, lookupservice.lookupPrincipalByName(username),
                                    lookupservice.lookupPrincipalByGroupName(username), permissions);
                        } catch (IOException e) {
                            throw new RuntimeException("Unable to create directory for user " + username + "",
                                    e);
                        }
                    }
                    path = p;
                }

                File file = new File(f, (String) h.get("filename"));
                logger.finest("Write to " + file.getAbsolutePath());

                try (FileOutputStream s = new FileOutputStream(file)) {
                    s.write(content);
                }

                if (username != null) {
                    Files.setOwner(file.toPath(), lookupservice.lookupPrincipalByName(username));
                    // username and groupname is the same by convention
                    Files.getFileAttributeView(file.toPath(), PosixFileAttributeView.class,
                            LinkOption.NOFOLLOW_LINKS)
                            .setGroup(lookupservice.lookupPrincipalByGroupName(username));
                    Files.setPosixFilePermissions(file.toPath(), perms);
                }

                counter++;
                if (numImages != null && numImages == counter) {
                    break;
                }
            } catch (IOException e) {
                logger.log(Level.SEVERE, "", e);
                counterDropped++;
            }
        }

    } catch (Exception e) {
        if (receive) {
            e.printStackTrace();
        }
    }
}

From source file:net.krotscheck.jersey2.configuration.Jersey2ToolkitConfigTest.java

/**
 * Assert that an unreadable file does not throw an error.
 *
 * @throws java.io.IOException File operation errors.
 *///from  w ww .j  a  v  a  2  s. c  o m
@Test
public void testUnreadableFile() throws IOException {
    // Get the prop file and store the old permissions.
    File propFile = ResourceUtil.getFileForResource("jersey2-toolkit.properties");

    Set<PosixFilePermission> oldPerms = Files.getPosixFilePermissions(propFile.toPath());

    // Apply writeonly permission set.
    Set<PosixFilePermission> writeonly = new HashSet<>();
    writeonly.add(PosixFilePermission.OWNER_WRITE);
    writeonly.add(PosixFilePermission.GROUP_WRITE);
    Files.setPosixFilePermissions(propFile.toPath(), writeonly);

    // Add something to check
    System.setProperty("property3", "override3");

    // If this throws an error, we've got a problem.
    Configuration config = new Jersey2ToolkitConfig();
    Assert.assertFalse(config.containsKey("property1"));
    Assert.assertFalse(config.containsKey("property2"));
    Assert.assertTrue(config.containsKey("property3"));

    // Apply the correct permissions again
    Files.setPosixFilePermissions(propFile.toPath(), oldPerms);
}

From source file:org.darkware.wpman.wpcli.WPCLI.java

/**
 * Update the local WP-CLI tool to the most recent version.
 *//*  ww  w . jav  a  2s  .co  m*/
public static void update() {
    try {
        WPManager.log.info("Downloading new version of WP-CLI.");

        CloseableHttpClient httpclient = HttpClients.createDefault();

        URI pharURI = new URIBuilder().setScheme("http").setHost("raw.githubusercontent.com")
                .setPath("/wp-cli/builds/gh-pages/phar/wp-cli.phar").build();

        WPManager.log.info("Downloading from: {}", pharURI);
        HttpGet downloadRequest = new HttpGet(pharURI);

        CloseableHttpResponse response = httpclient.execute(downloadRequest);

        WPManager.log.info("Download response: {}", response.getStatusLine());
        WPManager.log.info("Download content type: {}", response.getFirstHeader("Content-Type").getValue());

        FileChannel wpcliFile = FileChannel.open(WPCLI.toolPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);

        response.getEntity().writeTo(Channels.newOutputStream(wpcliFile));
        wpcliFile.close();

        Set<PosixFilePermission> wpcliPerms = new HashSet<>();
        wpcliPerms.add(PosixFilePermission.OWNER_READ);
        wpcliPerms.add(PosixFilePermission.OWNER_WRITE);
        wpcliPerms.add(PosixFilePermission.OWNER_EXECUTE);
        wpcliPerms.add(PosixFilePermission.GROUP_READ);
        wpcliPerms.add(PosixFilePermission.GROUP_EXECUTE);

        Files.setPosixFilePermissions(WPCLI.toolPath, wpcliPerms);
    } catch (URISyntaxException e) {
        WPManager.log.error("Failure building URL for WPCLI download.", e);
        System.exit(1);
    } catch (IOException e) {
        WPManager.log.error("Error while downloading WPCLI client.", e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.everit.osgi.dev.maven.util.FileManager.java

private static void setPermissionsOnFile(final File file, final ZipArchiveEntry entry) throws IOException {
    if (entry.getPlatform() == ZipArchiveEntry.PLATFORM_FAT) {
        return;// ww  w  .j a va 2  s  . co  m
    }
    int unixPermissions = entry.getUnixMode();

    Set<PosixFilePermission> perms = new HashSet<>();

    if ((unixPermissions & OWNER_EXECUTE_BITMASK) > 0) {
        perms.add(PosixFilePermission.OWNER_EXECUTE);
    }

    if ((unixPermissions & GROUP_EXECUTE_BITMASK) > 0) {
        perms.add(PosixFilePermission.GROUP_EXECUTE);
    }

    if ((unixPermissions & OTHERS_EXECUTE_BITMASK) > 0) {
        perms.add(PosixFilePermission.OTHERS_EXECUTE);
    }

    if ((unixPermissions & OWNER_READ_BITMASK) > 0) {
        perms.add(PosixFilePermission.OWNER_READ);
    }

    if ((unixPermissions & GROUP_READ_BITMASK) > 0) {
        perms.add(PosixFilePermission.GROUP_READ);
    }

    if ((unixPermissions & OTHERS_READ_BITMASK) > 0) {
        perms.add(PosixFilePermission.OTHERS_READ);
    }

    if ((unixPermissions & OWNER_WRITE_BITMASK) > 0) {
        perms.add(PosixFilePermission.OWNER_WRITE);
    }

    if ((unixPermissions & GROUP_WRITE_BITMASK) > 0) {
        perms.add(PosixFilePermission.GROUP_WRITE);
    }

    if ((unixPermissions & OTHERS_WRITE_BITMASK) > 0) {
        perms.add(PosixFilePermission.OTHERS_WRITE);
    }

    Path path = file.toPath();
    if (path.getFileSystem().supportedFileAttributeViews().contains("posix")) {
        Files.setPosixFilePermissions(path, perms);
    } else {
        setPermissionsOnFileInNonPosixSystem(file, perms);
    }
}