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:es.upv.grycap.coreutils.fiber.test.FetchTest.java

@Test
public void testFetch() throws Exception {
    // create fetcher
    final HttpDataFetcher fetcher = new HttpDataFetcher(concurrencyLevel);
    assertThat("Fetcher was created", fetcher, notNullValue());

    // create output folder
    final File outDir = tmpFolder.newFolder(randomAlphanumeric(12));
    assertThat("Output dir was created", outDir, notNullValue());
    assertThat("Output dir is writable", outDir.canWrite());

    // create test dataset
    @SuppressWarnings("unchecked")
    final List<String> ids = union(validIds, invalidIds);
    final URL url = new URL(MOCK_SERVER_BASE_URL + path);

    // fetch from server
    Map<String, FetchStatus> results = null;
    if (useFiber) {
        results = AsyncCompletionStage.get(fetcher.fetchToDir(url, queryParam, ids, "file-", ".tmp", outDir),
                30l, TimeUnit.SECONDS);
    } else {//ww  w. j a  v  a 2s.  c  o  m
        final FecthFuture toBeCompleted = fetcher.fetchToDir(url, queryParam, ids, null, null, outDir);
        assertThat("Fetch task was created", toBeCompleted, notNullValue());
        results = toBeCompleted.get(30l, TimeUnit.SECONDS);
    }
    assertThat("Results are available", results, notNullValue());
    assertThat("Result count coincides with expected", results.size(), equalTo(ids.size()));
    assertThat("Ids coincides with expected", results.keySet(), hasItems(ids.toArray(new String[ids.size()])));
    pw.println(" >> Results: " + results);
    if (!validIds.isEmpty()) {
        assertThat("Status coincides with expected", results.values(), allOf(hasItem(FetchStatus.COMPLETED),
                not(hasItems(FetchStatus.PENDING, FetchStatus.CANCELLED))));
    }
    if (!invalidIds.isEmpty()) {
        assertThat("Status coincides with expected", results.values(),
                allOf(hasItem(FetchStatus.FAILED), not(hasItems(FetchStatus.PENDING, FetchStatus.CANCELLED))));
    }

    // check files in the output directory
    for (final String id : validIds) {
        final File outFile = new File(outDir,
                useFiber ? new StringBuilder("file-").append(id).append(".tmp").toString() : id);
        assertThat("Output file was created", outDir, notNullValue());
        assertThat("Output file file exists and is redable", outFile.canRead(), equalTo(true));
        assertThat("Output file file is not empty", outFile.length(), greaterThan(0l));
        if (path.contains("xml")) {
            validateXml(outFile, id);
        } else if (path.contains("json")) {
            validateJson(outFile, id);
        }
    }
}

From source file:marytts.util.io.FileUtils.java

public static void copy(String sourceFile, String destinationFile) throws IOException {
    File fromFile = new File(sourceFile);
    File toFile = new File(destinationFile);

    if (!fromFile.exists()) {
        throw new IOException("FileCopy: " + "no such source file: " + sourceFile);
    }/*  ww w . j av a  2  s .  com*/
    if (!fromFile.isFile()) {
        throw new IOException("FileCopy: " + "can't copy directory: " + sourceFile);
    }
    if (!fromFile.canRead()) {
        throw new IOException("FileCopy: " + "source file is unreadable: " + sourceFile);
    }

    if (toFile.isDirectory()) {
        toFile = new File(toFile, fromFile.getName());
    }

    if (toFile.exists()) {
        if (!toFile.canWrite()) {
            throw new IOException("FileCopy: " + "destination file cannot be written: " + destinationFile);
        }
    }

    String parent = toFile.getParent();
    if (parent == null) {
        parent = System.getProperty("user.dir");
    }
    File dir = new File(parent);
    if (!dir.exists()) {
        throw new IOException("FileCopy: " + "destination directory doesn't exist: " + parent);
    }
    if (dir.isFile()) {
        throw new IOException("FileCopy: " + "destination is not a directory: " + parent);
    }
    if (!dir.canWrite()) {
        throw new IOException("FileCopy: " + "destination directory is unwriteable: " + parent);
    }

    FileInputStream from = null;
    FileOutputStream to = null;
    try {
        from = new FileInputStream(fromFile);
        to = new FileOutputStream(toFile);
        byte[] buffer = new byte[4096];
        int bytesRead;

        while ((bytesRead = from.read(buffer)) != -1) {
            to.write(buffer, 0, bytesRead); // write
        }
    } finally {
        close(from, to);
    }
}

From source file:io.spotnext.maven.mojo.TransformTypesMojo.java

@SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "false positive")
protected void logError(Throwable cause) {
    final String tempFolder = System.getProperty("java.io.tmpdir");
    final Path logFilePath = Paths.get(tempFolder, "spot-transform.types.log");
    final File logFile = logFilePath.toFile();

    if (logFile.canWrite()) {
        FileWriter writer = null;
        try {/*from  w ww .ja  va  2s .  co m*/
            writer = new FileWriter(logFile);
            writer.write(cause.getMessage());
            writer.write(ExceptionUtils.getStackTrace(cause));
        } catch (Exception e) {
            getLog().error("Can't log to separete error log file " + logFilePath.toString());
        } finally {
            CloseUtil.closeQuietly(writer);
        }
    }
}

From source file:edu.ur.ir.file.DefaultTemporaryFileCreator.java

/**
 * Creates a temporary file and set the file to be deleted on exit.
 * // w ww  . j  a  v  a  2 s .c  o  m
 * @see edu.ur.ir.file.TemporaryFileCreator#createTemporaryFile(java.lang.String)
 */
public File createTemporaryFile(String extension) throws IOException {
    File tempDir = new File(temporaryDirectory);

    if (!tempDir.exists()) {
        FileUtils.forceMkdir(tempDir);
    }

    if (!tempDir.isDirectory()) {
        throw new RuntimeException("Temp directory is not a directory " + tempDir.getAbsolutePath());
    }

    if (!tempDir.canWrite()) {
        throw new RuntimeException("Could not write to directory " + tempDir.getAbsolutePath());
    }

    if (!tempDir.canRead()) {
        throw new RuntimeException("Could not read temp directory " + tempDir.getAbsolutePath());
    }
    File f = File.createTempFile("ur-temp", extension, tempDir);
    f.deleteOnExit();
    return f;
}

From source file:com.fusesource.forge.jmstest.executor.BenchmarkValueRecorder.java

private boolean checkDir(File dir) {
    if (dir.exists()) {
        if (!dir.isDirectory()) {
            log().error(dir.getAbsolutePath() + " is not a directory.");
            return false;
        }/*from   w w w .j av a2 s  .  c  om*/
        if (!dir.canWrite()) {
            log().error(dir.getAbsolutePath() + " is not writable.");
            return false;
        }
    } else {
        dir.mkdirs();
    }
    return true;
}

From source file:flexflux.analyses.result.ParetoAnalysisResult.java

public void writeToFile(String path) {

    File dir = new File(path);
    if (!dir.mkdirs()) {
        System.err.println("Error : result directory was not created");
        if (!dir.canWrite()) {
            System.err.println("FlexFlux cannot write in directory " + dir);
        }//from w w w. j  a va2s . co m
    }

    // 1D results
    PrintWriter out;
    try {
        out = new PrintWriter(new File(path + "/1D.txt"));

        for (Objective obj : oneDResults.keySet()) {

            out.println(obj.getName() + "\n");

            for (double val : oneDResults.get(obj)) {

                out.println(val);
            }

            out.println();
        }

        out.close();

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // 2Dresults

    int i = 1;
    for (PP2DResult res : twoDResults.keySet()) {
        res.writeToFile(path + "/2D_" + i + ".txt");
        i++;
    }

    // 3D results

    i = 1;
    for (PP3DResult res : threeDResults.keySet()) {
        res.writeToFile(path + "/3D_" + i + ".txt");
        i++;
    }

}

From source file:com.garyclayburg.persistence.config.EmbeddedMongoConfig.java

/**
 * This is for a relset of db's//  w w w.  ja v a  2  s.  com
 */

//        return new MongoClient(new ArrayList<ServerAddress>() {{
//            add(new ServerAddress("127.0.0.1",27017));
//            add(new ServerAddress("127.0.0.1",27027));
//            add(new ServerAddress("127.0.0.1",27037));
//        }});

//    }
@Bean
@Override
public Mongo mongo() throws Exception {

    log.info("configuring embedded mongo");
    //Files that could be left over after a previous execution was (rudely) killed with kill -9

    try {
        DeletionFileVisitor.deletePath(Paths.get(System.getProperty("java.io.tmpdir")), "embedmongo-db-*");
        DeletionFileVisitor.deletePath(Paths.get(System.getProperty("java.io.tmpdir")), "extract-*-mongod*");
    } catch (IOException e) {
        log.warn(
                "could not delete temporary files from embedded mongod process.  Try manually stopping or killing mongod.exe process first.");
    }

    //        RuntimeConfig config = new RuntimeConfig();
    //        config.setExecutableNaming(new UserTempNaming());

    //        MongodStarter starter = MongodStarter.getInstance(config);

    //        MongodExecutable mongoExecutable = starter.prepare(new MongodConfig(Version.V2_2_0,MONGO_TEST_PORT,false));
    //        mongoExecutable.start();

    File storeFile = new File(System.getProperty("user.home"));
    IDirectory artifactStorePath;
    if (storeFile.exists() && storeFile.isDirectory() && storeFile.canWrite()) {
        artifactStorePath = new FixedPath(System.getProperty("user.home") + "/.embeddedmongo");
    } else {
        //use java tmp dir instead of the default user.home - cloudbees cannot write to user.home
        artifactStorePath = new FixedPath(System.getProperty("java.io.tmpdir") + "/.embeddedmongo");
    }
    ITempNaming executableNaming = new UUIDTempNaming();
    Command command = Command.MongoD;
    IRuntimeConfig runtimeConfig;

    if (!mongoDownloadServer.equals("none")) {
        log.debug("using custom download server: " + mongoDownloadServer);
        runtimeConfig = new RuntimeConfigBuilder().defaults(command)
                .artifactStore(new ArtifactStoreBuilder().defaults(command)
                        .download(new DownloadConfigBuilder().defaultsForCommand(command)
                                .downloadPath(mongoDownloadServer).artifactStorePath(artifactStorePath))
                        .executableNaming(executableNaming))
                .build();
    } else {
        log.debug("using standard download server: " + mongoDownloadServer);
        runtimeConfig = new RuntimeConfigBuilder().defaults(command)
                .artifactStore(new ArtifactStoreBuilder().defaults(command)
                        .download(new DownloadConfigBuilder().defaultsForCommand(command)
                                .artifactStorePath(artifactStorePath))
                        .executableNaming(executableNaming))
                .build();
    }
    MongodStarter runtime = MongodStarter.getInstance(runtimeConfig);
    MongodExecutable mongodExe = runtime.prepare(new MongodConfigBuilder().version(Version.Main.PRODUCTION)
            .timeout(new Timeout(60000)).net(new Net(MONGO_TEST_PORT, Network.localhostIsIPv6())).build());
    mongodExe.start();

    mongo = new MongoClient(LOCALHOST, MONGO_TEST_PORT);
    mongo.getDB(DB_NAME);

    return new MongoClient(new ArrayList<ServerAddress>() {
        {
            add(new ServerAddress(LOCALHOST, MONGO_TEST_PORT));
        }
    });
}

From source file:com.github.rnewson.couchdb.lucene.Config.java

public final File getDir() throws IOException {
    final File dir = new File(this.configuration.getString(LUCENE_DIR, DEFAULT_DIR));
    if (!dir.exists() && !dir.mkdir()) {
        throw new IOException("Could not create " + dir.getCanonicalPath());
    }/*from  w w  w.j a v a  2 s  . com*/
    if (!dir.canRead()) {
        throw new IOException(dir + " is not readable.");
    }
    if (!dir.canWrite()) {
        throw new IOException(dir + " is not writable.");
    }
    LOG.info("Index output goes to: " + dir.getCanonicalPath());
    return dir;
}

From source file:com.naryx.tagfusion.cfm.engine.cfEngine.java

public synchronized static void writeXmlFile(xmlCFML newXmlCFML, boolean notifyListeners)
        throws cfmRunTimeException {

    if (thisInstance.bRemoteOpenBDXML) {
        log("Attempted to update a remote bluedragon.xml; operation failed");
        return;/*from  w  w  w .  j a  va2 s . c o  m*/
    }

    File xmlFileName = getXmlFileName();

    if ((xmlFileName != null) && (xmlFileName.canWrite())) {
        // delete the oldest (10th) backup; increment the numbers of the remaining backups
        for (int backupNo = 10; backupNo > 0; backupNo--) {
            File backupFile = new File(xmlFileName + ".bak." + backupNo);
            if (backupFile.exists()) {
                if (backupNo == 10) {
                    backupFile.delete();
                } else {
                    backupFile.renameTo(new File(xmlFileName + ".bak." + (backupNo + 1)));
                }
            }
        }

        // clean up older backup files
        for (int backupNo = 11; true; backupNo++) {
            File backupFile = new File(xmlFileName + ".bak." + backupNo);
            if (backupFile.exists()) {
                backupFile.delete();
            } else {
                break;
            }
        }

        // write back out the xml file to the file, saving the old one
        File xmlFile = xmlFileName;
        File newFile = new File(xmlFileName + ".bak.1");

        // Put in the last updated
        newXmlCFML.setData("server.system.lastupdated",
                com.nary.util.Date.formatDate(System.currentTimeMillis(), "dd/MMM/yyyy HH:mm.ss", Locale.US));
        newXmlCFML.setData("server.system.lastfile", newFile.toString());

        // Rename the file
        xmlFile.renameTo(newFile);

        try {
            newXmlCFML.writeTo(xmlFile);
        } catch (IOException e) {
            cfCatchData catchData = new cfCatchData();
            catchData.setMessage("failed to write configuration file, " + e.toString());
            throw new cfmRunTimeException(catchData);
        }
    } else {
        // NOTE: this will happen with BD J2EE when it is running in a WAR file,
        // or when the bluedragon.xml
        // file is marked read-only, or when something goes seriously wrong at BD
        // init time.
        cfCatchData catchData = new cfCatchData();
        catchData.setMessage("failed to write configuration file");
        throw new cfmRunTimeException(catchData);
    }

    if (notifyListeners) {
        notifyAllListenersAdmin(newXmlCFML);
    }
}

From source file:com.adobe.communities.ugc.migration.export.GenericExportServlet.java

@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {

    if (!request.getRequestParameterMap().containsKey("path")) {
        throw new ServletException("No path specified for export. Exiting.");
    }/*from w  w w  . j  a v  a 2  s  .c  om*/
    final String path = StringUtils.stripEnd(request.getRequestParameter("path").getString(), "/");
    final Resource resource = request.getResourceResolver().getResource(path);
    if (resource == null) {
        throw new ServletException("Could not find a valid resource for export");
    }
    File outFile = null;
    try {
        outFile = File.createTempFile(UUID.randomUUID().toString(), ".zip");
        if (!outFile.canWrite()) {
            throw new ServletException("Cannot write to specified output file");
        }
        response.setContentType("application/octet-stream");
        final String headerKey = "Content-Disposition";
        final String headerValue = "attachment; filename=\"export.zip\"";
        response.setHeader(headerKey, headerValue);

        FileOutputStream fos = new FileOutputStream(outFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        zip = new ZipOutputStream(bos);
        OutputStream outStream = null;
        InputStream inStream = null;
        try {
            exportContent(resource, path);
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            // obtains response's output stream
            outStream = response.getOutputStream();
            inStream = new FileInputStream(outFile);
            // copy from file to output
            IOUtils.copy(inStream, outStream);
        } catch (final IOException e) {
            throw new ServletException(e);
        } catch (final Exception e) {
            throw new ServletException(e);
        } finally {
            IOUtils.closeQuietly(zip);
            IOUtils.closeQuietly(bos);
            IOUtils.closeQuietly(fos);
            IOUtils.closeQuietly(inStream);
            IOUtils.closeQuietly(outStream);
        }
    } finally {
        if (outFile != null) {
            outFile.delete();
        }
    }
}