Example usage for java.nio.file Files setPosixFilePermissions

List of usage examples for java.nio.file Files setPosixFilePermissions

Introduction

In this page you can find the example usage for java.nio.file Files setPosixFilePermissions.

Prototype

public static Path setPosixFilePermissions(Path path, Set<PosixFilePermission> perms) throws IOException 

Source Link

Document

Sets a file's POSIX permissions.

Usage

From source file:jenkins.plugins.pbs.tasks.Qsub.java

public Boolean call() {
    final String myLogBasename = (logBasename.length() > 0) ? logBasename : System.getenv("java.io.tmpdir");

    try {/*www.java2 s . com*/
        // If we are running as another user, we are going to make sure we
        // set permissions more loosely
        Path tmpDir = Files.createTempDirectory(Paths.get(myLogBasename), "jenkinsPBS_");
        File tmpDirFile = tmpDir.toFile();
        if (!tmpDirFile.exists()) {
            if (!tmpDirFile.mkdirs()) {
                listener.getLogger().println("Failed to create working directory: " + tmpDir.toString());
                throw new PBSException("Failed to create working directory: " + tmpDir.toString());
            }
        }

        this.executionDirectory = tmpDir.toString();
        if (this.runUser.length() > 0) {
            Files.setPosixFilePermissions(Paths.get(this.executionDirectory),
                    PosixFilePermissions.fromString("rwxrwxrwx"));
        }
        listener.getLogger()
                .println(String.format("Created working directory '%s' with permissions '%s'",
                        this.executionDirectory, PosixFilePermissions
                                .toString(Files.getPosixFilePermissions(Paths.get(this.executionDirectory)))));
    } catch (IOException e) {
        listener.fatalError(e.getMessage(), e);
        throw new PBSException("Failed to create working directory: " + e.getMessage(), e);
    }

    if (StringUtils.isNotBlank(logHostname)) {
        this.errFileName = String.format("%s:%s", logHostname, Paths.get(this.executionDirectory, "err"));
        this.outFileName = String.format("%s:%s", logHostname, Paths.get(this.executionDirectory, "out"));
    } else {
        this.errFileName = Paths.get(this.executionDirectory, "err").toString();
        this.outFileName = Paths.get(this.executionDirectory, "out").toString();
    }

    OutputStream tmpScriptOut = null;
    try {
        Path tmpScript = Paths.get(this.executionDirectory, "script");
        tmpScriptOut = Files.newOutputStream(tmpScript);
        tmpScriptOut.write(script.getBytes());
        tmpScriptOut.flush();

        listener.getLogger().println("PBS script: " + tmpScript.toString());
        String[] argList;
        if (this.runUser.length() > 0) {
            argList = new String[] { "-P", this.runUser, "-e", this.errFileName, "-o", this.outFileName,
                    tmpScript.toString(), "-W", "umask=022" };
        } else {
            argList = new String[] { "-e", this.errFileName, "-o", this.outFileName, tmpScript.toString() };
        }
        String jobId = PBS.qsub(argList, this.environment);

        listener.getLogger().println("PBS Job submitted: " + jobId);

        return this.seekEnd(jobId, numberOfDays, span);
    } catch (IOException e) {
        e.printStackTrace(listener.getLogger());
        throw new PBSException("Failed to create temp script");
    } finally {
        IOUtils.closeQuietly(tmpScriptOut);
    }
}

From source file:keywhiz.cli.ClientUtils.java

/**
 * Serialize the cookies to JSON from the given CookieManager to a file at the specified path.
 * Output file will have 660 permissions (owner-read, owner-write).
 *
 * @param cookieManager CookieManager that contains cookies to be serialized.
 * @param path Location to serialize cookies to file.
 *//*from ww w  . jav  a2  s  .  c  o m*/
public static void saveCookies(CookieManager cookieManager, Path path) {
    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    try (BufferedWriter writer = Files.newBufferedWriter(path, CREATE)) {
        Files.setPosixFilePermissions(path, ImmutableSet.of(OWNER_READ, OWNER_WRITE));
        writer.write(Jackson.newObjectMapper().writeValueAsString(
                cookies.stream().map(c -> JsonCookie.fromHttpCookie(c)).collect(Collectors.toList())));
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.dishevelled.thumbnail.AbstractThumbnailManager.java

/**
 * Fix the permissions of the specified file.
 *
 * @param file file//from w w  w.  jav  a2s . c o m
 */
private void fixPermissions(final File file) {
    try {
        // set to 600
        Files.setPosixFilePermissions(file.toPath(), FILE_PERMISSIONS);
    } catch (Exception e) {
        // ignore
    }
}

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

/**
 * Update the local WP-CLI tool to the most recent version.
 *///from   w  ww.ja  v  a2s  .c  o 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:com.redhat.jenkins.plugins.ci.integration.FedMsgMessagingPluginIntegrationTest.java

@Test
public void testTriggeringUsingFedMsgLogger() throws Exception {

    FreeStyleJob jobA = jenkins.jobs.create();
    jobA.configure();/*  ww w. j  av  a  2  s.  c o m*/
    jobA.addShellStep("echo CI_MESSAGE = $CI_MESSAGE");
    CIEventTrigger ciEvent = new CIEventTrigger(jobA);
    ciEvent.selector.set("topic = 'org.fedoraproject.dev.logger.log'");
    CIEventTrigger.MsgCheck check = ciEvent.addMsgCheck();
    check.expectedValue.set(".+compose_id.+message.+");
    check.field.set("compose");
    jobA.save();
    // Allow for connection
    elasticSleep(5000);

    File privateKey = File.createTempFile("ssh", "key");
    FileUtils.copyURLToFile(FedmsgRelayContainer.class.getResource("FedmsgRelayContainer/unsafe"), privateKey);
    Files.setPosixFilePermissions(privateKey.toPath(), singleton(OWNER_READ));

    File ssh = File.createTempFile("jenkins", "ssh");
    FileUtils.writeStringToFile(ssh, "#!/bin/sh\n" + "exec ssh -o StrictHostKeyChecking=no -i "
            + privateKey.getAbsolutePath() + " fedmsg2@" + fedmsgRelay.getIpAddress()
            //+ " fedmsg-logger --message=\\\"This is a message.\\\"");
            + " fedmsg-logger " + " \"$@\"");
    //+ "--message=\\\'{\\\"compose\\\": "
    //+ "{\\\"compose_id\\\": \\\"This is a message.\\\"}}\\\' --json-input");
    Files.setPosixFilePermissions(ssh.toPath(), new HashSet<>(Arrays.asList(OWNER_READ, OWNER_EXECUTE)));

    System.out.println(FileUtils.readFileToString(ssh));
    ProcessBuilder gitLog1Pb = new ProcessBuilder(ssh.getAbsolutePath(),
            "--message='{\"compose\": " + "{\"compose_id\": \"This is a message.\"}}\'", "--json-input");
    String output = stringFrom(logProcessBuilderIssues(gitLog1Pb, "ssh"));
    System.out.println(output);

    jobA.getLastBuild().shouldSucceed().shouldExist();
    assertThat(jobA.getLastBuild().getConsole(), containsString("This is a message"));

}

From source file:com.linkedin.pinot.core.segment.index.converter.SegmentV1V2ToV3FormatConverter.java

private void setDirectoryPermissions(File v3Directory) throws IOException {
    EnumSet<PosixFilePermission> permissions = EnumSet.of(PosixFilePermission.OWNER_READ,
            PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_READ,
            PosixFilePermission.GROUP_WRITE, PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.OTHERS_READ,
            PosixFilePermission.OTHERS_EXECUTE);

    Files.setPosixFilePermissions(v3Directory.toPath(), permissions);
}

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;//from  w w w.j ava2 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);
    }
}

From source file:org.dishevelled.thumbnail.AbstractThumbnailManager.java

/**
 * Fix the permissions of the specified directory.
 *
 * @param directory directory/*  w  w  w .  j  a  va  2 s .  c om*/
 */
private void fixDirectoryPermissions(final File directory) {
    try {
        // set to 700
        Files.setPosixFilePermissions(directory.toPath(), DIRECTORY_PERMISSIONS);
    } catch (Exception e) {
        // ignore
    }
}

From source file:io.stallion.boot.NewJavaPluginRunAction.java

public void makeNewApp(String javaFolder) throws Exception {
    targetFolder = javaFolder;//from  w ww  .  j  ava 2 s  .co m

    templating = new JinjaTemplating(targetFolder, false);

    setGroupId(promptForInputOfLength("What is the maven group name? ", 5));
    setPluginName(
            promptForInputOfLength("What is the plugin package name (will be appended to the groupid)? ", 2));
    setArtifactId(promptForInputOfLength("What maven artifact id? ", 5));

    setPluginNameTitleCase(getPluginName().substring(0, 1).toUpperCase() + getPluginName().substring(1));
    setJavaPackageName(getGroupId() + "." + getPluginName());

    File dir = new File(javaFolder);
    if (!dir.isDirectory()) {
        FileUtils.forceMkdir(dir);
    }

    String sourceFolder = "/src/main/java/" + getJavaPackageName().replaceAll("\\.", "/");
    List<String> paths = list(targetFolder + "/src/main/resources", targetFolder + "/src/main/resources/sql",
            targetFolder + "/src/test/resources",
            targetFolder + "/src/main/java/" + getJavaPackageName().replaceAll("\\.", "/"),
            targetFolder + "/src/test/java/" + getJavaPackageName().replaceAll("\\.", "/"));
    for (String path : paths) {
        File file = new File(path);
        if (!file.isDirectory()) {
            FileUtils.forceMkdir(file);
        }
    }
    new File(targetFolder + "/src/main/resources/sql/migrations.txt").createNewFile();

    Map ctx = map(val("config", this));
    copyTemplate("/templates/wizard/pom.xml.jinja", "pom.xml", ctx);
    copyTemplate("/templates/wizard/PluginBooter.java.jinja",
            sourceFolder + "/" + pluginNameTitleCase + "Plugin.java", ctx);
    copyTemplate("/templates/wizard/PluginSettings.java.jinja",
            sourceFolder + "/" + pluginNameTitleCase + "Settings.java", ctx);
    copyTemplate("/templates/wizard/MainRunner.java.jinja", sourceFolder + "/MainRunner.java", ctx);
    copyTemplate("/templates/wizard/Endpoints.java.jinja", sourceFolder + "/Endpoints.java", ctx);
    copyTemplate("/templates/wizard/build.py.jinja", "build.py", ctx);
    copyTemplate("/templates/wizard/run-dev.jinja", "run-dev.sh", ctx);

    Files.setPosixFilePermissions(FileSystems.getDefault().getPath(targetFolder + "/build.py"),
            set(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE));
    Files.setPosixFilePermissions(FileSystems.getDefault().getPath(targetFolder + "/run-dev.sh"),
            set(PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE));
    copyFile("/templates/wizard/app.bundle", "src/main/resources/assets/app.bundle");
    copyFile("/templates/wizard/app.js", "src/main/resources/assets/app.js");
    copyFile("/templates/wizard/app.scss", "src/main/resources/assets/app.scss");
    copyFile("/templates/wizard/file1.js", "src/main/resources/assets/common/file1.js");
    copyFile("/templates/wizard/file2.js", "src/main/resources/assets/common/file2.js");
    copyFile("/assets/vendor/jquery-1.11.3.js", "src/main/resources/assets/vendor/jquery-1.11.3.js");
    copyFile("/assets/basic/stallion.js", "src/main/resources/assets/vendor/stallion.js");
    copyFile("/templates/wizard/app.jinja", "src/main/resources/templates/app.jinja");

}

From source file:com.dangdang.ddframe.job.example.JavaMain.java

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();
    }//from  ww w  .  j av  a  2s  .c  o  m
    Path result = Paths.get(JavaMain.class.getResource("/script/demo.sh").getPath());
    Files.setPosixFilePermissions(result, PosixFilePermissions.fromString("rwxr-xr-x"));
    return result.toString();
}