Example usage for java.io File canWrite

List of usage examples for java.io File canWrite

Introduction

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

Prototype

public boolean canWrite() 

Source Link

Document

Tests whether the application can modify the file denoted by this abstract pathname.

Usage

From source file:com.navercorp.pinpoint.bootstrap.AgentDirGenerator.java

private File createDir(String dirPath) {
    logger.debug("create dir:{}", dirPath);

    final File dir = new File(dirPath);
    if (!dir.exists()) {
        boolean mkdir = dir.mkdirs();
        Assert.assertTrue(dir + " create fail", mkdir);
    }/*w w  w  .ja v  a 2s .  c o m*/
    Assert.assertTrue(dirPath + " not a directory", dir.isDirectory());

    Assert.assertTrue(dir.canWrite());

    return dir;
}

From source file:edu.umn.msi.tropix.common.test.Foo.java

public void testTempDirectoryCreator(final TempDirectoryCreator creator) throws Exception {
    final Collection<File> tempDirectories = new LinkedList<File>();
    for (int i = 0; i < 10; i++) {
        final File tempDirectory = creator.getNewTempDirectory();
        assert !tempDirectories.contains(tempDirectory) : "Non unique temp directory created";
        tempDirectories.add(tempDirectory);
        assert tempDirectory.isDirectory() : "Temp directory is not a directory.";
        assert tempDirectory.canWrite() : "Cant write to temp directory.";
        assert tempDirectory.list().length == 0 : "New directory not empty";
    }//from   ww w.ja va 2 s  .  c om
}

From source file:dk.netarkivet.common.distribute.AbstractRemoteFile.java

/** Copy this remote file to the given file.
 * This method will make a fileoutputstream, and use appendTo to write
 * the remote file to this stream./* w w  w .  ja  v a2s  .  c  o m*/
 * @param destFile The file to write the remote file to.
 * @throws ArgumentNotValid on null destFile, or parent to destfile is not
 * a writeable directory, or destfile exists and cannot be overwritten.
 * @throws IOFailure on I/O trouble writing remote file to destination.
 */
public void copyTo(File destFile) {
    ArgumentNotValid.checkNotNull(destFile, "File destFile");
    destFile = destFile.getAbsoluteFile();
    if ((!destFile.isFile() || !destFile.canWrite())
            && (!destFile.getParentFile().isDirectory() || !destFile.getParentFile().canWrite())) {
        throw new ArgumentNotValid(
                "Destfile '" + destFile + "' does not point to a writable file for remote file '" + file + "'");
    }
    try {
        FileOutputStream fos = null;
        int retry = 0;
        boolean success = false;

        // retry if it fails, but always make at least one attempt.
        do {
            try {
                try {
                    fos = new FileOutputStream(destFile);
                    appendTo(fos);
                    success = true;
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                }
            } catch (IOFailure e) {
                if (retry == 0) {
                    log.warn("Could not retrieve the file '" + getName()
                            + "' on first attempt. Will retry up to '" + getNumberOfRetries() + "' times.", e);
                } else {
                    log.warn("Could not retrieve the file '" + getName() + "' on retry number '" + retry
                            + "' of '" + getNumberOfRetries() + "' retries.", e);
                }
            }
            retry++;
            if (!success && retry < getNumberOfRetries()) {
                log.debug("CopyTo attempt #" + retry + " of max " + getNumberOfRetries()
                        + " failed. Will sleep a while before trying to " + "copyTo again.");
                TimeUtils.exponentialBackoffSleep(retry, Calendar.MINUTE);
            }
        } while (!success && retry < getNumberOfRetries());

        // handle case when the retrieval is unsuccessful.
        if (!success) {
            throw new IOFailure("Unable to retrieve the file '" + getName() + "' in '" + getNumberOfRetries()
                    + "' attempts.");
        }
    } catch (Exception e) {
        FileUtils.remove(destFile);
        throw new IOFailure("IO trouble transferring file", e);
    }
}

From source file:interactivespaces.util.io.directorywatcher.SimpleDirectoryWatcher.java

@Override
public synchronized void addDirectory(File directory) {
    if (directory.isDirectory()) {
        if (directory.canRead()) {
            if (directory.canWrite()) {
                if (cleanFirst) {
                    Files.deleteDirectoryContents(directory);
                }//from   w w  w .ja  v  a 2s. c o  m
            }
            directoriesWatched.add(directory);
        } else {
            throw new IllegalArgumentException(String.format("%s is not readable", directory));
        }
    } else if (directory.exists()) {
        // The file exists, but it isn't a directory.
        //
        // This is checked for separately to handle directories added
        // after the watcher starts running.
        throw new IllegalArgumentException(String.format("%s is not a directory", directory));
    } else {
        // Assume the directory will be added at some point
        directoriesWatched.add(directory);
    }
}

From source file:it.geosolutions.geostore.services.rest.BaseAuthenticationTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();

    File securityTempFolder = new File(System.getProperty("java.io.tmpdir"), "apacheds-spring-security");

    int i = 0;/*www.j  a  v  a2s . c  o  m*/
    for (i = 0; i < 10; i++) {
        try {
            if (securityTempFolder.exists() && securityTempFolder.isDirectory()
                    && securityTempFolder.canWrite()) {
                FileDeleteStrategy.FORCE.delete(securityTempFolder);
                FileUtils.forceDelete(securityTempFolder);
            }
        } catch (Exception e) {
            LOGGER.info(i * 10 + "... ");
            Thread.sleep(1000);
            continue;
        }
        break;
    }
    LOGGER.info(100);

    String[] paths = { "classpath*:applicationContext-test.xml" };
    context = new ClassPathXmlApplicationContext(paths);
    LOGGER.info("Built test context: " + context);
}

From source file:org.ow2.clif.jenkins.chart.AbstractChart.java

private File getImageFile(File rootDir) {
    File clifImageDir = new File(rootDir, "clif");
    if (clifImageDir.exists()) {
        if (!clifImageDir.isDirectory()) {
            throw new IllegalStateException(clifImageDir.getAbsolutePath() + " is not a directory");
        }/*from   w  w  w .j  a va 2 s .  co  m*/
        if (!clifImageDir.canWrite()) {
            throw new IllegalStateException(clifImageDir.getAbsolutePath() + " is not writable");
        }
    } else {
        if (!clifImageDir.mkdirs()) {
            throw new IllegalStateException("Impossible to create directory " + clifImageDir.getAbsolutePath());
        }
    }

    return new File(clifImageDir, this.chartId.getId() + ".png");
}

From source file:com.github.FraggedNoob.GitLabTransfer.GitlabRelatedData.java

/**
 * Creates a File for writing the JSON data.  The ".json" extension is added.
 * @param filepath the path/filename prefix
 * @param suffix the data suffix (without extension, e.g. ".json")
 * @return A File ready for writing, or null.
 *///from  w  w w  . j  a v  a  2  s  .  com
protected static File createFileForWriting(String filepath, String dataSuffix) {

    File w = new File(filepath + dataSuffix + ".json");
    if (!w.exists()) {
        try {
            w.createNewFile();
        } catch (IOException e) {
            System.out.printf("Error, can't create file:%s for writing.\n", filepath);
            e.printStackTrace();
            return null;
        }
    }

    if (!w.canWrite()) {
        System.out.printf("Error, file:%s not writable.\n", filepath);
        return null;
    }

    return w;
}

From source file:eu.prestoprime.plugin.dracma.DRACMATasks.java

@WfService(name = "dracma_make_consumer_segment", version = "2.0.0")
public void segment(Map<String, String> sParams, Map<String, String> dParamsString,
        Map<String, File> dParamsFile) throws TaskExecutionFailedException {

    if (!Boolean.parseBoolean(dParamsString.get("isSegmented"))) {

        // retrieve static params
        String DRACMASegmentServer = sParams.get("dracma.segmenter.url");
        String destVolume = sParams.get("dest.path.volume").trim();
        String destFolder = sParams.get("dest.path.folder").trim();

        // retrieve dynamic params
        String dipID = dParamsString.get("dipID");
        String sourceFilePath = dParamsString.get("source.file.path");
        String mimetype = dParamsString.get("source.file.mimetype");
        int startFrame = Integer.parseInt(dParamsString.get("start.frame"));
        int stopFrame = Integer.parseInt(dParamsString.get("stop.frame"));

        String outputFolder = destVolume + File.separator + destFolder;

        try {//from   w  w w.  j av a 2  s. c om
            DIP dip = P4DataManager.getInstance().getDIPByID(dipID);

            // get UMID
            String UMID = null;

            if (mimetype != null) {
                List<String> videoFileList = dip.getAVMaterial(mimetype, "DRACMA");

                if (videoFileList.size() > 0) {
                    UMID = videoFileList.get(0);

                    File targetDir = new File(outputFolder);
                    targetDir.mkdirs();

                    if (!targetDir.canWrite())
                        throw new TaskExecutionFailedException("Unable to write to output dir " + outputFolder);

                    String targetFileName = dipID + "." + startFrame + "." + stopFrame + ".mxf";
                    File targetFile = new File(targetDir, targetFileName);

                    URI segmentServer = new URI(DRACMASegmentServer);
                    DRACMAClient c = new DRACMAClient(segmentServer);

                    c.update(UMID, new File(sourceFilePath));

                    logger.debug("Updated DRACMA " + UMID + " resource location to " + sourceFilePath);
                    logger.debug("Requesting segment to DRACMA...");

                    DRACMASegment segment = new DRACMASegment(UMID, startFrame, stopFrame);
                    URL targetFileURL = c.segment(segment);

                    logger.debug("DRACMA segmented available on " + targetFileURL);
                    logger.debug("Downloadin' DRACMA segment...");

                    HttpClient client = new DefaultHttpClient();
                    HttpUriRequest request = new HttpGet(targetFileURL.toString());
                    HttpResponse response = client.execute(request);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        HttpEntity entity = response.getEntity();

                        InputStream in = entity.getContent();
                        FileOutputStream out = new FileOutputStream(targetFile);

                        byte[] buffer = new byte[4096];
                        int bytesRead;
                        while ((bytesRead = in.read(buffer)) != -1)
                            out.write(buffer, 0, bytesRead);

                        in.close();
                        out.close();

                        dParamsString.put("isSegmented", "true");
                        dParamsString.put("segment.file.path", targetFileName);

                        logger.debug("Consumer copy available at: " + targetFile.getAbsolutePath());
                    } else {
                        logger.debug(
                                "DRACMA response with status code " + response.getStatusLine().getStatusCode());
                    }
                }
            }
        } catch (DataException e) {
            e.printStackTrace();
            throw new TaskExecutionFailedException("Unable to retrieve DIP with id: " + dipID);
        } catch (IPException | FileNotFoundException e) {
            e.printStackTrace();
            throw new TaskExecutionFailedException("Unable to retrieve MQ file");
        } catch (IOException e) {
            e.printStackTrace();
            throw new TaskExecutionFailedException("Unable to create consumer copy");
        } catch (DRACMAException e) {
            e.printStackTrace();
            throw new TaskExecutionFailedException("Unable to execute segmentation with DRACMA...");
        } catch (URISyntaxException e) {
            e.printStackTrace();
            throw new TaskExecutionFailedException("Bad DRACMA segmenter URL in wfDescriptor...");
        }
    }
}

From source file:com.mirth.connect.connectors.doc.DocumentDispatcher.java

private File createFile(String filename) throws IOException {
    File file = new File(filename);
    if (!file.canWrite()) {
        String dirName = file.getPath();
        int i = dirName.lastIndexOf(File.separator);
        if (i > -1) {
            dirName = dirName.substring(0, i);
            File dir = new File(dirName);
            dir.mkdirs();/*from w w w  . ja v  a2  s  .  c o m*/
        }
        file.createNewFile();
    }
    return file;
}

From source file:com.adaptris.core.fs.FsConsumerImpl.java

/**
 * Could we read and process this file.//  w  w  w  .j av a 2  s  .  c  o  m
 *
 * @param f the file.
 * @return true, if the file is a file, can be read, and can be written to (for renaming purposes).
 */
protected boolean isFileAccessible(File f) {
    return f.isFile() && f.canRead() && f.canWrite();
}