Example usage for java.io File setReadable

List of usage examples for java.io File setReadable

Introduction

In this page you can find the example usage for java.io File setReadable.

Prototype

public boolean setReadable(boolean readable, boolean ownerOnly) 

Source Link

Document

Sets the owner's or everybody's read permission for this abstract pathname.

Usage

From source file:com.mods.grx.settings.utils.Utils.java

public static void delete_file(String filename) {
    File f = new File(filename);
    if (f.exists()) {
        f.setReadable(true, false);
        f.setWritable(true, false);/*from   w ww. j a  va2  s .  c  o  m*/
        f.delete();
    }
}

From source file:com.mods.grx.settings.utils.Utils.java

public static boolean rename_grx_tmp_file(String tmp_name) {

    String n_f = tmp_name.replace("grxtmp", "");
    File f_t = new File(tmp_name);
    if (f_t.exists()) {
        File f_f = new File(n_f);
        f_t.renameTo(f_f);/*  www  .j  av  a2 s.  c  om*/
        f_f.setReadable(true, false);
        f_f.setWritable(true, false);
        return true;
    }
    return false;
}

From source file:ezbake.protect.ezca.EzCABootstrap.java

public static void createAndWriteTarball(String name, AppCerts certs, String filePath) {
    TarArchiveOutputStream os = null;//from   w  w w  . j  av  a2s  . c  om
    try {
        File outputFile = new File(filePath, name + ".tar.gz");
        outputFile.createNewFile();
        outputFile.setWritable(false, false);
        outputFile.setWritable(true, true);
        outputFile.setReadable(false, false);
        outputFile.setReadable(true, true);
        FileOutputStream fos = new FileOutputStream(outputFile);

        CompressorOutputStream cos = new CompressorStreamFactory()
                .createCompressorOutputStream(CompressorStreamFactory.GZIP, fos);
        os = new TarArchiveOutputStream(cos);

        // For each field in the app certs, create an entry in the tar archive
        for (AppCerts._Fields field : AppCerts._Fields.values()) {
            Object o = certs.getFieldValue(field);
            if (o instanceof byte[]) {
                String fieldName = field.getFieldName().replace("_", ".");
                addTarArchiveEntry(os, fieldName, (byte[]) o);
            }
        }

    } catch (FileNotFoundException e) {
        logger.error("Unable to write tarball", e);
    } catch (CompressorException e) {
        logger.error("Error compressing tarball", e);
    } catch (IOException e) {
        logger.error("Error creating output file for tarball", e);
    } finally {
        if (os != null) {
            try {
                os.finish();
                os.close();
            } catch (IOException e) {
                logger.warn("Unable to close output stream", e);
            }
        }
    }
}

From source file:com.mods.grx.settings.utils.Utils.java

public static void set_read_write_file_permissions(String file_name) {
    if (file_name == null || file_name.isEmpty())
        return;//from   ww  w.j a  v a2s.c om
    try {
        File file = new File(file_name);
        if (file.exists()) {
            file.setReadable(true, false);
            file.setWritable(true, false);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.flink.client.FlinkYarnSessionCli.java

private static void writeYarnProperties(Properties properties, File propertiesFile) {
    try {/*from w  w  w.j  av  a2 s . c o m*/
        OutputStream out = new FileOutputStream(propertiesFile);
        properties.store(out, "Generated YARN properties file");
        out.close();
    } catch (IOException e) {
        throw new RuntimeException("Error writing the properties file", e);
    }
    propertiesFile.setReadable(true, false); // readable for all.
}

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

private static void setPermissionsOnFileInNonPosixSystem(final File file,
        final Set<PosixFilePermission> perms) {

    if (perms.contains(PosixFilePermission.OWNER_EXECUTE)) {
        file.setExecutable(true, !perms.contains(PosixFilePermission.OTHERS_EXECUTE));
    }//  w  w w  . j  av a 2 s  . c  om

    if (perms.contains(PosixFilePermission.OWNER_READ)) {
        file.setReadable(true, !perms.contains(PosixFilePermission.OTHERS_READ));
    }

    if (perms.contains(PosixFilePermission.OWNER_WRITE)) {
        file.setWritable(true, !perms.contains(PosixFilePermission.OTHERS_WRITE));
    }

}

From source file:org.apache.flink.yarn.cli.FlinkYarnSessionCli.java

private static void writeYarnProperties(Properties properties, File propertiesFile) {
    try (final OutputStream out = new FileOutputStream(propertiesFile)) {
        properties.store(out, "Generated YARN properties file");
    } catch (IOException e) {
        throw new RuntimeException("Error writing the properties file", e);
    }/*  ww w . ja  v a 2s .c  o m*/
    propertiesFile.setReadable(true, false); // readable for all.
}

From source file:io.hops.hopsworks.common.util.HopsUtils.java

/**
 * Utility method that copies project user certificates from the Database, to
 * either hdfs to be passed as LocalResources to the YarnJob or to used
 * by another method./*ww  w  .j  av a  2  s. com*/
 *
 * @param project
 * @param username
 * @param localTmpDir
 * @param remoteTmpDir
 * @param jobType
 * @param dfso
 * @param projectLocalResources
 * @param jobSystemProperties
 * @param flinkCertsDir
 * @param applicationId
 */
public static void copyProjectUserCerts(Project project, String username, String localTmpDir,
        String remoteTmpDir, JobType jobType, DistributedFileSystemOps dfso,
        List<LocalResourceDTO> projectLocalResources, Map<String, String> jobSystemProperties,
        String flinkCertsDir, String applicationId, CertificateMaterializer certMat, boolean isRpcTlsEnabled) {

    // Let the Certificate Materializer handle the certificates
    UserCerts userCert = new UserCerts(project.getName(), username);
    try {
        certMat.materializeCertificatesLocal(username, project.getName());
        CertificateMaterializer.CryptoMaterial material = certMat.getUserMaterial(username, project.getName());
        userCert.setUserKey(material.getKeyStore().array());
        userCert.setUserCert(material.getTrustStore().array());
        userCert.setUserKeyPwd(new String(material.getPassword()));
    } catch (IOException | CryptoPasswordNotFoundException ex) {
        throw new RuntimeException("Could not materialize user certificates", ex);
    }

    //Check if the user certificate was actually retrieved
    if (userCert.getUserCert() != null && userCert.getUserCert().length > 0 && userCert.getUserKey() != null
            && userCert.getUserKey().length > 0) {

        Map<String, byte[]> certFiles = new HashMap<>();
        certFiles.put(Settings.T_CERTIFICATE, userCert.getUserCert());
        certFiles.put(Settings.K_CERTIFICATE, userCert.getUserKey());

        try {
            String kCertName = HopsUtils.getProjectKeystoreName(project.getName(), username);
            String tCertName = HopsUtils.getProjectTruststoreName(project.getName(), username);
            String passName = getProjectMaterialPasswordName(project.getName(), username);

            try {
                if (jobType != null) {
                    switch (jobType) {
                    case FLINK:
                        File appDir = Paths.get(flinkCertsDir, applicationId).toFile();
                        if (!appDir.exists()) {
                            appDir.mkdir();
                        }

                        File f_k_cert = new File(appDir.toString() + File.separator + kCertName);
                        f_k_cert.setExecutable(false);
                        f_k_cert.setReadable(true, true);
                        f_k_cert.setWritable(false);

                        File t_k_cert = new File(appDir.toString() + File.separator + tCertName);
                        t_k_cert.setExecutable(false);
                        t_k_cert.setReadable(true, true);
                        t_k_cert.setWritable(false);

                        if (!f_k_cert.exists()) {
                            Files.write(certFiles.get(Settings.K_CERTIFICATE), f_k_cert);
                            Files.write(certFiles.get(Settings.T_CERTIFICATE), t_k_cert);
                        }

                        File certPass = new File(appDir.toString() + File.separator + passName);
                        certPass.setExecutable(false);
                        certPass.setReadable(true, true);
                        certPass.setWritable(false);
                        FileUtils.writeStringToFile(certPass, userCert.getUserKeyPwd(), false);
                        jobSystemProperties.put(Settings.CRYPTO_MATERIAL_PASSWORD, certPass.toString());
                        jobSystemProperties.put(Settings.K_CERTIFICATE, f_k_cert.toString());
                        jobSystemProperties.put(Settings.T_CERTIFICATE, t_k_cert.toString());
                        break;
                    case PYSPARK:
                    case SPARK:
                        Map<String, File> certs = new HashMap<>();
                        certs.put(Settings.K_CERTIFICATE, new File(localTmpDir + File.separator + kCertName));
                        certs.put(Settings.T_CERTIFICATE, new File(localTmpDir + File.separator + tCertName));
                        certs.put(Settings.CRYPTO_MATERIAL_PASSWORD,
                                new File(localTmpDir + File.separator + passName));

                        for (Map.Entry<String, File> entry : certs.entrySet()) {
                            //Write the actual file(cert) to localFS
                            //Create HDFS certificate directory. This is done
                            //So that the certificates can be used as LocalResources
                            //by the YarnJob
                            if (!dfso.exists(remoteTmpDir)) {
                                dfso.mkdir(new Path(remoteTmpDir),
                                        new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL));
                            }
                            //Put project certificates in its own dir
                            String certUser = project.getName() + "__" + username;
                            String remoteTmpProjDir = remoteTmpDir + File.separator + certUser;
                            if (!dfso.exists(remoteTmpProjDir)) {
                                dfso.mkdir(new Path(remoteTmpProjDir),
                                        new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.NONE));
                                dfso.setOwner(new Path(remoteTmpProjDir), certUser, certUser);
                            }

                            String remoteProjAppDir = remoteTmpProjDir + File.separator + applicationId;
                            Path remoteProjAppPath = new Path(remoteProjAppDir);
                            if (!dfso.exists(remoteProjAppDir)) {
                                dfso.mkdir(remoteProjAppPath,
                                        new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.NONE));
                                dfso.setOwner(remoteProjAppPath, certUser, certUser);
                            }

                            dfso.copyToHDFSFromLocal(false, entry.getValue().getAbsolutePath(),
                                    remoteProjAppDir + File.separator + entry.getValue().getName());

                            dfso.setPermission(
                                    new Path(remoteProjAppDir + File.separator + entry.getValue().getName()),
                                    new FsPermission(FsAction.ALL, FsAction.NONE, FsAction.NONE));
                            dfso.setOwner(
                                    new Path(remoteProjAppDir + File.separator + entry.getValue().getName()),
                                    certUser, certUser);

                            projectLocalResources.add(new LocalResourceDTO(entry.getKey(),
                                    "hdfs://" + remoteProjAppDir + File.separator + entry.getValue().getName(),
                                    LocalResourceVisibility.APPLICATION.toString(),
                                    LocalResourceType.FILE.toString(), null));
                        }
                        break;
                    default:
                        break;
                    }
                }
            } catch (IOException ex) {
                LOG.log(Level.SEVERE, "Error writing project user certificates to local fs", ex);
            }

        } finally {
            if (jobType != null) {
                certMat.removeCertificatesLocal(username, project.getName());
            }
        }
    }
}

From source file:com.ghgande.j2mod.modbus.utils.TestUtils.java

/**
 * This method will extract the appropriate Modbus master tool into the
 * temp folder so that it can be used later
 *
 * @return The temporary location of the Modbus master tool.
 * @throws Exception//ww w.  j  a  va  2s  .co  m
 */
public static File loadModPollTool() throws Exception {

    // Load the resource from the library

    String osName = System.getProperty("os.name");

    // Work out the correct name

    String exeName;
    if (osName.matches("(?is)windows.*")) {
        osName = "win32";
        exeName = "modpoll.exe";
    } else {
        osName = "linux";
        exeName = "modpoll";
    }

    // Copy the native modpoll library to a temporary directory in the build workspace to facilitate
    // execution on some platforms.
    File tmpDir = Files.createTempDirectory(Paths.get("."), "modpoll-").toFile();
    tmpDir.deleteOnExit();

    File nativeFile = new File(tmpDir, exeName);

    // Copy the library to the temporary folder

    InputStream in = null;
    String resourceName = String.format("/com/ghgande/j2mod/modbus/native/%s/%s", osName, exeName);

    try {
        in = SerialPort.class.getResourceAsStream(resourceName);
        if (in == null) {
            throw new Exception(String.format("Cannot find resource [%s]", resourceName));
        }
        pipeInputToOutputStream(in, nativeFile, false);
        nativeFile.deleteOnExit();

        // Set the correct privileges

        if (!nativeFile.setWritable(true, true)) {
            logger.warn("Cannot set modpoll native library to be writable");
        }
        if (!nativeFile.setReadable(true, false)) {
            logger.warn("Cannot set modpoll native library to be readable");
        }
        if (!nativeFile.setExecutable(true, false)) {
            logger.warn("Cannot set modpoll native library to be executable");
        }
    } catch (Exception e) {
        throw new Exception(
                String.format("Cannot locate modpoll native library [%s] - %s", exeName, e.getMessage()));
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("Cannot close stream - {}", e.getMessage());
            }
        }
    }

    return nativeFile;
}

From source file:net.sf.jasperreports.eclipse.util.FileUtils.java

public static File createTempDir(String prefix) throws IOException {
    final File sysTempDir = new File(System.getProperty("java.io.tmpdir")); //$NON-NLS-1$
    File newTempDir;
    final int maxAttempts = 9;
    int attemptCount = 0;
    do {/*from   www.j av a2s  .  c  o  m*/
        attemptCount++;
        if (attemptCount > maxAttempts)
            throw new IOException(NLS.bind(Messages.FileUtils_ImpossibleToCreateTempDirectory, maxAttempts));
        String dirName = prefix + System.currentTimeMillis();// gUUID.randomUUID().toString();
        newTempDir = new File(sysTempDir, dirName);
    } while (newTempDir.exists());

    if (newTempDir.mkdirs()) {
        newTempDir.deleteOnExit();
        newTempDir.setWritable(true, false);
        newTempDir.setReadable(true, false);
        return newTempDir;
    } else
        throw new IOException(
                NLS.bind(Messages.FileUtils_UnableToCreateDirectory, newTempDir.getAbsolutePath()));
}