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, boolean ownerOnly) 

Source Link

Document

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

Usage

From source file:org.apache.flink.runtime.taskexecutor.TaskManagerRunnerStartupTest.java

/**
 * Tests that the TaskManagerRunner startup fails synchronously when the I/O
 * directories are not writable.//ww w . j  a va  2  s .  com
 */
@Test
public void testIODirectoryNotWritable() throws Exception {
    File nonWritable = tempFolder.newFolder();
    Assume.assumeTrue("Cannot create non-writable temporary file directory. Skipping test.",
            nonWritable.setWritable(false, false));

    try {
        Configuration cfg = new Configuration();
        cfg.setString(CoreOptions.TMP_DIRS, nonWritable.getAbsolutePath());

        try {

            startTaskManager(cfg, rpcService, highAvailabilityServices);

            fail("Should fail synchronously with an IOException");
        } catch (IOException e) {
            // splendid!
        }
    } finally {
        // noinspection ResultOfMethodCallIgnored
        nonWritable.setWritable(true, false);
        try {
            FileUtils.deleteDirectory(nonWritable);
        } catch (IOException e) {
            // best effort
        }
    }
}

From source file:gov.jgi.meta.MetaUtils.java

/**
 * given a map of sequences indexed by sequence id, write out a fasta file to local file system.
 * files are created with rwx bits set to 777.
 *
 * @param seqList is the list of sequences to create the database with
 * @param tmpFileName the file name/path to create
 * @return the full path of the location of the database
 * @throws IOException if error occures in file creation
 *///from  ww w. j ava 2 s  . c  o m
public static String sequenceToLocalFile(Map<String, String> seqList, String tmpFileName) throws IOException {
    BufferedWriter out;
    File seqFile = null;

    /*
     * open temp file
     */
    seqFile = new File(tmpFileName);
    out = new BufferedWriter(new FileWriter(seqFile.getPath()));

    /*
     * write out the sequences to file
     */
    for (String key : seqList.keySet()) {
        assert (seqList.get(key) != null);
        out.write(">" + key + "\n");
        out.write(seqList.get(key) + "\n");
    }

    /*
     * close temp file
     */
    out.close();

    if (!(seqFile.setExecutable(true, false) && seqFile.setReadable(true, false)
            && seqFile.setWritable(true, false))) {
        throw new IOException("unable to set RWX bits to 777");
    }

    return (seqFile.getPath());
}

From source file:org.rhq.enterprise.server.plugins.jdr.JdrServerPluginComponent.java

private void writeAccessToken() {
    File dataDir = new File(System.getProperty("jboss.server.data.dir"));
    if (!dataDir.exists() || !dataDir.canWrite()) {
        log.error("Failed to write access token, jboss.server.data.dir=" + dataDir
                + " does not exist or not writable");
        return;/*  www. ja  v a2s  .  c o  m*/
    }
    File file = new File(dataDir, TOKEN_FILE_NAME);

    try {
        PrintWriter pw = new PrintWriter(file);
        pw.println(accessToken);
        pw.close();
        file.setWritable(true, true);
        file.setReadable(true, true);
        file.setExecutable(false, false);
        boolean isWindows = (File.separatorChar == '\\');
        if (!isWindows) {
            try {
                Runtime.getRuntime().exec("chmod 600 " + file.getAbsolutePath());
            } catch (IOException e) {
                log.error("Unable to set file permissions", e);
            }
        }
    } catch (FileNotFoundException fnfe) {
        log.error("Failed to write acces token, jboss.server.data.dir=" + file.getParent()
                + " does not exist or not writable");
    }
}

From source file:org.ow2.proactive.scheduler.task.TaskLogger.java

public File createFileAppender(File pathToFolder) throws IOException {
    if (taskLogAppender.getAppender(FILE_APPENDER_NAME) != null) {
        throw new IllegalStateException("Only one file appender can be created");
    }//from   w ww. j av a 2 s  .  com

    File logFile = new File(pathToFolder, new TaskLoggerRelativePathGenerator(taskId).getRelativePath());

    logFile.getParentFile().mkdirs();

    FileUtils.touch(logFile);

    logFile.setWritable(true, false);

    FileAppender fap = new FileAppender(Log4JTaskLogs.getTaskLogLayout(), logFile.getAbsolutePath(), false);
    fap.setName(FILE_APPENDER_NAME);
    taskLogAppender.addAppender(fap);

    return logFile;
}

From source file:com.papteco.client.netty.SelProjectClientHandler.java

private void prepareLocalFolders(ProjectBean project) {
    File projectFolder = new File(EnvConstant.LCL_STORING_PATH, project.getProjectCde());
    if (!projectFolder.exists()) {
        projectFolder.mkdirs();// w  w  w  .  j a v  a2 s. c om
        projectFolder.setExecutable(true, false);
        projectFolder.setReadable(true, false);
        projectFolder.setWritable(true, false);
        // logger.info("Folder \"" + projectFolder.getName()
        // + "\" created!");
    } else {
        // logger.info("Folder \"" + projectFolder.getName()
        // + "\" existing already!");
    }

    for (FolderBean folder : project.getFolderTree()) {
        File sf = new File(projectFolder.getPath(), folder.getFolderName());
        if (!sf.exists()) {
            sf.mkdirs();
            sf.setExecutable(true, false);
            sf.setReadable(true, false);
            sf.setWritable(true, false);
            // logger.info("(execable, readable, writeable) - ("
            // + sf.canExecute() + ", " + sf.canRead() + ", "
            // + sf.canWrite() + ") - " + projectFolder.getPath()
            // + "/" + folder.getFolderName());
        } else {
            // logger.info("(execable, readable, writeable) - ("
            // + sf.canExecute() + ", " + sf.canRead() + ", "
            // + sf.canWrite() + ") - " + projectFolder.getPath()
            // + "/" + folder.getFolderName() + " [existing already]");
        }
    }
    logger.info("Folders creation finish.");
}

From source file:org.apache.hadoop.io.crypto.tool.BeeCli.java

private void credentailsFileWriter(Credentials credentials, String path) throws Exception {
    DataOutputStream dos = new DataOutputStream(new FileOutputStream(path));
    credentials.writeTokenStorageToStream(dos);
    File f = new File(path);
    f.setExecutable(false, false);/*from w w w.  j  av  a 2 s  .  co m*/
    f.setReadable(true, true);
    f.setWritable(true, true);
}

From source file:org.apache.flink.contrib.streaming.state.RocksDBStateBackendConfigTest.java

@Test
public void testFailWhenNoLocalStorageDir() throws Exception {
    String checkpointPath = tempFolder.newFolder().toURI().toString();
    RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(checkpointPath);
    File targetDir = tempFolder.newFolder();

    try {//from   w w  w  . j a  va 2 s .c om
        if (!targetDir.setWritable(false, false)) {
            System.err.println(
                    "Cannot execute 'testFailWhenNoLocalStorageDir' because cannot mark directory non-writable");
            return;
        }

        rocksDbBackend.setDbStoragePath(targetDir.getAbsolutePath());

        boolean hasFailure = false;
        try {
            Environment env = getMockEnvironment();
            rocksDbBackend.createKeyedStateBackend(env, env.getJobID(), "foobar", IntSerializer.INSTANCE, 1,
                    new KeyGroupRange(0, 0),
                    new KvStateRegistry().createTaskRegistry(env.getJobID(), new JobVertexID()));
        } catch (Exception e) {
            assertTrue(e.getMessage().contains("No local storage directories available"));
            assertTrue(e.getMessage().contains(targetDir.getAbsolutePath()));
            hasFailure = true;
        }
        assertTrue("We must see a failure because no storaged directory is feasible.", hasFailure);
    } finally {
        //noinspection ResultOfMethodCallIgnored
        targetDir.setWritable(true, false);
        FileUtils.deleteDirectory(targetDir);
    }
}

From source file:com.seedboxer.seedboxer.sources.processors.QueueProcessor.java

private String downloadFile(URL url, String path) throws IOException {
    URLConnection conn = url.openConnection();
    InputStream in = conn.getInputStream();
    String disposition = conn.getHeaderField("Content-Disposition");
    String fileNameProperty = "filename=\"";
    String fileName = disposition.substring(disposition.indexOf(fileNameProperty),
            disposition.lastIndexOf("\""));
    fileName = fileName.substring(fileNameProperty.length(), fileName.length());
    path += File.separator + fileName;
    File file = new File(path);
    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    byte[] bytes = new byte[1024];
    int read;//from  ww w  .  jav  a2s  .co m
    while ((read = in.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }
    in.close();
    out.close();
    file.setReadable(true, false);
    file.setWritable(true, false);
    return fileName;
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.loc.AbstractServiceUpdater.java

private void deleteDatabase(final File db) {
    db.setReadable(true, true);//from  www.j  a v a  2s .co m
    db.setWritable(true, false);

    if (db.isDirectory()) {
        for (final File file : db.listFiles()) {
            file.delete();
        }
        LOGGER.debug("[" + getClass().getSimpleName() + "] Successfully deleted database under: " + db);
    } else {
        db.delete();
    }
}

From source file:com.intel.chimera.utils.NativeCodeLoader.java

/**
 * Extracts the specified library file to the target folder.
 * /*from ww w .j a va 2s  .  c om*/
 * @param libFolderForCurrentOS the library in chimera.lib.path.
 * @param libraryFileName the library name.
 * @param targetFolder Target folder for the native lib. Use the value of
 *                     chimera.tempdir or java.io.tmpdir.
 * @return the library file.
 */
private static File extractLibraryFile(String libFolderForCurrentOS, String libraryFileName,
        String targetFolder) {
    String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;

    // Attach UUID to the native library file to ensure multiple class loaders
    // can read the libchimera multiple times.
    String uuid = UUID.randomUUID().toString();
    String extractedLibFileName = String.format("chimera-%s-%s-%s", getVersion(), uuid, libraryFileName);
    File extractedLibFile = new File(targetFolder, extractedLibFileName);

    InputStream reader = null;
    try {
        // Extract a native library file into the target directory
        reader = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath);
        FileOutputStream writer = new FileOutputStream(extractedLibFile);
        try {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, bytesRead);
            }
        } finally {
            // Delete the extracted lib file on JVM exit.
            extractedLibFile.deleteOnExit();

            if (writer != null) {
                writer.close();
            }

            if (reader != null) {
                reader.close();
                reader = null;
            }
        }

        // Set executable (x) flag to enable Java to load the native library
        if (!extractedLibFile.setReadable(true) || !extractedLibFile.setExecutable(true)
                || !extractedLibFile.setWritable(true, true)) {
            throw new RuntimeException("Invalid path for library path");
        }

        // Check whether the contents are properly copied from the resource folder
        {
            InputStream nativeIn = null;
            InputStream extractedLibIn = null;
            try {
                nativeIn = NativeCodeLoader.class.getResourceAsStream(nativeLibraryFilePath);
                extractedLibIn = new FileInputStream(extractedLibFile);
                if (!contentsEquals(nativeIn, extractedLibIn))
                    throw new RuntimeException(
                            String.format("Failed to write a native library file at %s", extractedLibFile));
            } finally {
                if (nativeIn != null)
                    nativeIn.close();
                if (extractedLibIn != null)
                    extractedLibIn.close();
            }
        }

        return new File(targetFolder, extractedLibFileName);
    } catch (IOException e) {
        e.printStackTrace(System.err);
        return null;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}