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.google.testing.pogen.GenerateCommand.java

/**
 * Parses the specified template file and generates a modified template file and skeleton test
 * code.//from w w  w.j  av  a  2 s  .  c om
 * 
 * @param templateFile the template file to be modified
 * @param rootInputDir the root input directory of template files
 * @param codeOutDir the output directory of skeleton test code
 * @param parser the parser to parse template files
 * @param updater the updater to update template files
 * @param generator the generator to generate skeleton test code
 * @throws IOException if errors occur in reading and writing files
 * @throws TemplateParseException if the specified template is in bad format
 * @throws PageObjectUpdateException if the existing test code doesn't have generated code
 */
private void parseAndGenerate(File templateFile, File rootInputDir, File codeOutDir, TemplateParser parser,
        TemplateUpdater updater, TestCodeGenerator generator)
        throws IOException, TemplateParseException, PageObjectUpdateException {
    Preconditions.checkNotNull(templateFile);
    Preconditions.checkNotNull(rootInputDir);
    Preconditions.checkNotNull(codeOutDir);
    Preconditions.checkArgument(!Strings.isNullOrEmpty(packageName));
    Preconditions.checkNotNull(parser);

    if (verbose) {
        System.out.println(templateFile.getAbsolutePath() + " ... ");
    }
    File orgTemplateFile = backupFile(templateFile);
    String pageName = NameConverter.getJavaClassName(getFileNameWithoutExtension(templateFile));
    // Read template file
    String template = Files.toString(orgTemplateFile, Charset.defaultCharset());
    // Parse template extracting template variables
    TemplateInfo templateInfo = parser.parse(template);
    if (verbose) {
        System.out.print(".");
    }
    // Generate modified template
    String modifiedTemplate = updater.generate(templateInfo);
    if (verbose) {
        System.out.print(".");
    }

    // Construct path of skeleton test code
    URI relativeDirUri = rootInputDir.toURI().relativize(templateFile.getParentFile().toURI());
    String relativeDirPath = relativeDirUri.toString();
    if (relativeDirPath.endsWith("/")) {
        relativeDirPath = relativeDirPath.substring(0, relativeDirPath.length() - 1);
    }
    if (!Strings.isNullOrEmpty(relativeDirPath)) {
        relativeDirPath = File.separatorChar + relativeDirPath;
    }
    String packagePrefix = relativeDirPath.replace('/', '.');
    File actualDir = new File(codeOutDir.getPath() + relativeDirPath);
    actualDir.mkdirs();

    // Generate skeleton test code
    File codeFile = new File(actualDir, pageName + "Page.java");
    if (codeFile.exists() && !codeFile.canWrite()) {
        throw new FileProcessException("No permission for writing the specified file", codeFile);
    }

    // @formatter:off
    String testCode = codeFile.exists()
            ? generator.update(templateInfo, Files.toString(codeFile, Charset.defaultCharset()))
            : generator.generate(templateInfo, packageName + packagePrefix, pageName);
    // @formatter:on
    if (verbose) {
        System.out.print(".");
    }
    // Write generated template and skeleton test code
    Files.write(modifiedTemplate, templateFile, Charset.defaultCharset());
    if (verbose) {
        System.out.print(".");
    }
    Files.write(testCode, codeFile, Charset.defaultCharset());
    if (verbose) {
        System.out.println("\n" + templateFile.getAbsolutePath() + " processed successfully");
    }
}

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

/** Copy this remote file to the given file.
 * If the file resides on the current machine, remote file transfer is done
 * locally. Otherwise, the remote file is transferred over http.
 * If the file is not set to be able to be transferred multiple times, it is
 * cleaned up after the transfer./*  w  w  w.j  a 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 + "'");
    }
    if (isLocal() && fileDeletable && !multipleDownloads && !useChecksums) {
        if (file.renameTo(destFile)) {
            cleanup();
            return;
        }
        //if rename fails we fall back to normal usage.
    }
    super.copyTo(destFile);
}

From source file:it.geosolutions.opensdi.operations.FolderManagerOperationController.java

/**
 * Delete a folder/*  w ww  . ja v  a 2s  .  c o  m*/
 * 
 * @param folderName
 * @param subFolder
 */
private void deleteFolder(String folderName, String subFolder) {
    String folderPath = getFilePath(folderName, subFolder);
    LOGGER.debug("Deleting folder '" + folderPath + "'");
    File file = new File(folderPath);
    if (file.exists()) {
        if (file.canWrite()) {
            try {
                FileUtils.deleteDirectory(file);
            } catch (IOException e) {
                LOGGER.error("Error deleting '" + folderPath + "' folder");
            }
        } else {
            LOGGER.error("Incorrect permissions on folder '" + folderPath + "'. We can't delete it");
        }
    } else {
        LOGGER.error("Folder '" + folderPath + "' not exists");
    }
}

From source file:com.aoyetech.fee.commons.utils.FileUtils.java

public static void copyFile(final File srcFile, final File destFile, final boolean preserveFileDate)
        throws IOException {
    if (srcFile == null) {
        throw new NullPointerException("Source must not be null");
    }/*  w  ww.j ava  2  s  . c  o  m*/
    if (destFile == null) {
        throw new NullPointerException("Destination must not be null");
    }
    if (srcFile.exists() == false) {
        throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
    }
    if (srcFile.isDirectory()) {
        throw new IOException("Source '" + srcFile + "' exists but is a directory");
    }
    if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
        throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
    }
    if ((destFile.getParentFile() != null) && (destFile.getParentFile().exists() == false)) {
        if (destFile.getParentFile().mkdirs() == false) {
            throw new IOException("Destination '" + destFile + "' directory cannot be created");
        }
    }
    if (destFile.exists() && (destFile.canWrite() == false)) {
        throw new IOException("Destination '" + destFile + "' exists but is read-only");
    }
    doCopyFile(srcFile, destFile, preserveFileDate);
}

From source file:com.liferay.lms.service.impl.SCORMContentLocalServiceImpl.java

public boolean force(long scormId, String version) throws SystemException, PortalException, IOException {

    try {//from   ww  w  . j a  v  a2s . c o m
        SCORMContent scorm = this.getSCORMContent(scormId);
        String filename = this.getBaseDir() + "/" + Long.toString(scorm.getCompanyId()) + "/"
                + Long.toString(scorm.getGroupId()) + "/" + scorm.getUuid() + "/imsmanifest.xml";

        File file = new File(filename);
        FileOutputStream outputStream = null;
        if (file.exists() && file.canRead() && file.canWrite()) {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            InputStream inputStream = new FileInputStream(file);
            org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
            NodeList nodeList = doc.getElementsByTagName("schemaversion");
            Node node = nodeList.item(0);
            if (node == null) {
                return false;
            }
            node.setTextContent(version);
            StringWriter stw = new StringWriter();
            Transformer serializer = TransformerFactory.newInstance().newTransformer();
            serializer.transform(new DOMSource(doc), new StreamResult(stw));
            String scormXml = stw.toString();

            outputStream = new FileOutputStream(file);
            outputStream.write(scormXml.getBytes());

            outputStream.flush();
            outputStream.close();

        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

}

From source file:com.openmeap.model.dto.ClusterNode.java

public String validateFileSystemStoragePathPrefix() {
    if (fileSystemStoragePathPrefix == null) {
        return "File system storage path prefix should be set";
    }/*from  w  w w .  j a  v a 2  s .c om*/
    File path = new File(fileSystemStoragePathPrefix);
    List<String> errors = new ArrayList<String>();
    if (!path.exists()) {
        errors.add("does not exist");
    } else {
        if (!path.canWrite()) {
            return "not writable";
        }
        if (!path.canRead()) {
            return "not readable";
        }
    }
    if (errors.size() > 0) {
        StringBuilder sb = new StringBuilder(
                "The path \"" + fileSystemStoragePathPrefix + "\" has the following issues: ");
        sb.append(StringUtils.join(errors, ","));
        return sb.toString();
    }
    return null;
}

From source file:edu.cornell.mannlib.vivo.utilities.rdbmigration.RdbMigrator.java

private void confirmTargetDirectory() {
    File vivoHome = new File(vivoHomeDir);
    if (!vivoHome.isDirectory()) {
        quit("'" + vivoHome + "' is not a directory.");
    }/*from  ww w .ja va 2 s  .com*/
    if (!vivoHome.canWrite()) {
        quit("Can't write to '" + vivoHome + "'.");
    }
    targetDir = new File(vivoHome, DIRECTORY_TDB);
}

From source file:gov.nasa.ensemble.common.ui.FileSystemExportWizardPage.java

protected boolean ensureDirectoryExists(File target) {
    if (target.exists() && target.isDirectory() && target.canRead() && target.canWrite()) {
        return true;
    } else if (!target.exists()) {
        return target.mkdirs();
    } else//from   ww  w . j  a v  a 2  s .c om
        return false;
}

From source file:eu.eubrazilcc.lvl.storage.mongodb.cache.ReferencePersistingCache.java

@Override
public CachedVersionable put(final String id, final Reference obj) throws IOException {
    String key = null;/*from  w w  w.  j a  v a 2  s  .co  m*/
    checkArgument(isNotBlank(key = toKey(id)) && obj != null && isNotBlank(obj.getPubmedId())
            && obj.getArticle() != null, "Uninitialized or invalid reference");
    File outfile = null;
    try {
        final String uuid = randomUUID().toString();
        outfile = new File(new File(getCacheDir(), uuid.substring(0, 2)), uuid);
        final File parentDir = outfile.getParentFile();
        if (parentDir.exists() || parentDir.mkdirs())
            ;
        if ((outfile.isFile() && outfile.canWrite()) || outfile.createNewFile())
            ;
        final CachedVersionable cached = CachedVersionable.builder().cachedFilename(outfile.getCanonicalPath())
                .version(obj.getPubmedId().trim()).build();
        PUBMED_XMLB.typeToFile(obj.getArticle(), outfile);
        CACHE.put(key, cached);
        return cached;
    } catch (Exception e) {
        deleteQuietly(outfile);
        throw e;
    }
}

From source file:com.ironiacorp.scm.subversion.SubversionRepository.java

/**
 * Change the repository address.//from  www  .j  av a  2 s .  c o  m
 * 
 * @param url
 *            A valid URL.
 * @throws RepositoryError
 *             If the URL is invalid.
 */
public void setLocation(String url) {
    if (url.startsWith(File.separator)) {
        File dir = new File(url);
        if (dir.isDirectory() && dir.canRead() && dir.canWrite()) {
            url = "file://" + url;
        } else {
            throw new IllegalArgumentException("exception.repository.invalidLocation");
        }
    } else {
        try {
            new URL(url);

        } catch (MalformedURLException e) {
            throw new IllegalArgumentException("exception.repository.invalidLocation", e);
        }
    }

    super.setLocation(url);
}