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.tecapro.inventory.common.util.FileLocalUtil.java

/**
 * check file Writable//from  w  w w.j  a  v  a2s  . c  o  m
 */
public boolean isWritable(String name, int index) {
    if (name == null) {
        return true;
    }
    File file = new File(baseDir, name);
    return !file.exists() || file.canWrite();
}

From source file:cz.cas.lib.proarc.common.config.AppConfigurationTest.java

@Test
public void testGetAllUserHome() throws Exception {
    AppConfiguration config = factory.create(new HashMap<String, String>() {
        {// w w w  .  j  av a 2 s .  co m
            put(AppConfiguration.PROPERTY_APP_HOME, confHome.toString());
        }
    });
    assertNotNull(config);
    File expectedUserFolder = new File(confHome, "users");
    assertEquals(expectedUserFolder, config.getDefaultUsersHome());
    assertTrue(expectedUserFolder.exists());
    assertTrue(expectedUserFolder.isDirectory());
    assertTrue(expectedUserFolder.canRead());
    assertTrue(expectedUserFolder.canWrite());
}

From source file:com.isencia.passerelle.runtime.repos.impl.filesystem.FlowRepositoryServiceImpl.java

@Override
public FlowHandle update(FlowHandle handle, Flow updatedFlow, boolean activate) throws EntryNotFoundException {
    String flowCode = handle.getCode();
    File flowRootFolder = new File(rootFolder, flowCode);
    if (!flowRootFolder.isDirectory()) {
        throw new EntryNotFoundException(ErrorCode.FLOW_SAVING_ERROR_FUNC, "Flow code unknown " + flowCode,
                null);//from w ww  . ja v  a  2s .c  o  m
    } else {
        FlowHandle flowHandle = null;
        ThreeDigitVersionSpecification vSpec = ((ThreeDigitVersionSpecification) handle.getVersion())
                .increaseMinor();
        File versionFolder = new File(flowRootFolder, vSpec.toString());
        while (versionFolder.exists()) {
            vSpec = vSpec.increaseMinor();
            versionFolder = new File(flowRootFolder, vSpec.toString());
        }
        versionFolder.mkdirs();
        File destinationFile = new File(versionFolder, updatedFlow.getName() + ".moml");
        if ((!destinationFile.exists() || destinationFile.canWrite())) {
            BufferedWriter outputWriter = null;
            try {
                outputWriter = new BufferedWriter(new FileWriter(destinationFile));
                updatedFlow.exportMoML(outputWriter);
                flowHandle = new FlowHandleImpl(flowCode, destinationFile, vSpec);
                writeMetaData(flowCode, VERSION_MOSTRECENT, vSpec.toString());
                if (activate) {
                    activateFlowRevision(flowHandle);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (outputWriter != null) {
                    try {
                        outputWriter.flush();
                        outputWriter.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
            return flowHandle;
        } else {
            throw new RuntimeException(new IOException("File not writable " + destinationFile));
        }
    }
}

From source file:edu.isi.wings.portal.controllers.ComponentController.java

public boolean saveComponentFile(String cid, String path, String data) {
    try {/*from   ww  w .  j av a 2s .co m*/
        String loc = cc.getComponentLocation(cid);
        if (loc != null && path != null) {
            loc = loc + "/" + path;
            File f = new File(loc);
            if (f.isFile() && f.canWrite()) {
                FileUtils.writeStringToFile(f, data);
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cc.end();
        dc.end();
        prov.end();
    }
    return false;
}

From source file:it.geosolutions.geobatch.flow.file.FileBasedFlowManager.java

public static File initTempDir(FileBasedFlowConfiguration flowConfiguration, File geoBatchTempDir)
        throws FileNotFoundException {

    File ret = null;

    File overrideTempDir = flowConfiguration.getOverrideTempDir();
    if (overrideTempDir != null) {
        ret = overrideTempDir;/*from  ww  w.  j  a  va  2s  .com*/
        if (!ret.isAbsolute())
            throw new IllegalStateException(
                    "Override temp dir must be an absolute path (" + overrideTempDir + ")");
    } else {

        String flowId = flowConfiguration.getId();
        ret = new File(geoBatchTempDir, flowId);

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("FlowBaseTempDir = " + ret);
    }

    if ((!ret.mkdir() && !ret.exists()) || !ret.canWrite())
        throw new IllegalStateException("Can't write temp dir (" + ret + ")");

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Flow: " + flowConfiguration.getId() + " - temp dir is now set to -> " + ret);
    }
    return ret;
}

From source file:com.symbian.driver.remoting.cmdline.ResultsCmdLine.java

/**
 * Implements additional constraints on switches.
 * /*from   w w w. j a v  a2  s .  c  o m*/
 * @param aCommandLine
 *            {@inheritDoc}
 */
public void checkAdditionalConstraints(final CommandLine aCommandLine) {
    if (aCommandLine.hasOption("j")) {
        if (Integer.parseInt(aCommandLine.getOptionValue("j")) < 1) {
            LOGGER.severe("Job ID must be a positive number");
        }
    }
    if (aCommandLine.hasOption("c")) {
        File resultsPath = new File(aCommandLine.getOptionValue("c"));
        if (!resultsPath.exists()) {
            try {
                resultsPath.mkdirs();
            } catch (SecurityException se) {
                LOGGER.severe(
                        "Can not create " + resultsPath + ". Please check permissions." + se.getMessage());
            }
        } else if (!resultsPath.isDirectory() || !resultsPath.canWrite()) {
            LOGGER.severe("Results path " + resultsPath + " is not a valid directory.");
        }
    }
}

From source file:de.eimb.testlink.synchronize.citrus.mvn.plugin.CreateTestCasesFromTestLink.java

/**
 * Add TestLink variables to the newly created CITRUS test case. Add variables after the
 * description tag, as this is required by the XSD definition of CITRUS. In case this changes,
 * make sure to adapt it here as well.//  ww w  .  j  ava 2 s.  c  om
 *
 * @param bean
 *            CITRUS test case bean.
 */
private void addVariables(final CitrusBean bean) {

    final File file = new File(bean.getTestFileName());

    if (!file.exists() || !file.canWrite() || (file.length() <= 0)) {

        // there is no file, return
        return;
    }

    BufferedReader reader = null;
    final StringBuilder builder = new StringBuilder();

    try {

        reader = new BufferedReader(new FileReader(file));

        String line;

        while ((line = reader.readLine()) != null) {

            if (line.contains("</description>")) {

                // write description line
                builder.append(line);
                builder.append("\n");

                // start to write CITRUS TestLink variables
                // the indention is some experimental value
                builder.append(CitrusUtils.buildVariables(bean, "        "));
            } else if (line.contains("variable")) {

                // ignore lines containing variable definitions
                // removing them by this
            } else {

                builder.append(line);
                builder.append("\n");
            }
        }
    } catch (final Exception ex) {

        this.getLog().error("Error while working on file [ " + file.getAbsolutePath() + " ]", ex);
    } finally {

        FileUtils.close(reader);
    }

    BufferedWriter writer = null;

    try {

        writer = new BufferedWriter(new FileWriter(file));
        writer.write(builder.toString());
    } catch (final Exception ex) {

        this.getLog().error("Error trying to write to file [ " + file.getAbsolutePath() + " ]", ex);
    } finally {

        FileUtils.close(writer);
    }
}

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

@Override
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 '" + toString() + "'");
    }//from w ww  .j  ava2s. c o  m
    if (log.isDebugEnabled()) {
        log.debug("Writing {} to {}", toString(), destFile.getAbsolutePath());
    }
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(destFile);
        appendTo(fos);
    } catch (Exception e) {
        FileUtils.remove(destFile);
        throw new IOFailure("IO trouble transferring file", e);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:com.blackducksoftware.tools.vuln_collector.VCProcessor.java

/**
 * Grabs the user specified location for reports
 * //from  w w w  . j av a 2  s.  c  om
 * @return
 * @throws CommonFrameworkException
 */
private File getReportLocation() throws CommonFrameworkException {
    String reportLocation = vcConfigManager.getReportLocation();
    if (reportLocation == null) {
        throw new CommonFrameworkException(vcConfigManager, "Report location not specified");
    }

    File f = new File(reportLocation);
    if (!f.exists()) {
        throw new CommonFrameworkException(vcConfigManager,
                String.format("Report location {%s} does not exist", reportLocation));
    }

    if (!f.canWrite()) {
        throw new CommonFrameworkException(vcConfigManager,
                String.format("Report location {%s} has no write access", reportLocation));
    }

    return f;
}

From source file:com.adobe.communities.ugc.migration.legacyProfileExport.MessagesExportServlet.java

@Override
protected void doGet(final SlingHttpServletRequest request, final SlingHttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/octet-stream");
    final String headerKey = "Content-Disposition";
    final String headerValue = "attachment; filename=\"export.zip\"";
    response.setHeader(headerKey, headerValue);
    File outFile = null;
    exportedIds = new HashMap<String, Boolean>();
    messagesForExport = new HashMap<String, JSONObject>();
    try {/*from w ww  .j av a2 s  .  c o m*/
        outFile = File.createTempFile(UUID.randomUUID().toString(), ".zip");
        if (!outFile.canWrite()) {
            throw new ServletException("Cannot write to specified output file");
        }
        FileOutputStream fos = new FileOutputStream(outFile);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        zip = new ZipOutputStream(bos);
        responseWriter = new OutputStreamWriter(zip);
        OutputStream outStream = null;
        InputStream inStream = null;
        try {

            int start = 0;
            int increment = 100;
            try {
                do {
                    Iterable<Message> messages = messagingService.search(request.getResourceResolver(),
                            new MessageFilter(), start, start + increment);
                    if (messages.iterator().hasNext()) {
                        exportMessagesBatch(messages);
                    } else {
                        break;
                    }
                    start += increment;
                } while (true);
            } catch (final RepositoryException e) {
                // do nothing for now
            }
            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 (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();
        }
    }
}