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.duracloud.retrieval.mgmt.RetrievalWorker.java

public Map<String, String> retrieveFile(RetrievalListener listener) {
    attempts++;//from w  w w . ja  v a2s .  co m
    File localFile = getLocalFile();
    Map<String, String> props = null;
    try {
        if (localFile.exists()) { // File already exists
            props = getContentProperties();
            if (checksumsMatch(localFile, props.get(ContentStore.CONTENT_CHECKSUM))) {
                noChangeNeeded(localFile.getAbsolutePath());
            } else { // Different file in DuraStore
                if (overwrite) {
                    deleteFile(localFile);
                } else {
                    renameFile(localFile);
                }
                props = retrieveToFile(localFile, listener);
                succeed(localFile.getAbsolutePath());
            }
        } else { // File does not exist
            File parentDir = localFile.getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
                parentDir.setWritable(true);
            }
            props = retrieveToFile(localFile, listener);
            succeed(localFile.getAbsolutePath());
        }
    } catch (Throwable e) {
        logger.error("Exception retrieving remote file " + contentItem.getContentId() + " as local file "
                + localFile.getAbsolutePath() + ": " + e.getMessage(), e);
        if (attempts < MAX_ATTEMPTS) {
            props = retrieveFile();
        } else {
            fail(e.getMessage());
        }
    }
    return props;
}

From source file:org.footware.server.services.TrackUploadServlet.java

private File initFileStructure(String user) {

    File tmpDirectory = new File("tmp");
    if (!tmpDirectory.exists()) {
        logger.debug("Create 'tmp' directory");
        tmpDirectory.mkdir();//from   w ww .  jav a  2 s .com
    }
    tmpDirectory.setWritable(true);

    // Check if import directory exists
    File importDirectory = new File("import");
    if (!importDirectory.exists()) {
        logger.debug("Create 'import' directory");
        importDirectory.mkdir();
    }

    // Check if user directoy exists
    File userDirectory = new File(importDirectory.getAbsolutePath() + "/" + user);
    if (!userDirectory.exists()) {
        logger.debug("Create '" + importDirectory.getAbsolutePath() + "/" + user + "' directory");
        userDirectory.mkdir();
    }
    return userDirectory;

}

From source file:org.dataone.proto.trove.mn.service.v1.impl.MNStorageImpl.java

@Override
public Identifier create(Identifier pid, InputStream object, SystemMetadata sysmeta)
        throws InvalidToken, ServiceFailure, NotAuthorized, IdentifierNotUnique, UnsupportedType,
        InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidRequest {
    try {// w ww . j a  v  a  2 s.  c om
        File systemMetadata = new File(dataoneCacheDirectory + File.separator + "meta" + File.separator
                + EncodingUtilities.encodeUrlPathSegment(pid.getValue()));
        TypeMarshaller.marshalTypeToFile(sysmeta, systemMetadata.getAbsolutePath());

        if (systemMetadata.exists()) {
            systemMetadata.setLastModified(sysmeta.getDateSysMetadataModified().getTime());
        } else {
            throw new ServiceFailure("1190", "SystemMetadata not found on FileSystem after create");
        }
        File objectFile = new File(dataoneCacheDirectory + File.separator + "object" + File.separator
                + EncodingUtilities.encodeUrlPathSegment(pid.getValue()));
        if (!objectFile.exists() && objectFile.createNewFile()) {
            objectFile.setReadable(true);
            objectFile.setWritable(true);
            objectFile.setExecutable(false);
        }

        if (object != null) {
            FileOutputStream objectFileOutputStream = new FileOutputStream(objectFile);
            BufferedInputStream inputStream = new BufferedInputStream(object);
            byte[] barray = new byte[SIZE];
            int nRead = 0;

            while ((nRead = inputStream.read(barray, 0, SIZE)) != -1) {
                objectFileOutputStream.write(barray, 0, nRead);
            }
            objectFileOutputStream.flush();
            objectFileOutputStream.close();
            inputStream.close();
        }
    } catch (FileNotFoundException ex) {
        throw new ServiceFailure("1190", ex.getCause().toString() + ":" + ex.getMessage());
    } catch (IOException ex) {
        throw new ServiceFailure("1190", ex.getMessage());
    } catch (JiBXException ex) {
        throw new InvalidSystemMetadata("1180", ex.getMessage());
    }
    return pid;
}

From source file:gov.nasa.jpl.mudrod.main.MudrodEngine.java

private String decompressSVMWithSGDModel(String archiveName) throws IOException {

    URL scmArchive = getClass().getClassLoader().getResource(archiveName);
    if (scmArchive == null) {
        throw new IOException("Unable to locate " + archiveName + " as a classpath resource.");
    }/*from  w ww.  j av  a2  s  .c  om*/
    File tempDir = Files.createTempDirectory("mudrod").toFile();
    assert tempDir.setWritable(true);
    File archiveFile = new File(tempDir, archiveName);
    FileUtils.copyURLToFile(scmArchive, archiveFile);

    // Decompress archive
    int BUFFER_SIZE = 512000;
    ZipInputStream zipIn = new ZipInputStream(new FileInputStream(archiveFile));
    ZipEntry entry;
    while ((entry = zipIn.getNextEntry()) != null) {
        File f = new File(tempDir, entry.getName());
        // If the entry is a directory, create the directory.
        if (entry.isDirectory() && !f.exists()) {
            boolean created = f.mkdirs();
            if (!created) {
                LOG.error("Unable to create directory '{}', during extraction of archive contents.",
                        f.getAbsolutePath());
            }
        } else if (!entry.isDirectory()) {
            boolean created = f.getParentFile().mkdirs();
            if (!created && !f.getParentFile().exists()) {
                LOG.error("Unable to create directory '{}', during extraction of archive contents.",
                        f.getParentFile().getAbsolutePath());
            }
            int count;
            byte data[] = new byte[BUFFER_SIZE];
            FileOutputStream fos = new FileOutputStream(new File(tempDir, entry.getName()), false);
            try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
                while ((count = zipIn.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                }
            }
        }
    }

    return new File(tempDir, StringUtils.removeEnd(archiveName, ".zip")).toURI().toString();
}

From source file:com.streamsets.datacollector.cluster.TestClusterProviderImpl.java

@Test
public void testCopyDirectory() throws Exception {
    File copyTempDir = new File(tempDir, "copy");
    File srcDir = new File(copyTempDir, "somedir");
    File dstDir = new File(copyTempDir, "dst");
    Assert.assertTrue(srcDir.mkdirs());//w  w w .  ja  va  2 s  .  c om
    Assert.assertTrue(dstDir.mkdirs());
    File link1 = new File(copyTempDir, "link1");
    File link2 = new File(copyTempDir, "link2");
    File dir1 = new File(copyTempDir, "dir1");
    File file1 = new File(dir1, "f1");
    File file2 = new File(dir1, "f2");
    Assert.assertTrue(dir1.mkdirs());
    Assert.assertTrue(file1.createNewFile());
    Assert.assertTrue(file2.createNewFile());
    file2.setReadable(false);
    file2.setWritable(false);
    file2.setExecutable(false);
    Files.createSymbolicLink(link1.toPath(), dir1.toPath());
    Files.createSymbolicLink(link2.toPath(), link1.toPath());
    Files.createSymbolicLink(new File(srcDir, "dir1").toPath(), link2.toPath());
    File clone = ClusterProviderImpl.createDirectoryClone(srcDir, srcDir.getName(), dstDir);
    File cloneF1 = new File(new File(clone, "dir1"), "f1");
    Assert.assertTrue(cloneF1.isFile());
}

From source file:org.spoutcraft.client.gui.texturepacks.GuiTexturePacks.java

public void deleteCurrentTexturepack() {
    for (int tries = 0; tries < 3; tries++) {
        try {//from   ww w .jav  a  2 s .c om
            TexturePackBase pack = model.getItem(view.getSelectedRow()).getPack();
            if (pack instanceof TexturePackCustom) {
                TexturePackCustom custom = (TexturePackCustom) pack;
                custom.closeTexturePackFile();
                File d = new File(SpoutClient.getInstance().getTexturePackFolder(), custom.texturePackFileName);
                if (!d.exists()) {
                    d = new File(new File(Minecraft.getAppDir("minecraft"), "texturepacks"),
                            custom.texturePackFileName);
                }
                d.setWritable(true);
                FileUtils.forceDelete(d);
                model.update();

                if (!d.exists()) {
                    break;
                }

                Thread.sleep(25);
            }
        } catch (Exception e) {
        }
    }
}

From source file:org.apache.hadoop.mapred.TestTaskLogsMonitor.java

/**
 * clean-up any stale directories after enabling writable permissions for all
 * attempt-dirs.//  ww  w.ja v a 2  s.c o  m
 * 
 * @throws IOException
 */
@After
public void tearDown() throws IOException {
    File logDir = TaskLog.getUserLogDir();
    for (File attemptDir : logDir.listFiles()) {
        attemptDir.setWritable(true);
        FileUtil.fullyDelete(attemptDir);
    }
}

From source file:com.iontorrent.utils.settings.Config.java

public Config(File userFile, URL initialConfigFile) {

    if (userFile == null) {
        warn("Got no user file:" + userFile);
        //userConfigFile = initialConfigFile
    }/* w w  w .jav  a2 s . c o  m*/
    if (!userFile.exists() || userFile.length() < 10) {
        p("Copy source to target first");
        File parent = userFile.getParentFile();
        if (!parent.exists()) {
            p("Parent " + parent + " does not exist, creating folder");
            boolean ok = parent.mkdirs();
            parent.setExecutable(true);
            parent.setWritable(true);
            if (!parent.exists()) {
                err("Parent folder still does not exist");
                userFile = new File(parent.getParentFile() + "/" + userFile.getName());
                p("Trying " + userFile);
            }
        }
        boolean ok = FileTools.copyUrl(initialConfigFile, userFile);
        if (!ok) {
            err("Was uable to copy " + initialConfigFile + " to " + userFile);
        }
    } else {
        p("Already found user file " + userFile);
    }
    try {
        this.url = userFile.toURI().toURL();
    } catch (MalformedURLException ex) {
        Logger.getLogger(Config.class.getName()).log(Level.SEVERE, null, ex);
    }
    p("Reading XML file from URL:" + url);
    this.setXMLConfig(url);

    init();
}

From source file:io.specto.hoverfly.junit.HoverflyRule.java

private Path extractBinary(final String binaryName) throws IOException, URISyntaxException {
    final URI sourceHoverflyUrl = findResourceOnClasspath(binaryName);
    final Path temporaryHoverflyPath = Files.createTempFile(binaryName, "");
    LOGGER.info("Storing binary in temporary directory " + temporaryHoverflyPath);
    final File temporaryHoverflyFile = temporaryHoverflyPath.toFile();
    FileUtils.copyURLToFile(sourceHoverflyUrl.toURL(), temporaryHoverflyFile);
    if (SystemUtils.IS_OS_WINDOWS) {
        temporaryHoverflyFile.setExecutable(true);
        temporaryHoverflyFile.setReadable(true);
        temporaryHoverflyFile.setWritable(true);
    } else {//from w  w w  . j a  v a  2s . co m
        Files.setPosixFilePermissions(temporaryHoverflyPath, new HashSet<>(asList(OWNER_EXECUTE, OWNER_READ)));
    }

    return temporaryHoverflyPath;
}

From source file:com.buaa.cfs.utils.FileUtil.java

/**
 * Platform independent implementation for {@link File#setWritable(boolean)} File#setWritable does not work as
 * expected on Windows.//from   ww  w . ja  v a  2  s.c om
 *
 * @param f        input file
 * @param writable
 *
 * @return true on success, false otherwise
 */
public static boolean setWritable(File f, boolean writable) {
    if (Shell.WINDOWS) {
        try {
            String permission = writable ? "u+w" : "u-w";
            FileUtil.chmod(f.getCanonicalPath(), permission, false);
            return true;
        } catch (IOException ex) {
            return false;
        }
    } else {
        return f.setWritable(writable);
    }
}