Example usage for java.io File setWritable

List of usage examples for java.io File setWritable

Introduction

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

Prototype

public boolean setWritable(boolean writable) 

Source Link

Document

A convenience method to set the owner's write permission for this abstract pathname.

Usage

From source file:org.eclipse.cft.server.core.internal.CloudUtil.java

/**
 * Creates a temporary folder and file with the given names. It is the
 * responsibility of the caller to properly dispose the folder and file
 * after it is created/*from  w  w  w.  ja va  2s  .com*/
 * @param folderName
 * @param fileName
 * @return
 * @throws IOException
 */
public static File createTemporaryFile(String folderName, String fileName) throws IOException {
    File tempFolder = File.createTempFile(folderName, null);
    // Delete an existing one
    tempFolder.delete();

    tempFolder.mkdirs();
    tempFolder.setExecutable(true);

    File targetFile = new File(tempFolder, fileName);

    // delete existing file
    targetFile.delete();

    targetFile.createNewFile();
    targetFile.setExecutable(true);
    targetFile.setWritable(true);

    return targetFile;
}

From source file:jenkins.plugins.asqatasun.AsqatasunRunnerBuilder.java

/**
 * Create a temporary file within a temporary folder, created in the
 * contextDir if not exists (first time)
 * @param contextDir//from  w ww . ja v  a 2s. c o  m
 * @param fileName
 * @param fileContent
 * @return
 * @throws IOException 
 */
public static File createTempFile(File contextDir, String fileName, String fileContent) throws IOException {
    File contextDirTemp = new File(contextDir.getAbsolutePath() + "/tmp");
    if (!contextDirTemp.exists() && contextDirTemp.mkdir()) {
        contextDirTemp.setExecutable(true);
        contextDirTemp.setWritable(true);
    }
    File tempFile = new File(contextDirTemp.getAbsolutePath() + "/" + fileName);
    FileUtils.writeStringToFile(tempFile, fileContent);
    if (tempFile.exists()) {
        tempFile.setExecutable(true);
        tempFile.setWritable(true);
    }
    return tempFile;
}

From source file:jenkins.plugins.tanaguru.TanaguruRunnerBuilder.java

/**
 * Create a temporary file within a temporary folder, created in the
 * contextDir if not exists (first time)
 * @param contextDir/*from ww  w.jav a 2 s.  com*/
 * @param fileName
 * @param fileContent
 * @return
 * @throws IOException 
 */
public static File createTempFile(File contextDir, String fileName, String fileContent) throws IOException {
    File contextDirTemp = new File(contextDir.getAbsolutePath() + "/tmp");
    if (!contextDirTemp.exists()) {
        if (contextDirTemp.mkdir()) {
            contextDirTemp.setExecutable(true);
            contextDirTemp.setWritable(true);
        }
    }
    File tempFile = new File(contextDirTemp.getAbsolutePath() + "/" + fileName);
    FileUtils.writeStringToFile(tempFile, fileContent);
    if (tempFile.exists()) {
        tempFile.setExecutable(true);
        tempFile.setWritable(true);
    }
    return tempFile;
}

From source file:org.limewire.util.FileUtils.java

public static void copyDirectoryRecursively(File srcDir, File targetDir) {
    if (!targetDir.exists()) {
        targetDir.mkdir();// w  ww . ja v a2s.c  om
        targetDir.setWritable(true);
    }

    for (File srcElement : srcDir.listFiles()) {
        if (srcElement.isFile()) {
            FileUtils.copy(srcElement, new File(targetDir + File.separator + srcElement.getName()));
        } else if (srcElement.isDirectory()) {
            FileUtils.copyDirectoryRecursively(srcElement, new File(targetDir, srcElement.getName()));
        }
    }
}

From source file:org.jboss.tools.openshift.reddeer.utils.FileHelper.java

public static void extractTarGz(File archive, File outputDirectory) {
    InputStream inputStream = null;
    try {//from   w  w w  .ja  va  2  s .  co  m
        logger.info("Opening stream to gzip archive");
        inputStream = new GzipCompressorInputStream(new FileInputStream(archive));
    } catch (IOException ex) {
        throw new OpenShiftToolsException(
                "Exception occured while processing tar.gz file.\n" + ex.getMessage());
    }

    logger.info("Opening stream to tar archive");
    BufferedOutputStream outputStream = null;
    TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(inputStream);
    TarArchiveEntry currentEntry = null;
    try {
        while ((currentEntry = tarArchiveInputStream.getNextTarEntry()) != null) {
            if (currentEntry.isDirectory()) {
                logger.info("Creating directory: " + currentEntry.getName());
                createDirectory(new File(outputDirectory, currentEntry.getName()));
            } else {
                File outputFile = new File(outputDirectory, currentEntry.getName());
                if (!outputFile.getParentFile().exists()) {
                    logger.info("Creating directory: " + outputFile.getParentFile());
                    createDirectory(outputFile.getParentFile());
                }

                outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

                logger.info("Extracting file: " + currentEntry.getName());
                copy(tarArchiveInputStream, outputStream, (int) currentEntry.getSize());
                outputStream.close();

                outputFile.setExecutable(true);
                outputFile.setReadable(true);
                outputFile.setWritable(true);
            }
        }
    } catch (IOException e) {
        throw new OpenShiftToolsException("Exception occured while processing tar.gz file.\n" + e.getMessage());
    } finally {
        try {
            tarArchiveInputStream.close();
        } catch (Exception ex) {
        }
        try {
            outputStream.close();
        } catch (Exception ex) {
        }
    }
}

From source file:org.scify.NewSumServer.Server.Utils.Main.java

private static void writeSummaryToFile(List<Sentence> lsSen, String sCluster, HashMap<String, Topic> hsTopics)
        throws IOException {
    File f = new File(sTxtSumPath);
    if (!f.exists()) {
        System.err.println("FILE " + sTxtSumPath + " DOES NOT EXIST");
        if (!f.mkdirs()) {
            System.err.println("FILE " + sTxtSumPath + " Could not be created");
        }/*w ww .  j  a v  a 2s  .  co m*/
    }
    if (f.isDirectory()) {
        f.setWritable(true);
    }
    String sFullFileName = sTxtSumPath + sCluster + ".txt";
    File fFile = new File(sFullFileName);
    fFile.createNewFile();
    BufferedWriter bw = new BufferedWriter(new FileWriter(fFile, false));
    bw.write("ClusterID" + sSep + sCluster);
    bw.newLine();
    bw.write("Title: " + hsTopics.get(sCluster).getTitle());
    bw.write(("\n========================================\n"));
    StringBuilder sb = new StringBuilder();
    ListIterator<Sentence> li = lsSen.listIterator();
    while (li.hasNext()) {
        Sentence sCur = li.next();
        if (sCur.getSnippet().split("[;,. ]").length < 5) {
            li.remove();
        }
    }
    lsSen = new RedundancyRemover().removeRedundantSentences(lsSen);
    for (Sentence each : lsSen) {
        sb.append(each.getSnippet());
        sb.append("\n========================================\n");
        //            sb.append(each.getLinkToSource());
        //            sb.append("\n");
        //            sb.append(each.getFeed());
        //            sb.append("\n");
    }
    bw.write(sb.toString());
    bw.close();
}

From source file:org.cytoscape.app.internal.manager.App.java

public static boolean delete(File f) {
    if (!f.exists()) {
        System.err.println("Cannot delete, file does not exist: " + f.getPath());
        return false;
    }/*from  ww  w  .j a  v a2s . c  o m*/
    f.setReadable(true);
    f.setWritable(true);
    if (!f.canWrite()) {
        System.err.println("Cannot delete, file is read-only: " + f.getPath());
        return false;
    }

    // Hack attempt  
    File parent = f.getParentFile();
    parent.setReadable(true);
    parent.setWritable(true);
    if (!parent.canWrite()) {
        System.err.println("Cannot delete, parent folder read-only: " + parent.getPath());
        return false;
    }

    try {
        (new SecurityManager()).checkDelete(f.getPath());
    } catch (Exception ex) {
        System.err.println("Cannot delete file, " + ex.getMessage());
        return false;
    }

    boolean ret = f.delete();
    if (!ret)
        System.err.println("Delete failed: " + f.getPath());
    return ret;
}

From source file:org.jboss.tools.openshift.reddeer.utils.FileHelper.java

private static void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDirectory) {

    if (entry.isDirectory()) {
        createDirectory(new File(outputDirectory, entry.getName()));
        return;/*w ww. j av  a  2  s.  c o m*/
    }

    File outputFile = new File(outputDirectory, entry.getName());
    if (!outputFile.getParentFile().exists()) {
        createDirectory(outputFile.getParentFile());
    }

    BufferedInputStream inputStream = null;
    BufferedOutputStream outputStream = null;
    try {
        inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
        outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));
        copy(inputStream, outputStream, 1024);
    } catch (IOException ex) {
    } finally {
        try {
            outputStream.close();
        } catch (Exception ex) {
        }
        try {
            inputStream.close();
        } catch (Exception ex) {
        }
    }
    outputFile.setExecutable(true);
    outputFile.setReadable(true);
    outputFile.setWritable(true);
}

From source file:com.frostwire.gui.updates.InstallerUpdater.java

public final static void downloadTorrentFile(String torrentURL, File saveLocation)
        throws IOException, URISyntaxException {
    byte[] contents = new HttpFetcher(new URI(torrentURL)).fetch();

    // save the torrent locally if you have to
    if (saveLocation != null && contents != null && contents.length > 0) {

        if (saveLocation.exists()) {
            saveLocation.delete();/*from  w ww  . j  a  v a  2 s .co m*/
        }

        //Create all the route necessary to save the .torrent file if it does not exit.
        saveLocation.getParentFile().mkdirs();
        saveLocation.createNewFile();
        saveLocation.setWritable(true);

        FileOutputStream fos = new FileOutputStream(saveLocation, false);
        fos.write(contents);
        fos.flush();
        fos.close();
    }
}

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./*from  w w  w . j ava  2s  .  co m*/
 *
 * @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());
            }
        }
    }
}