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:com.frostwire.gui.updates.InstallerUpdater.java

private void handleHttpDownload() {
    File updateFolder = UpdateSettings.UPDATES_DIR;

    int index = _updateMessage.getInstallerUrl().lastIndexOf('/');
    File installerFileLocation = new File(updateFolder, _updateMessage.getInstallerUrl().substring(index + 1));

    if (!updateFolder.exists()) {
        updateFolder.mkdir();//from www .ja va2s .  co  m
        updateFolder.setWritable(true);
    }
    try {
        new HttpFetcher(new URI(_updateMessage.getInstallerUrl())).save(installerFileLocation);
        saveMetaData();
        cleanupOldUpdates();

        if (checkIfDownloaded()) {
            showUpdateMessage();
        }
    } catch (Throwable e) {
        LOG.error("Failed to download installer: " + _updateMessage.getInstallerUrl(), e);
    }
}

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

private File downloadDotTorrent() {

    File appSpecialShareFolder = UpdateSettings.UPDATES_DIR;

    int index = _updateMessage.getTorrent().lastIndexOf('/');
    File torrentFileLocation = new File(appSpecialShareFolder,
            _updateMessage.getTorrent().substring(index + 1));

    if (!appSpecialShareFolder.exists()) {
        appSpecialShareFolder.mkdir();/*w  w w.  ja  va  2  s .co  m*/
        appSpecialShareFolder.setWritable(true);
    }

    //We always re-download the torrent just in case.
    try {
        downloadTorrentFile(_updateMessage.getTorrent(), torrentFileLocation);
    } catch (Throwable e) {
        LOG.error("Error downloading update torrent file", e);
    }

    return torrentFileLocation;
}

From source file:org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.TestFsDatasetImpl.java

/**
 * Tests stopping all the active DataXceiver thread on volume failure event.
 * @throws Exception//w  w w.ja v  a 2 s  . c  o  m
 */
@Test
public void testCleanShutdownOfVolume() throws Exception {
    MiniDFSCluster cluster = null;
    try {
        Configuration config = new HdfsConfiguration();
        config.setLong(DFSConfigKeys.DFS_DATANODE_XCEIVER_STOP_TIMEOUT_MILLIS_KEY, 1000);
        config.setInt(DFSConfigKeys.DFS_DATANODE_FAILED_VOLUMES_TOLERATED_KEY, 1);

        cluster = new MiniDFSCluster.Builder(config).numDataNodes(1).build();
        cluster.waitActive();
        FileSystem fs = cluster.getFileSystem();
        DataNode dataNode = cluster.getDataNodes().get(0);
        Path filePath = new Path("test.dat");
        // Create a file and keep the output stream unclosed.
        FSDataOutputStream out = fs.create(filePath, (short) 1);
        out.write(1);
        out.hflush();

        ExtendedBlock block = DFSTestUtil.getFirstBlock(fs, filePath);
        FsVolumeImpl volume = (FsVolumeImpl) dataNode.getFSDataset().getVolume(block);
        File finalizedDir = volume.getFinalizedDir(cluster.getNamesystem().getBlockPoolId());

        if (finalizedDir.exists()) {
            // Remove write and execute access so that checkDiskErrorThread detects
            // this volume is bad.
            finalizedDir.setExecutable(false);
            finalizedDir.setWritable(false);
        }
        Assert.assertTrue("Reference count for the volume should be greater " + "than 0",
                volume.getReferenceCount() > 0);
        // Invoke the synchronous checkDiskError method
        dataNode.getFSDataset().checkDataDir();
        // Sleep for 1 second so that datanode can interrupt and cluster clean up
        Thread.sleep(1000);
        assertEquals("There are active threads still referencing volume: " + volume.getBasePath(), 0,
                volume.getReferenceCount());
        LocatedBlock lb = DFSTestUtil.getAllBlocks(fs, filePath).get(0);
        DatanodeInfo info = lb.getLocations()[0];

        try {
            out.close();
            Assert.fail("This is not a valid code path. " + "out.close should have thrown an exception.");
        } catch (IOException ioe) {
            GenericTestUtils.assertExceptionContains(info.getXferAddr(), ioe);
        }
        finalizedDir.setWritable(true);
        finalizedDir.setExecutable(true);
    } finally {
        cluster.shutdown();
    }
}

From source file:com.docdoku.cli.helpers.FileHelper.java

public void downloadNativeCADFile(URL serverURL, File path, String workspace, String partNumber,
        PartRevision pr, PartIteration pi, boolean force)
        throws IOException, LoginException, NoSuchAlgorithmException {
    BinaryResource bin = pi.getNativeCADFile();
    String fileName = bin.getName();
    PartIterationKey partIPK = new PartIterationKey(workspace, partNumber, pr.getVersion(), pi.getIteration());
    boolean writable = (pr.isCheckedOut()) && (pr.getCheckOutUser().getLogin().equals(login))
            && (pr.getLastIteration().getIteration() == pi.getIteration());
    File localFile = new File(path, fileName);
    MetaDirectoryManager meta = new MetaDirectoryManager(path);

    if (localFile.exists() && !force
            && localFile.lastModified() != meta.getLastModifiedDate(localFile.getAbsolutePath())) {
        boolean confirm = FileHelper.confirmOverwrite(localFile.getAbsolutePath());
        if (!confirm)
            return;
    }/*from   w ww  .ja  v a 2  s.  c  o m*/
    localFile.delete();
    System.out.println("Fetching part: " + partIPK.getPartMasterNumber() + " "
            + partIPK.getPartRevision().getVersion() + "." + partIPK.getIteration() + " (" + workspace + ")");
    String digest = downloadFile(localFile, FileHelper.getPartURL(serverURL, partIPK, fileName));
    localFile.setWritable(writable);

    saveMetadata(meta, partIPK, digest, localFile);
}

From source file:display.containers.FileManager.java

public static boolean copyFile(File from, File to) throws IOException {

    boolean created = to.createNewFile();

    if (created) {
        FileChannel fromChannel = null;
        FileChannel toChannel = null;
        try {/*  ww  w. j  a  va 2s .  co  m*/
            fromChannel = new FileInputStream(from).getChannel();
            toChannel = new FileOutputStream(to).getChannel();

            toChannel.transferFrom(fromChannel, 0, fromChannel.size());

            // set the flags of the to the same as the from
            to.setReadable(from.canRead());
            to.setWritable(from.canWrite());
            to.setExecutable(from.canExecute());
        } finally {
            if (fromChannel != null) {
                fromChannel.close();
            }
            if (toChannel != null) {
                toChannel.close();
            }
            return false;
        }
    }
    return created;
}

From source file:org.rapidbeans.rapidenv.Unpacker.java

private void setOutFileMode(final File file, final FileMode fileMode) {
    switch (PlatformHelper.getOsfamily()) {
    case linux:/*from   w  ww. j a  v  a2  s . c  o  m*/
        final String smode = fileMode.toChmodStringFull();
        final SystemCommand cmd = new SystemCommand();
        cmd.setExecutable("chmod");
        cmd.addArgument(new Argument(smode));
        cmd.addArgument(new Argument(file.getAbsolutePath()));
        cmd.setSilent(true);
        final CommandExecutionResult result = cmd.execute();
        if (result.getReturncode() != 0) {
            throw new RapidEnvException(
                    "Error while trying to set mode \"" + smode + "\" for file: " + file.getAbsolutePath());
        }
        break;
    default:
        file.setReadable(fileMode.isUr() || fileMode.isGr() || fileMode.isOr());
        file.setWritable(fileMode.isUw() || fileMode.isGw() || fileMode.isOw());
        file.setExecutable(fileMode.isUx() || fileMode.isGx() || fileMode.isOx());
        break;
    }
}

From source file:jenkins.plugins.shiningpanda.ShiningPandaTestCase.java

/**
 * Delete a VIRTUALENV./*  w ww  .  j  a v a  2  s  .  c  o m*/
 * 
 * @param home
 *            The home folder of the VIRTUALENV.
 * @throws IOException
 */
protected void deleteVirtualenv(File home) throws IOException {
    // Check if exists
    if (!home.exists())
        return;
    // Do not follow symbolic links
    IOFileFilter filter = new IOFileFilter() {
        /*
         * (non-Javadoc)
         * 
         * @see
         * org.apache.commons.io.filefilter.IOFileFilter#accept(java.io.
         * File, java.lang.String)
         */
        public boolean accept(File dir, String name) {
            return accept(dir);
        }

        /*
         * (non-Javadoc)
         * 
         * @see
         * org.apache.commons.io.filefilter.IOFileFilter#accept(java.io.
         * File)
         */
        public boolean accept(File file) {
            try {
                return !FileUtils.isSymlink(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
    };
    // Go threw the selected files to set write permission
    for (File file : FileUtils.listFiles(home, filter, filter)) {
        // Set write permission
        file.setWritable(true);
    }
    // Delete the directory
    FileUtils.deleteDirectory(home);
}

From source file:org.duracloud.sync.config.SyncToolConfigParser.java

protected SyncToolConfig processStandardOptions(String[] args, boolean requirePassword) throws ParseException {
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(cmdOptions, args);
    SyncToolConfig config = new SyncToolConfig();

    config.setContext(context);/*from  ww  w.  ja v  a  2s.  c  om*/
    config.setHost(cmd.getOptionValue("h"));
    config.setUsername(cmd.getOptionValue("u"));

    if (null != cmd.getOptionValue("p")) {
        config.setPassword(cmd.getOptionValue("p"));
    } else if (null != getPasswordEnvVariable()) {
        config.setPassword(getPasswordEnvVariable());
    } else if (requirePassword) {
        ConsolePrompt console = getConsole();
        if (null == console) {
            printHelp("You must either specify a password in the command " + "line or specify the "
                    + CommandLineToolUtil.PASSWORD_ENV_VARIABLE_NAME + " environmental variable.");
        } else {
            char[] password = console.readPassword("DuraCloud password: ");
            config.setPassword(new String(password));
        }
    }

    config.setSpaceId(cmd.getOptionValue("s"));

    if (cmd.hasOption("i")) {
        config.setStoreId(cmd.getOptionValue("i"));
    }

    if (cmd.hasOption("r")) {
        try {
            config.setPort(Integer.valueOf(cmd.getOptionValue("r")));
        } catch (NumberFormatException e) {
            throw new ParseException("The value for port (-r) must be " + "a number.");
        }
    } else {
        config.setPort(DEFAULT_PORT);
    }

    if (cmd.hasOption("w")) {
        File workDir = new File(cmd.getOptionValue("w"));
        if (workDir.exists()) {
            if (!workDir.isDirectory()) {
                throw new ParseException("Work Dir parameter must provide " + "the path to a directory. "
                        + "(optional, set to duracloud-" + "sync-work directory in user's "
                        + "home directory by default)");
            }
        } else {
            workDir.mkdirs();
        }
        workDir.setWritable(true);
        config.setWorkDir(workDir);
    } else {
        config.setWorkDir(null);
    }

    String[] contentDirPaths = cmd.getOptionValues("c");
    List<File> contentDirs = new ArrayList<File>();
    for (String path : contentDirPaths) {
        File contentDir = new File(path);
        if (!contentDir.exists() || !contentDir.isDirectory()) {
            throw new ParseException("Each content dir value must provide " + "the path to a directory.");
        }
        contentDirs.add(contentDir);
    }
    config.setContentDirs(contentDirs);

    if (cmd.hasOption("f")) {
        try {
            config.setPollFrequency(Long.valueOf(cmd.getOptionValue("f")));
        } catch (NumberFormatException e) {
            throw new ParseException("The value for poll frequency (-f) " + "must be a number.");
        }
    } else {
        config.setPollFrequency(DEFAULT_POLL_FREQUENCY);
    }

    if (cmd.hasOption("t")) {
        try {
            config.setNumThreads(Integer.valueOf(cmd.getOptionValue("t")));
        } catch (NumberFormatException e) {
            throw new ParseException("The value for threads (-t) must " + "be a number.");
        }
    } else {
        config.setNumThreads(DEFAULT_NUM_THREADS);
    }

    if (cmd.hasOption("m")) {
        String error = "The value for max-file-size (-m) must be a " + "number between 1 and 5.";
        try {
            long maxFileSize = Integer.valueOf(cmd.getOptionValue("m"));
            if (maxFileSize >= 1 && maxFileSize <= 5) {
                config.setMaxFileSize(maxFileSize * GIGABYTE);
            } else {
                throw new ParseException(error);
            }
        } catch (NumberFormatException e) {
            throw new ParseException(error);
        }
    } else {
        config.setMaxFileSize(DEFAULT_MAX_FILE_SIZE * GIGABYTE);
    }

    if (cmd.hasOption("o") && cmd.hasOption("n")) {
        throw new ParseException(
                "Options -o (no updates) and -n " + "(rename updates) cannot be used together.");
    }

    if (cmd.hasOption("o")) {
        config.setSyncUpdates(false);
    }

    if (cmd.hasOption("n") && cmd.hasOption("d")) {
        throw new ParseException(
                "Options -n (rename updates) and -d " + "(sync deletes) cannot be used together.");
    }

    if (cmd.hasOption("n")) {
        config.setRenameUpdates(true);
        String suffix = cmd.getOptionValue("n");
        if (StringUtils.isNotBlank(suffix)) {
            config.setUpdateSuffix(suffix);
        }
    }

    if (cmd.hasOption("d")) {
        config.setSyncDeletes(true);
    } else {
        config.setSyncDeletes(false);
    }

    if (cmd.hasOption("l")) {
        config.setCleanStart(true);
    } else {
        config.setCleanStart(false);
    }

    if (cmd.hasOption("j")) {
        config.setJumpStart(true);

        if (cmd.hasOption("n") || cmd.hasOption("o")) {
            throw new ParseException("The Jump Start option (-j) requires that updates be "
                    + "handled as overwrites, thus options -n (rename updates) "
                    + "and -o (no-updates) cannot be used at the same time.");
        }
    } else {
        config.setJumpStart(false);
    }

    if (cmd.hasOption("x")) {
        config.setExitOnCompletion(true);
    } else {
        config.setExitOnCompletion(false);
    }

    if (cmd.hasOption("e")) {
        File excludeFile = new File(cmd.getOptionValue("e"));
        if (!excludeFile.exists()) {
            throw new ParseException("Exclude parameter must provide the " + "path to a valid file.");
        }
        config.setExcludeList(excludeFile);
    }

    if (cmd.hasOption("a")) {
        config.setPrefix(cmd.getOptionValue("a"));
    }

    return config;
}

From source file:org.apache.solr.handler.dataimport.TestNonWritablePersistFile.java

@Test
@SuppressWarnings("unchecked")
public void testNonWritablePersistFile() throws Exception {
    // See SOLR-2551
    String configDir = h.getCore().getResourceLoader().getConfigDir();
    String filePath = configDir;/* www. j a  va  2s  .  c  o m*/
    if (configDir != null && !configDir.endsWith(File.separator))
        filePath += File.separator;
    filePath += "dataimport.properties";
    File f = new File(filePath);

    try {
        // execute the test only if we are able to set file to read only mode
        assumeTrue("No dataimport.properties file", f.exists() || f.createNewFile());
        assumeTrue("dataimport.properties can't be set read only", f.setReadOnly());
        assumeFalse("dataimport.properties is still writable even though "
                + "marked readonly - test running as superuser?", f.canWrite());

        ignoreException("Properties is not writable");

        @SuppressWarnings("rawtypes")
        List parentRow = new ArrayList();
        parentRow.add(createMap("id", "1"));
        MockDataSource.setIterator(FULLIMPORT_QUERY, parentRow.iterator());

        @SuppressWarnings("rawtypes")
        List childRow = new ArrayList();
        childRow.add(createMap("desc", "hello"));
        MockDataSource.setIterator("select * from y where y.A='1'", childRow.iterator());

        runFullImport(dataConfig_delta);
        assertQ(req("id:1"), "//*[@numFound='0']");
    } finally {
        f.setWritable(true);
    }
}