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.github.notizklotz.derbunddownloader.download.IssueDownloadService.java

private String startDownload(LocalDate issueDate, boolean wifiOnly) {
    final String title = expandTemplateWithDate(ISSUE_TITLE_TEMPLATE, issueDate);
    final String filename = expandTemplateWithDate(ISSUE_FILENAME_TEMPLATE, issueDate);
    if (BuildConfig.DEBUG) {
        File extFilesDir = getExternalFilesDir(null);
        File file = new File(extFilesDir, filename);
        Log.d(LOG_TAG, "Filename: " + file.toString());
        Log.d(LOG_TAG, "Can write? " + (extFilesDir != null && extFilesDir.canWrite()));
    }/* w w w  .  j  a  v  a2  s . c o m*/

    Uri issueUrl = Uri.parse(expandTemplateWithDate(ISSUE_PDF_URL_TEMPLATE, issueDate));
    DownloadManager.Request pdfDownloadRequest = new DownloadManager.Request(issueUrl).setTitle(title)
            .setDescription(expandTemplateWithDate(ISSUE_DESCRIPTION_TEMPLATE, issueDate))
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
            .setDestinationInExternalFilesDir(this, null, filename);

    if (wifiOnly) {
        pdfDownloadRequest.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            pdfDownloadRequest.setAllowedOverMetered(false);
        }
    }
    downloadManager.enqueue(pdfDownloadRequest);

    return title;
}

From source file:com.adobe.communities.ugc.migration.legacyExport.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   www. j  a  v a2  s .  com*/
    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");
    }
    entries = new HashMap<String, Boolean>();
    entriesToSkip = new HashMap<String, Boolean>();
    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);
            if (entries.size() > 0) {
                exportCommentSystems(entries, entriesToSkip, 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();
        }
    }
}

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

@Override
protected void doGet(@Nonnull final SlingHttpServletRequest request,
        @Nonnull 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  w  w  . j  a  v a2s  .  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();
        }
    }
}

From source file:eu.prestoprime.plugin.p4.CopyTasks.java

@WfService(name = "make_consumer_copy", version = "2.0.0")
public void makeConsumerCopy(Map<String, String> sParams, Map<String, String> dParamsString,
        Map<String, File> dParamFile) throws TaskExecutionFailedException {

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

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

        // retrieve dynamic params
        String dipID = dParamsString.get("id");
        String mimetype = dParamsString.get("mimetype");

        String outputFolder = destVolume + File.separator + destFolder;

        try {//  w  ww . ja v a  2  s.  co  m
            DIP dip = P4DataManager.getInstance().getDIPByID(dipID);

            // get MQ file
            String videoFile = null;

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

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

                    File sourceFile = new File(videoFile);

                    if (!sourceFile.canRead() || !sourceFile.isFile())
                        throw new TaskExecutionFailedException("Unable to read source video file...");

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

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

                    String targetFileName = dipID + videoFile.substring(videoFile.lastIndexOf("."));
                    File targetFile = new File(outputFolder, targetFileName);

                    FileInputStream in = new FileInputStream(sourceFile);
                    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("isCopied", "true");
                    dParamsString.put("target.file.name", targetFileName);

                    logger.debug("Consumer copy available at: " + targetFile.getAbsolutePath());
                }
            }
        } 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");
        }
    }
}

From source file:com.gisgraphy.importer.GeonamesAdmExtracter.java

/**
 * @param file//from  w  ww  . j a v a 2s .  co m
 */
private void checkWriteRights(File file) {
    if (!file.canWrite()) {
        throw new RuntimeException(
                "you must have write rights in order to export adm in file " + file.getAbsolutePath());
    }
}

From source file:es.uvigo.ei.sing.rubioseq.gui.view.models.experiments.ChipSeqExperimentModel.java

@NotifyChange({ "selectOutputFile", "currentExperimentFile" })
@Command//ww w.j av  a2s .c  om
public void generateXMLConfigurationFile() {
    File output = new File(this.outputFilePath, this.outputFileName);
    File outputDirectory = new File(this.outputFilePath);
    if (outputDirectory.isDirectory()) {
        if (outputDirectory.canWrite()) {
            try {
                experiment.generateXMLConfigurationFile(output);
                this.currentExperimentFile = new RUbioSeqFile(output, outputFilePathRSFile.getDatastore());
                Messagebox.show("Configuration saved", "OK", Messagebox.OK, Messagebox.INFORMATION);
            } catch (IOException e) {
                Messagebox.show("Error saving configuration", "Error", Messagebox.OK, Messagebox.ERROR);
                this.currentExperimentFile = null;
                e.printStackTrace();
            }
            this.selectOutputFile = false;
        } else {
            this.currentExperimentFile = null;
            Messagebox.show("Cannot write to file " + output.getName(), "Invalid file", Messagebox.OK,
                    Messagebox.ERROR);
        }
    } else {
        this.currentExperimentFile = null;
        Messagebox.show(this.outputFilePath + " is not a directory.", "Invalid file", Messagebox.OK,
                Messagebox.ERROR);
    }
    if (this.executeExperiment) {
        this.executeExperiment();
        this.executeExperiment = false;
    }
}

From source file:dk.netarkivet.common.utils.FileUtils.java

/** Creates a new temporary directory with a unique name.
 * This directory will be deleted automatically at the end of the
 * VM (though behaviour if there are files in it is undefined).
 * This method will try a limited number of times to create a directory,
 * using a randomly generated suffix, before giving up.
 *
 * @param inDir The directory where the temporary directory
 * should be created./*w w  w .j  a  va  2s. co  m*/
 * @param prefix The prefix of the directory name, for identification
 * purposes.
 * @return A newly created directory that no other calls to createUniqueDir
 * returns.
 * @throws ArgumentNotValid if inDir is not an existing
 * directory that can be written to.
 * @throws IOFailure if a free name couldn't be found within a reasonable
 * number of tries.
 */
public static File createUniqueTempDir(File inDir, String prefix) {
    ArgumentNotValid.checkNotNull(inDir, "File inDir");
    ArgumentNotValid.checkNotNullOrEmpty(prefix, "String prefix");
    ArgumentNotValid.checkTrue(inDir.isDirectory(), inDir + " must be a directory");
    ArgumentNotValid.checkTrue(inDir.canWrite(), inDir + " must be writeable");
    for (int tries = 0; tries < MAX_RETRIES; tries++) {
        File newDir;
        try {
            newDir = File.createTempFile(prefix, null, inDir);
        } catch (IOException e) {
            final String errMsg = "Couldn't create temporary file in '" + inDir.getAbsolutePath()
                    + "' with prefix '" + prefix + "'";
            log.warn(errMsg, e);
            throw new IOFailure(errMsg, e);
        }
        newDir.delete();
        if (newDir.mkdir()) {
            newDir.deleteOnExit();
            return newDir;
        }
    }
    final String errMsg = "Too many similar files around, cannot create " + "unique dir with prefix " + prefix
            + " in '" + inDir.getAbsolutePath() + "'.";
    log.warn(errMsg);
    throw new IOFailure(errMsg);
}

From source file:io.sightly.tck.TCK.java

private void extract(String extractDir) throws IOException {
    File extractFolder = new File(extractDir);
    if (extractFolder.exists()) {
        if (!extractFolder.isDirectory()) {
            throw new IOException("File entry " + extractFolder.getAbsolutePath()
                    + " already exists and it is not a folder.");
        }//from  w w w. j  av  a 2  s  .  c  om
        if (!extractFolder.canWrite()) {
            throw new IOException(
                    "Folder " + extractFolder.getAbsolutePath() + " exists but it is not writable.");
        }
    } else {
        if (!extractFolder.mkdirs()) {
            throw new IOException("Unable to create folder " + extractFolder.getAbsolutePath() + ".");
        }
    }
    Enumeration<JarEntry> entries = jarFile.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String entryName = entry.getName();
        if (entryName.startsWith(TESTFILES)) {
            File file = new File(extractFolder, entryName);
            if (entry.isDirectory()) {
                if (!file.mkdir()) {
                    throw new IOException("Unable to create folder " + file.getAbsolutePath());
                }
                continue;
            }
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = jarFile.getInputStream(entry);
                fos = new FileOutputStream(file);
                while (is.available() > 0) {
                    fos.write(is.read());
                }
                fos.close();
                is.close();
            } catch (IOException e) {
                LOG.error("Unable to extract file " + file.getAbsolutePath());
            } finally {
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
            }
        }
    }
}

From source file:com.us.action.file.KindUpLoad.java

@Override
public String execute() throws Exception {
    if (gloabelError != null) {
        return text(getError(gloabelError.toString()));
    }//from w  w  w .j  a  v a 2 s .c om

    if (imgFile == null) {
        return text(getError(getI118("${upload.nofile}", getRequest())));
    }

    String dirName = getRequest().getParameter("dir");
    if (dirName == null) {
        dirName = "image";
    }

    final String allowed = AppHelper.KIND_CONFIG.get(dirName).toString();
    String fileExt = FilenameUtils.getExtension(imgFileFileName);
    if (!Arrays.<String>asList(allowed.split(",")).contains(fileExt)) {
        return text(getError(getI118("${upload.invaildFile}", getRequest(), imgFileFileName, allowed)));
    }

    Object savePath = AppHelper.KIND_CONFIG.get("savePath");
    if (savePath == null) {
        return text(getError(getI118("${upload.noConfig}", getRequest(), "savePath")));
    }
    // 
    File uploadDir = FileHelper.getFile(AppHelper.APPSET.getFilePath(), savePath.toString());
    if (!uploadDir.exists())
        uploadDir.mkdirs();
    if (uploadDir == null || !uploadDir.isDirectory()) {
        return text(getError(getI118("${upload.dirNotExist}", getRequest())));
    }
    // ??
    if (!uploadDir.canWrite()) {
        return text(getError(getI118("${upload.dirCantWrite}", getRequest())));
    }

    Object type = AppHelper.KIND_CONFIG.get(dirName);
    if (type == null) {
        return text(getError(getI118("${upload.typeNoConfig}", getRequest(), "dirName")));
    }
    // ?URL
    String saveUrl = AppHelper.APPSET.getWebPath() + savePath.toString();

    if (!uploadDir.exists())
        uploadDir.mkdirs();

    String child = DateUtil.format(DateUtil.now(), "yyyyMM/dd/");
    uploadDir = FileHelper.getFile(uploadDir, child);
    saveUrl += child;
    if (!uploadDir.exists()) {
        uploadDir.mkdirs();
    }

    final long initSize = Long.parseLong(AppHelper.KIND_CONFIG.get("maxSize").toString());
    if (imgFile.length() > initSize * 1024000) {
        return text(getError(
                getI118("${upload.tooMax}", getRequest(), imgFileFileName, imgFile.length(), initSize)));
    }

    String newFileName = RandomHelper.uu_id() + "." + fileExt;
    File uploadedFile = new File(uploadDir, newFileName);
    final long startTime = System.currentTimeMillis();
    FileUtils.copyFile(imgFile, uploadedFile);
    log.info(String.format("?%s(ms)", (System.currentTimeMillis() - startTime)));

    return text(JSONHelper.obj2Json(KindResult
            .success(getI118("${upload.hasUpload}", getRequest(), imgFileFileName), saveUrl + newFileName)));
}