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

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

Introduction

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

Prototype

PosixFilePermission OWNER_EXECUTE

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

Click Source Link

Document

Execute/search permission, owner.

Usage

From source file:com.facebook.buck.io.ProjectFilesystemTest.java

@Test
public void testCreateZipPreservesExecutablePermissions() throws IOException {

    // Create a empty executable file.
    Path exe = tmp.newFile("test.exe");
    MoreFiles.makeExecutable(exe);//from   ww w .ja  va  2 s.  c o m

    // Archive it into a zipfile using `ProjectFileSystem.createZip`.
    Path zipFile = tmp.getRoot().resolve("test.zip");
    filesystem.createZip(ImmutableList.of(exe), zipFile);

    // Now unpack the archive (using apache's common-compress, as it preserves
    // executable permissions) and verify that the archive entry has executable
    // permissions.
    try (ZipFile zip = new ZipFile(zipFile.toFile())) {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        assertTrue(entries.hasMoreElements());
        ZipArchiveEntry entry = entries.nextElement();
        Set<PosixFilePermission> permissions = MorePosixFilePermissions
                .fromMode(entry.getExternalAttributes() >> 16);
        assertTrue(permissions.contains(PosixFilePermission.OWNER_EXECUTE));
        assertFalse(entries.hasMoreElements());
    }

}

From source file:com.facebook.buck.util.ProjectFilesystemTest.java

@Test
public void testCreateZipPreservesExecutablePermissions() throws IOException {

    // Create a empty executable file.
    File exe = tmp.newFile("test.exe");
    exe.setExecutable(true);//from w  ww .  j  a v  a 2 s  . c o m

    // Archive it into a zipfile using `ProjectFileSystem.createZip`.
    File zipFile = new File(tmp.getRoot().toPath().toString() + "/test.zip");
    filesystem.createZip(ImmutableList.of(exe.toPath()), zipFile);

    // Now unpack the archive (using apache's common-compress, as it preserves
    // executable permissions) and verify that the archive entry has executable
    // permissions.
    try (ZipFile zip = new ZipFile(zipFile)) {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        assertTrue(entries.hasMoreElements());
        ZipArchiveEntry entry = entries.nextElement();
        Set<PosixFilePermission> permissions = MorePosixFilePermissions
                .fromMode(entry.getExternalAttributes() >> 16);
        assertTrue(permissions.contains(PosixFilePermission.OWNER_EXECUTE));
        assertFalse(entries.hasMoreElements());
    }

}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java

@Test
public void testCreateZipPreservesExecutablePermissions() throws IOException {

    // Create a empty executable file.
    Path exe = tmp.newFile("test.exe");
    MostFiles.makeExecutable(exe);//w  w w .  j a v a 2  s.  c o m

    // Archive it into a zipfile using `Zip.create`.
    Path zipFile = tmp.getRoot().resolve("test.zip");
    Zip.create(filesystem, ImmutableList.of(exe), zipFile);

    // Now unpack the archive (using apache's common-compress, as it preserves
    // executable permissions) and verify that the archive entry has executable
    // permissions.
    try (ZipFile zip = new ZipFile(zipFile.toFile())) {
        Enumeration<ZipArchiveEntry> entries = zip.getEntries();
        assertTrue(entries.hasMoreElements());
        ZipArchiveEntry entry = entries.nextElement();
        Set<PosixFilePermission> permissions = MorePosixFilePermissions
                .fromMode(entry.getExternalAttributes() >> 16);
        assertTrue(permissions.contains(PosixFilePermission.OWNER_EXECUTE));
        assertFalse(entries.hasMoreElements());
    }
}

From source file:org.springframework.boot.loader.tools.RepackagerTests.java

@Test
public void addLauncherScript() throws Exception {
    this.testJarFile.addClass("a/b/C.class", ClassWithMainMethod.class);
    File source = this.testJarFile.getFile();
    File dest = this.temporaryFolder.newFile("dest.jar");
    Repackager repackager = new Repackager(source);
    LaunchScript script = new MockLauncherScript("ABC");
    repackager.repackage(dest, NO_LIBRARIES, script);
    byte[] bytes = FileCopyUtils.copyToByteArray(dest);
    assertThat(new String(bytes)).startsWith("ABC");
    assertThat(hasLauncherClasses(source)).isFalse();
    assertThat(hasLauncherClasses(dest)).isTrue();
    try {/* www . j a  va2 s  . c om*/
        assertThat(Files.getPosixFilePermissions(dest.toPath())).contains(PosixFilePermission.OWNER_EXECUTE);
    } catch (UnsupportedOperationException ex) {
        // Probably running the test on Windows
    }
}

From source file:com.streamsets.datacollector.http.TestWebServerTaskHttpHttps.java

@Test
public void testAuthorizationConstraints() throws Exception {
    WebAppProvider webAppProvider = new WebAppProvider() {
        @Override//from  w ww.j  a va2 s .co m
        public ServletContextHandler get() {
            ServletContextHandler handler = new ServletContextHandler();
            handler.setContextPath("/webapp");
            handler.addServlet(new ServletHolder(new PingServlet()), "/ping");
            handler.addServlet(new ServletHolder(new PingServlet()), "/rest/v1/ping");
            handler.addServlet(new ServletHolder(new PingServlet()), "/public-rest/v1/ping");
            return handler;
        }

        @Override
        public void postStart() {
        }
    };
    Configuration conf = new Configuration();
    int httpPort = getRandomPort();
    conf.set(WebServerTask.AUTHENTICATION_KEY, "basic");
    conf.set(WebServerTask.HTTP_PORT_KEY, httpPort);
    String confDir = createTestDir();
    File realmFile = new File(confDir, "basic-realm.properties");
    try (InputStream is = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("basic-realm.properties"); OutputStream os = new FileOutputStream(realmFile)) {
        IOUtils.copy(is, os);
    }
    Set<PosixFilePermission> set = new HashSet<>();
    set.add(PosixFilePermission.OWNER_EXECUTE);
    set.add(PosixFilePermission.OWNER_READ);
    set.add(PosixFilePermission.OWNER_WRITE);
    Files.setPosixFilePermissions(realmFile.toPath(), set);

    final WebServerTask ws = createWebServerTask(confDir, conf, ImmutableSet.of(webAppProvider));
    try {
        ws.initTask();
        new Thread() {
            @Override
            public void run() {
                ws.runTask();
            }
        }.start();
        Thread.sleep(1000);

        String baseUrl = "http://127.0.0.1:" + httpPort;

        // root app
        HttpURLConnection conn = (HttpURLConnection) new URL(baseUrl + "/ping").openConnection();
        conn.setRequestProperty(CsrfProtectionFilter.HEADER_NAME, "CSRF");
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        conn = (HttpURLConnection) new URL(baseUrl + "/rest/v1/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/rest/v1/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        conn = (HttpURLConnection) new URL(baseUrl + "/public-rest/v1/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/public-rest/v1/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        // web app
        conn = (HttpURLConnection) new URL(baseUrl + "/webapp/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/webapp/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        conn = (HttpURLConnection) new URL(baseUrl + "/webapp/rest/v1/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/webapp/rest/v1/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

        conn = (HttpURLConnection) new URL(baseUrl + "/webapp/public-rest/v1/ping").openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        conn = (HttpURLConnection) openWithBasicAuth(new URL(baseUrl + "/webapp/public-rest/v1/ping"));
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

    } finally {
        ws.stopTask();
    }
}

From source file:com.virtualparadigm.packman.processor.JPackageManager.java

public static boolean autorun(File autorunDir, Map<String, String> environmentVariableMap) {
    logger.info("PackageManager::autorun()");
    boolean status = true;

    if (autorunDir != null && autorunDir.isDirectory()) {
        File[] autorunFiles = autorunDir.listFiles();
        Arrays.sort(autorunFiles);
        String fileExtension = null;
        DefaultExecutor cmdExecutor = new DefaultExecutor();

        //            String sqlScriptFilePath = null;
        //            Reader sqlScriptReader = null;
        //            Properties sqlScriptProperties = null;
        for (File autorunFile : autorunFiles) {
            if (!autorunFile.isDirectory()) {
                try {
                    fileExtension = FilenameUtils.getExtension(autorunFile.getAbsolutePath());
                    if (fileExtension != null) {
                        if (fileExtension.equalsIgnoreCase("bat")) {
                            logger.info("  executing autorun batch script: " + autorunFile.getAbsolutePath());
                            logger.info("  executing autorun environment: "
                                    + EnvironmentUtils.toStrings(environmentVariableMap));
                            cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath()),
                                    environmentVariableMap);
                        } else if (fileExtension.equalsIgnoreCase("sh")) {
                            Set<PosixFilePermission> permissionSet = new HashSet<PosixFilePermission>();
                            permissionSet.add(PosixFilePermission.OWNER_READ);
                            permissionSet.add(PosixFilePermission.OWNER_WRITE);
                            permissionSet.add(PosixFilePermission.OWNER_EXECUTE);
                            permissionSet.add(PosixFilePermission.OTHERS_READ);
                            permissionSet.add(PosixFilePermission.OTHERS_WRITE);
                            permissionSet.add(PosixFilePermission.OTHERS_EXECUTE);
                            permissionSet.add(PosixFilePermission.GROUP_READ);
                            permissionSet.add(PosixFilePermission.GROUP_WRITE);
                            permissionSet.add(PosixFilePermission.GROUP_EXECUTE);
                            Files.setPosixFilePermissions(Paths.get(autorunFile.toURI()), permissionSet);

                            logger.info("  executing autorun shell script: " + autorunFile.getAbsolutePath());
                            logger.info("  executing autorun environment: "
                                    + EnvironmentUtils.toStrings(environmentVariableMap));
                            cmdExecutor.execute(CommandLine.parse(autorunFile.getAbsolutePath()),
                                    environmentVariableMap);
                        } else if (fileExtension.equalsIgnoreCase("sql")
                                || fileExtension.equalsIgnoreCase("ddl")) {
                            logger.info("  executing autorun file: " + autorunFile.getAbsolutePath());

                            // look for properties file named same as script file for connection properties
                            //                                sqlScriptFilePath = autorunFile.getAbsolutePath();
                            //                                sqlScriptProperties = PropertyLoader.loadProperties(sqlScriptFilePath.substring(0, sqlScriptFilePath.length()-3) + "properties");
                            //                                sqlScriptReader = new FileReader(autorunFile.getAbsolutePath());
                        } else if (fileExtension.equalsIgnoreCase("jar")) {
                            logger.info("  executing autorun file: " + autorunFile.getAbsolutePath());
                        }/*from w w  w.  ja  v  a 2  s .c o m*/
                    }
                } catch (Exception e) {
                    logger.error("", e);
                    e.printStackTrace();
                }
            }
        }
    }
    return status;
}

From source file:org.apache.hadoop.yarn.server.security.CertificateLocalizationService.java

private void materializeInternalX509(X509SecurityMaterial material) throws IOException {
    writeX509ToLocalFS(material.getKeyStoreMem(), material.getKeyStoreLocation().toFile(),
            material.getTrustStoreMem(), material.getTrustStoreLocation().toFile(), material.getKeyStorePass(),
            material.getPasswdLocation().toFile());

    if (service == ServiceType.NM) {
        Set<PosixFilePermission> materialPermissions = EnumSet.of(PosixFilePermission.OWNER_READ,
                PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE,
                PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_EXECUTE);

        Files.setPosixFilePermissions(material.getCertFolder(), materialPermissions);
        Files.setPosixFilePermissions(material.getKeyStoreLocation(), materialPermissions);
        Files.setPosixFilePermissions(material.getTrustStoreLocation(), materialPermissions);
        Files.setPosixFilePermissions(material.getPasswdLocation(), materialPermissions);
    }/* w w w.j a va2 s . c o m*/
}

From source file:org.apache.hadoop.yarn.server.security.CertificateLocalizationService.java

private void materializeInternalJWT(JWTSecurityMaterial material) throws IOException {
    FileUtils.writeStringToFile(material.getTokenLocation().toFile(), material.getToken());
    if (service == ServiceType.NM) {
        Set<PosixFilePermission> materialPermissions = EnumSet.of(PosixFilePermission.OWNER_READ,
                PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE,
                PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_EXECUTE);

        Files.setPosixFilePermissions(material.getCertFolder(), materialPermissions);
        Files.setPosixFilePermissions(material.getTokenLocation(), materialPermissions);
    }//from  w w  w . j a  v  a  2  s .  co m
}

From source file:edu.utah.bmi.ibiomes.lite.IBIOMESLiteManager.java

/**
 * Pull data files (pdb and images) for a given experiment
 * @param fileTreeXmlPath Path to XML file representing the project file tree
 * @param workflowXmlPath Path to XML file representing the experiment workflow
 * @param dataDirPath Path to directory used to store data files
 * @throws SAXException//  w  w  w .j  a  va2s  .com
 * @throws IOException
 * @throws XPathExpressionException 
 * @throws ParserConfigurationException 
 * @throws TransformerException 
 */
private void pullDataFilesForExperiment(String fileTreeXmlPath, String workflowXmlPath, String dataDirPath)
        throws SAXException, IOException, XPathExpressionException, ParserConfigurationException,
        TransformerException {

    if (outputToConsole)
        System.out.println("Copying analysis data files...");

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document fileTreeDoc = docBuilder.parse(fileTreeXmlPath);
    fileTreeDoc = Utils.normalizeXmlDoc(fileTreeDoc);

    Element fileTreeRootElt = (Element) fileTreeDoc.getDocumentElement().getChildNodes().item(0);
    String dirPath = fileTreeRootElt.getAttribute("absolutePath");

    XPathReader xreader = new XPathReader(fileTreeDoc);

    //load XML representation of experiment workflow
    Document docWorkflow = docBuilder.parse(workflowXmlPath);
    docWorkflow = Utils.normalizeXmlDoc(docWorkflow);
    Element workflowRootElt = (Element) docWorkflow.getDocumentElement();

    //find main structure for display in Jmol
    Element jmolElt = pullJmolFile(fileTreeDoc, fileTreeRootElt, xreader, dataDirPath, dirPath);
    if (jmolElt != null)
        workflowRootElt.appendChild(docWorkflow.importNode(jmolElt, true));

    //find analysis data
    NodeList matchingFiles = (NodeList) xreader.read("//file[AVUs/AVU[@id='" + FileMetadata.FILE_CLASS
            + "' and text()='" + FileMetadata.FILE_CLASS_ANALYSIS.toUpperCase() + "']]",
            XPathConstants.NODESET);

    //add publication information
    //Element dirNode = (Element)fileTreeDoc.getDocumentElement().getFirstChild();
    //dirNode.setAttribute("publisher", workflowRootElt.getAttribute("publisher"));
    //dirNode.setAttribute("publicationDate", workflowRootElt.getAttribute("publicationDate"));

    //analysis data
    if (matchingFiles != null && matchingFiles.getLength() > 0) {
        Element dataElt = docWorkflow.createElement("analysis");
        workflowRootElt.appendChild(dataElt);

        Element imgElt = docWorkflow.createElement("images");
        Element pdbElt = docWorkflow.createElement("structures");
        Element csvElts = docWorkflow.createElement("spreadsheets");
        Element otherDataElts = docWorkflow.createElement("unknowns");

        dataElt.appendChild(imgElt);
        dataElt.appendChild(csvElts);
        dataElt.appendChild(pdbElt);
        dataElt.appendChild(otherDataElts);

        PlotGenerator plotTool = new PlotGenerator();

        for (int f = 0; f < matchingFiles.getLength(); f++) {
            Element fileNode = (Element) matchingFiles.item(f);
            String dataFilePath = fileNode.getAttribute("absolutePath");
            //copy file
            String dataFileNewName = dataFilePath.substring(dirPath.length() + 1)
                    .replaceAll(PATH_FOLDER_SEPARATOR_REGEX, "_");
            String dataFileDestPath = dataDirPath + PATH_FOLDER_SEPARATOR + dataFileNewName;
            Files.copy(Paths.get(dataFilePath), Paths.get(dataFileDestPath),
                    StandardCopyOption.REPLACE_EXISTING);
            //set read permissions
            if (!Utils.isWindows()) {
                HashSet<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.OTHERS_READ);
                Files.setPosixFilePermissions(Paths.get(dataFileDestPath), permissions);
            }
            //read file AVUs
            NodeList avuNodes = (NodeList) xreader.read("//file[@absolutePath='" + dataFilePath + "']/AVUs/AVU",
                    XPathConstants.NODESET);
            MetadataAVUList avuList = new MetadataAVUList();
            if (avuNodes != null) {
                for (int a = 0; a < avuNodes.getLength(); a++) {
                    Element avuNode = (Element) avuNodes.item(a);
                    avuList.add(new MetadataAVU(avuNode.getAttribute("id").toUpperCase(),
                            avuNode.getFirstChild().getNodeValue()));
                }
            }

            //add reference in XML doc
            String description = avuList.getValue(FileMetadata.FILE_DESCRIPTION);
            String format = fileNode.getAttribute("format");
            if (IBIOMESFileGroup.isJmolFile(format)) {
                Element jmolFileElt = docWorkflow.createElement("structure");
                jmolFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    jmolFileElt.setAttribute("description", description);
                pdbElt.appendChild(jmolFileElt);
            } else if (format.equals(LocalFile.FORMAT_CSV)) {
                Element csvElt = docWorkflow.createElement("spreadsheet");
                csvElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    csvElt.setAttribute("description", description);
                csvElts.appendChild(csvElt);
                //try to generate plot and save image
                try {
                    String imgPath = dataFileNewName + "_plot.png";
                    String plotType = generatePlotForCSV(plotTool, dataFileDestPath, avuList,
                            dataFileDestPath + "_plot", "png");
                    csvElt.setAttribute("plotPath", imgPath);
                    if (outputToConsole) {
                        if (plotType == null)
                            plotType = "";
                        else
                            plotType += " ";
                        System.out.println("\t" + plotType + "plot generated for " + dataFileNewName);
                    }

                } catch (Exception e) {
                    if (outputToConsole)
                        System.out.println(
                                "Warning: Plot for '" + dataFileDestPath + "' could not be generated.");
                    try {
                        if (IBIOMESConfiguration.getInstance().isOutputErrorStackToConsole())
                            e.printStackTrace();
                    } catch (Exception e1) {
                    }
                }
            } else if (IBIOMESFileGroup.isImageFile(format)) {
                Element imgFileElt = docWorkflow.createElement("image");
                imgFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    imgFileElt.setAttribute("description", description);
                imgElt.appendChild(imgFileElt);
            } else {
                Element otherFileElt = docWorkflow.createElement("unknown");
                otherFileElt.setAttribute("path", dataFileNewName);
                if (description != null && description.length() > 0)
                    otherFileElt.setAttribute("description", description);
                imgElt.appendChild(otherDataElts);
            }
        }
    }

    //update XML files
    File outputXmlAvusFile = new File(fileTreeXmlPath);
    if (outputXmlAvusFile.exists())
        outputXmlAvusFile.delete();

    File outputXmlWorkflowFile = new File(workflowXmlPath);
    if (outputXmlWorkflowFile.exists())
        outputXmlWorkflowFile.delete();

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    DOMSource source = new DOMSource(fileTreeDoc);
    StreamResult result = null;
    result = new StreamResult(fileTreeXmlPath);
    transformer.transform(source, result);

    source = new DOMSource(docWorkflow);
    result = null;
    result = new StreamResult(outputXmlWorkflowFile);
    transformer.transform(source, result);
}

From source file:sce.ProcessExecutor.java

/**
 * File Permissions using File and PosixFilePermission
 *
 * @throws IOException//from   w ww .  j  a  v  a2  s .  co m
 */
public void setFilePermissions() throws IOException {
    File file = new File("/Users/temp.txt");

    //set application user permissions to 455
    file.setExecutable(false);
    file.setReadable(false);
    file.setWritable(true);

    //change permission to 777 for all the users
    //no option for group and others
    file.setExecutable(true, false);
    file.setReadable(true, false);
    file.setWritable(true, false);

    //using PosixFilePermission to set file permissions 777
    Set<PosixFilePermission> perms = new HashSet<>();
    //add owners permission
    perms.add(PosixFilePermission.OWNER_READ);
    perms.add(PosixFilePermission.OWNER_WRITE);
    perms.add(PosixFilePermission.OWNER_EXECUTE);
    //add group permissions
    perms.add(PosixFilePermission.GROUP_READ);
    perms.add(PosixFilePermission.GROUP_WRITE);
    perms.add(PosixFilePermission.GROUP_EXECUTE);
    //add others permissions
    perms.add(PosixFilePermission.OTHERS_READ);
    perms.add(PosixFilePermission.OTHERS_WRITE);
    perms.add(PosixFilePermission.OTHERS_EXECUTE);

    Files.setPosixFilePermissions(Paths.get("/Users/pankaj/run.sh"), perms);
}