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:ee.pri.rl.blog.web.page.setting.SettingValidator.java

private void validateUploadPath(IValidatable<String> validatable) {
    String value = validatable.getValue();
    File directory = new File(value);
    if (!directory.exists()) {
        error(validatable, "Directory must exist");
    } else if (!directory.canWrite()) {
        error(validatable, "Directory must be writable");
    }/*  w w w . j ava  2  s .c  om*/
}

From source file:com.thoughtworks.go.util.validators.FileValidator.java

public Validation validate(Validation validation) {
    File file = new File(destDir, fileName);
    if (!shouldReplace && file.exists()) {
        if (file.canWrite() && file.canRead()) {
            return Validation.SUCCESS;
        } else {//  ww w  .  j a  va  2 s . c o  m
            String message = format("File {0} is not readable or writeable.", file.getAbsolutePath());
            return validation.addError(new RuntimeException(message));
        }
    } else {
        // Pull out the file from the class path
        InputStream input = this.getClass().getResourceAsStream(srcDir + "/" + fileName);
        if (input == null) {
            String message = format("Resource {0}/{1} does not exist in the classpath", srcDir, fileName);
            return validation.addError(new RuntimeException(message));
        } else {
            FileOutputStream output = null;
            try {
                // Make sure the dir exists
                file.getParentFile().mkdirs();
                output = new FileOutputStream(file);
                IOUtils.copy(input, output);
            } catch (Exception e) {
                return handleExceptionDuringFileHandling(validation, e);
            } finally {
                try {
                    input.close();
                    if (output != null) {
                        output.flush();
                        output.close();
                    }
                } catch (Exception e) {
                    return handleExceptionDuringFileHandling(validation, e);
                }
            }
        }
    }
    return Validation.SUCCESS;
}

From source file:com.genericworkflownodes.knime.nodes.io.outputfiles.OutputFilesNodeModel.java

@Override
protected PortObject[] execute(PortObject[] inObjects, ExecutionContext exec) throws Exception {
    IURIPortObject obj = (IURIPortObject) inObjects[0];
    List<URIContent> uris = obj.getURIContents();

    if (uris.size() == 0) {
        throw new Exception("There were no URIs in the supplied IURIPortObject");
    }//w  w w  . j ava2s  . c om

    int idx = 1;
    for (URIContent uri : uris) {
        File in = new File(uri.getURI());
        if (!in.canRead()) {
            throw new Exception("Cannot read file to export: " + in.getAbsolutePath());
        }

        String outfilename = insertIndex(m_filename.getStringValue(), obj.getSpec().getFileExtensions().get(0),
                idx++);
        File out = new File(outfilename);

        if (out.exists() && !out.canWrite()) {
            throw new Exception("Cannot write to file: " + out.getAbsolutePath());
        } else if (!out.getParentFile().canWrite()) {
            throw new Exception(
                    "Cannot write to containing directoy: " + out.getParentFile().getAbsolutePath());
        }

        FileUtils.copyFile(in, out);
    }
    return null;
}

From source file:hu.tvdr.serialport.serialport.java

public void SerialPortCall(File device, int baudrate, int flags) throws SecurityException, IOException {

    /* Check access permission */
    if (!device.canRead() || !device.canWrite()) {
        try {/* w ww.ja  va2 s .c o  m*/
            /* Missing read/write permission, trying to chmod the file */
            Process su;
            su = Runtime.getRuntime().exec("/system/bin/su");
            String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
            su.getOutputStream().write(cmd.getBytes());
            if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite()) {
                throw new SecurityException();
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new SecurityException();
        }
    }

    mFd = open(device.getAbsolutePath(), baudrate, flags);
    if (mFd == null) {
        Log.e(TAG, "native open returns null");
        throw new IOException();
    }
    mFileInputStream = new FileInputStream(mFd);
    mFileOutputStream = new FileOutputStream(mFd);
}

From source file:it.geosolutions.geobatch.settings.GBSettingsDAOXStreamImpl.java

public boolean save(GBSettings settings) {
    String id = settings.getId();
    if (id == null)
        throw new NullPointerException("Id is null");

    try {/*from  w ww . j a va2s.co  m*/
        if (!settingsDir.exists()) {
            if (!settingsDir.mkdirs()) {
                LOGGER.warn("Unable to build settings dir: " + settingsDir.getAbsolutePath());
                return false;
            }
        }
        final File outFile = new File(settingsDir, id + ".xml");

        if (!(outFile.createNewFile() && outFile.canWrite())) {
            LOGGER.warn("Unwritable file " + outFile);
            return false;
        } else if (outFile.isDirectory()) {
            LOGGER.warn("Output file " + outFile + " is a dir");
            return false;
        } else {
            XStream xstream = new XStream();
            alias.setAliases(xstream);
            String xml = xstream.toXML(settings);
            FileUtils.write(outFile, xml);

            if (LOGGER.isInfoEnabled())
                LOGGER.info("Stored settings " + id);
            return true;
        }
    } catch (IOException e) {
        LOGGER.error("Unable to store settings with id:" + id, e);
        return false;
    }
}

From source file:es.upv.grycap.coreutils.fiber.test.FetchCancellationTest.java

@Test
public void testFetch() throws Exception {
    // create fetcher
    final HttpDataFetcher fetcher = new HttpDataFetcher(2);
    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());

    // submit request and cancel
    final ExecutorService executorService = Executors.newFixedThreadPool(2);
    final Future<Map<String, FetchStatus>> future = executorService
            .submit(new Callable<Map<String, FetchStatus>>() {
                @Override/* ww  w . j  a  v  a 2  s . c  o  m*/
                public Map<String, FetchStatus> call() throws Exception {
                    return AsyncCompletionStage
                            .get(fetcher.fetchToDir(new URL(MOCK_SERVER_BASE_URL + "/fetch/long-waiting"),
                                    ImmutableList.of("1"), outDir), 120000l, TimeUnit.SECONDS);
                }
            });
    assertThat("Request was cancelled", future.cancel(true));
    assertThat("File does not exist", not(new File(outDir, "1").exists()));
}

From source file:de.awtools.basic.file.AWToolsFileUtilsTest.java

@Test
public void testCreateFilePath() {
    AWToolsFileUtils.createFilePath(TMP_DIR, TEST_FILE);
    File dir = new File(TMP_DIR + TEST_DIR);
    assertThat(dir).isDirectory();//w ww  .  j  a  v  a2s.c om
    assertThat(dir.canRead()).isTrue();
    assertThat(dir.canWrite()).isTrue();
}

From source file:hu.bme.mit.sette.common.validator.FileValidator.java

/**
 * Sets whether the file should be writable or not.
 *
 * @param isWritable//  ww  w  .  j a  v  a 2  s.co  m
 *            true if the file should be writable, false if it should not be
 * @return this object
 */
public FileValidator writable(final boolean isWritable) {
    if (getSubject() != null) {
        File file = getSubject();

        if (isWritable ^ file.canWrite()) {
            String must;

            if (isWritable) {
                must = "must";
            } else {
                must = "must not";
            }

            this.addException(String.format("The file %s be writable", must));
        }
    }

    return this;
}

From source file:com.sangupta.clitools.file.RandomFile.java

public void generate() {
    if (AssertUtils.isEmpty(this.size)) {
        System.out.println("Size of file to be generated must be specified.");
        return;//from  w  ww .  j  a  v a 2s  .  c o  m
    }

    if (AssertUtils.isEmpty(this.fileName)) {
        System.out.println("Filename of file to be generated must be specified.");
        return;
    }

    int bytes = (int) ReadableUtils.parseByteCount(this.size);
    if (bytes == 0) {
        System.out.println("Cannot generate a random file of size zero, use touch for the same");
        return;
    }

    File file = new File(this.fileName);
    if (file.exists()) {
        if (file.isFile()) {
            if (!file.canWrite()) {
                System.out.println("File already exists... but no permissions to write to it.");
                return;
            }

            // display warning message
            System.out.println("File already exists... it is being overwritten!");
        }
    }

    final long start = System.currentTimeMillis();
    try {
        createFile(bytes, file);
    } finally {
        long end = System.currentTimeMillis();
        System.out.println("File written in " + ReadableUtils.getReadableTimeDuration(end - start));
    }
}

From source file:net.doubledoordev.backend.server.FileManager.java

public String getIcon(File file) {
    if (!file.canWrite())
        return "lock";
    if (file.isDirectory())
        return "folder";
    switch (getExtension(file)) {
    case "html":
    case "json":
    case "dat":
    case "dat_old":
    case "properties":
        return "file-code-o";

    case "txt":
        return "file-text-o";

    case "jar":
    case "zip":
    case "disabled":
        return "file-archive-o";

    case "jpg":
    case "png":
        return "file-image-o";

    default://from   w  w w  .  j a v  a2s.  c o  m
        return "file-o";
    }
}