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.photokandy.PKVideoThumbnail.PKVideoThumbnail.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action        The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackId    The callback id used when calling back into JavaScript.
 * @return              A PluginResult object with a status and message.
 *///from  w  ww .j  a v  a2  s  . c  om
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {
        if (action.equals("createThumbnail")) {
            String sourceVideo = args.getString(0);
            String targetImage = args.getString(1);

            Bitmap thumbnail = ThumbnailUtils.createVideoThumbnail(sourceVideo.substring(7),
                    MediaStore.Images.Thumbnails.MINI_KIND);

            FileOutputStream theOutputStream;
            try {
                File theOutputFile = new File(targetImage.substring(7));
                if (!theOutputFile.exists()) {
                    if (!theOutputFile.createNewFile()) {
                        callbackContext.error("Could not save thumbnail.");
                        return true;
                    }
                }
                if (theOutputFile.canWrite()) {
                    theOutputStream = new FileOutputStream(theOutputFile);
                    if (theOutputStream != null) {
                        thumbnail.compress(CompressFormat.JPEG, 75, theOutputStream);
                    } else {
                        callbackContext.error("Could not save thumbnail; target not writeable");
                        return true;
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                callbackContext.error("I/O exception saving thumbnail");
                return true;
            }
            callbackContext.success(targetImage);
            return true;

        } else {
            return false;
        }
    } catch (JSONException e) {
        callbackContext.error("JSON Exception");
        return true;
    }
}

From source file:com.devbury.mkremote.server.QuickLaunchServiceImpl.java

protected void open(final File file) {
    if (logger.isDebugEnabled()) {
        logger.debug("File name {} exists {}, read {}, write {}, execute {}", new Object[] {
                file.getAbsolutePath(), file.exists(), file.canRead(), file.canWrite(), file.canExecute() });
    }/* ww w. j  av  a  2  s .  c  o  m*/
    try {
        Desktop.getDesktop().open(file);
    } catch (Throwable t) {
        if (isMac()) {
            File file_app = newFile(file.getAbsolutePath() + ".app");
            try {
                Desktop.getDesktop().open(file_app);
            } catch (Throwable tt) {
                handleOpenError(file, t);
            }
        } else {
            handleOpenError(file, t);
        }
    }
}

From source file:dk.netarkivet.common.distribute.arcrepository.LocalArcRepositoryClient.java

/**
 * Store the given file in the ArcRepository.  After storing, the file is
 * deleted.//  w ww . j a  v  a  2s . co  m
 *
 * @param file A file to be stored. Must exist.
 * @throws IOFailure thrown if store is unsuccessful, or failed to clean
 * up files after the store operation.
 * @throws IllegalState if file already exists.
 * @throws ArgumentNotValid if file parameter is null or file is not an
 *                          existing file.
 */
@Override
public void store(File file) throws IOFailure, ArgumentNotValid {
    ArgumentNotValid.checkNotNull(file, "File file");
    ArgumentNotValid.checkTrue(file.exists(), "File '" + file + "' does not exist");
    if (findFile(file.getName()) != null) {
        throw new IllegalState("A file with the name '" + file.getName() + " is already stored");
    }
    for (File dir : storageDirs) {
        if (dir.canWrite() && FileUtils.getBytesFree(dir) > file.length()) {
            FileUtils.moveFile(file, new File(dir, file.getName()));
            return;
        }
    }
    throw new IOFailure("Not enough room for '" + file + "' in any of the dirs " + storageDirs);
}

From source file:gridool.util.xfer.RecievedFileWriter.java

public RecievedFileWriter(@Nonnull File baseDir) {
    if (!baseDir.exists()) {
        throw new IllegalArgumentException("Directory not found: " + baseDir.getAbsolutePath());
    }/*from  w  w  w  .j  a  v a  2s .c o  m*/
    if (!baseDir.isDirectory()) {
        throw new IllegalArgumentException(baseDir.getAbsolutePath() + " is not directory");
    }
    if (!baseDir.canWrite()) {
        throw new IllegalArgumentException(baseDir.getAbsolutePath() + " is not writable");
    }
    this.baseDir = baseDir;
    this.locks = new SoftHashMap<String, ReadWriteLock>(32);
}

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

public String validateTemporaryStoragePath() {
    if (temporaryStoragePath == null) {
        return "Temporary storage path should be set";
    }//from   w w w.j a  va  2s  . co  m
    File path = new File(temporaryStoragePath);
    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 \"" + temporaryStoragePath + "\" has the following issues: ");
        sb.append(StringUtils.join(errors, ","));
        return sb.toString();
    }
    return null;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.XLSExport.java

public void writeData(final List<?> data) throws Exception {
    HSSFWorkbook workBook = new HSSFWorkbook();
    HSSFSheet workSheet = workBook.createSheet();
    DocumentSummaryInformation mappings = null;

    int rowNum = 0;

    if (config.getFirstRowHasHeaders() && !config.getAppendData()) {
        writeHeaders(workSheet);//from  w ww .j  a v  a  2  s. co  m
        rowNum++;

        String[] headers = config.getHeaders();
        for (int i = 0; i < headers.length; i++) {
            workSheet.setColumnWidth(i,
                    StringUtils.isNotEmpty(headers[i]) ? (256 * headers[i].length()) : 2560);
        }

        WorkbenchTemplate wbTemplate = null;
        if (data.get(0) instanceof WorkbenchTemplate) {
            wbTemplate = (WorkbenchTemplate) data.get(0);
        } else {
            wbTemplate = ((WorkbenchRow) data.get(0)).getWorkbench().getWorkbenchTemplate();
        }
        mappings = writeMappings(wbTemplate);
    }
    //assuming data is never empty.
    boolean hasTemplate = data.get(0) instanceof WorkbenchTemplate;
    boolean hasRows = hasTemplate ? data.size() > 1 : data.size() > 0;
    if (hasRows) {
        int[] disciplinees;

        WorkbenchRow wbRow = (WorkbenchRow) data.get(hasTemplate ? 1 : 0);
        Workbench workBench = wbRow.getWorkbench();
        WorkbenchTemplate template = workBench.getWorkbenchTemplate();
        int numCols = template.getWorkbenchTemplateMappingItems().size();
        int geoDataCol = -1;
        Vector<Integer> imgCols = new Vector<Integer>();

        disciplinees = bldColTypes(template);
        for (Object rowObj : data) {
            if (rowObj instanceof WorkbenchTemplate) {
                continue;
            }

            WorkbenchRow row = (WorkbenchRow) rowObj;
            HSSFRow hssfRow = workSheet.createRow(rowNum++);
            int colNum;
            boolean rowHasGeoData = false;

            for (colNum = 0; colNum < numCols; colNum++) {
                HSSFCell cell = hssfRow.createCell(colNum);
                cell.setCellType(disciplinees[colNum]);
                setCellValue(cell, row.getData(colNum));
            }

            if (row.getBioGeomancerResults() != null && !row.getBioGeomancerResults().equals("")) {
                geoDataCol = colNum;
                rowHasGeoData = true;
                HSSFCell cell = hssfRow.createCell(colNum++);
                cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                setCellValue(cell, row.getBioGeomancerResults());
            }

            // if (row.getCardImage() != null)
            if (row.getRowImage(0) != null) {
                if (!rowHasGeoData) {
                    colNum++;
                }
                int imgIdx = 0;
                WorkbenchRowImage img = row.getRowImage(imgIdx++);
                while (img != null) {
                    if (imgCols.indexOf(colNum) < 0) {
                        imgCols.add(colNum);
                    }
                    HSSFCell cell = hssfRow.createCell(colNum++);
                    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    String cellValue = img.getCardImageFullPath();
                    String attachToTbl = img.getAttachToTableName();
                    if (attachToTbl != null) {
                        cellValue += "\t" + attachToTbl;
                    }
                    setCellValue(cell, cellValue);
                    img = row.getRowImage(imgIdx++);
                }
            }

        }
        if (imgCols.size() > 0 || geoDataCol != -1) {
            writeExtraHeaders(workSheet, imgCols, geoDataCol);
        }

    }
    try {
        // Write the workbook
        File file = new File(getConfig().getFileName());
        if (file.canWrite() || (!file.exists() && file.createNewFile())) {
            FileOutputStream fos = new FileOutputStream(file);
            workBook.write(fos);
            fos.close();

            //Now write the mappings.
            //NOT (hopefully) the best way to write the mappings, but (sadly) the easiest way. 
            //May need to do this another way if this slows performance for big wbs.
            if (mappings != null) {
                InputStream is = new FileInputStream(file);
                POIFSFileSystem poifs = new POIFSFileSystem(is);
                is.close();
                mappings.write(poifs.getRoot(), DocumentSummaryInformation.DEFAULT_STREAM_NAME);
                fos = new FileOutputStream(file);
                poifs.writeFilesystem(fos);
                fos.close();
            }
        } else {
            UIRegistry.displayErrorDlgLocalized("WB_EXPORT_PERM_ERR");
        }
    } catch (Exception e) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(XLSExport.class, e);
        throw (e);
    }
}

From source file:com.silverpeas.silvercrawler.model.FileFolder.java

public FileFolder(String rootPath, String path, boolean isAdmin, String componentId) {
    this.path = path;
    files = new ArrayList<FileDetail>(0);
    folders = new ArrayList<FileDetail>(0);

    try {//from w  w w .jav  a2  s  .  c om
        SilverTrace.debug("silverCrawler", "FileFolder.FileFolder()", "root.MSG_GEN_PARAM_VALUE",
                "Starting constructor for FileFolder. Path = " + path);
        File f = new File(path);

        SilverTrace.debug("silverCrawler", "FileFolder.FileFolder()", "root.MSG_GEN_PARAM_VALUE",
                "isExists " + f.exists() + " isFile=" + f.isFile());

        writable = f.canWrite();

        if (f.exists()) {
            this.name = f.getName();
            this.readable = f.canRead();
            File[] children = f.listFiles();

            IndexReader reader = null;
            boolean isIndexed = false;

            if (isAdmin) {
                // ouverture de l'index
                Directory indexPath = FSDirectory
                        .open(new File(IndexFileManager.getAbsoluteIndexPath("", componentId)));
                if (IndexReader.indexExists(indexPath)) {
                    reader = IndexReader.open(indexPath);
                }
            }
            if (children != null && children.length > 0) {
                for (File childFile : children) {
                    SilverTrace.debug("silverCrawler", "FileFolder.FileFolder()", "root.MSG_GEN_PARAM_VALUE",
                            "Name = " + childFile.getName());
                    isIndexed = false;
                    if (isAdmin) {
                        // rechercher si le rpertoire (ou le fichier) est index
                        String pathIndex = componentId + "|";
                        if (childFile.isDirectory()) {
                            pathIndex = pathIndex + "LinkedDir" + "|";
                        } else {
                            pathIndex = pathIndex + "LinkedFile" + "|";
                        }
                        pathIndex = pathIndex + FilenameUtils.separatorsToUnix(childFile.getPath());
                        SilverTrace.debug("silverCrawler", "FileFolder.FileFolder()",
                                "root.MSG_GEN_PARAM_VALUE", "pathIndex = " + pathIndex);

                        Term term = new Term("key", pathIndex);
                        if (reader != null && reader.docFreq(term) == 1) {
                            isIndexed = true;
                        }
                    }

                    if (childFile.isDirectory()) {
                        folders.add(new FileDetail(childFile.getName(), childFile.getPath(), null,
                                childFile.length(), true, isIndexed));
                    } else {
                        String childPath = FileUtils.getFile(childFile.getPath().substring(rootPath.length()))
                                .getPath();
                        files.add(new FileDetail(childFile.getName(), childPath, childFile.getPath(),
                                childFile.length(), false, isIndexed));
                    }
                }
            }
            // fermeture de l'index
            if (reader != null && isAdmin) {
                reader.close();
            }

        }
    } catch (Exception e) {
        throw new SilverCrawlerRuntimeException("FileFolder.FileFolder()", SilverpeasRuntimeException.ERROR,
                "silverCrawler.IMPOSSIBLE_DACCEDER_AU_REPERTOIRE", e);
    }
}

From source file:org.duracloud.snapshot.bridge.rest.GeneralResource.java

/**
 * @param path//  ww  w.  j  a  v a 2s.  c o  m
 * @return
 */
private File createDirectoryIfNotExists(String path) {
    File wdir = new File(path);
    if (!wdir.exists()) {
        if (!wdir.mkdirs()) {
            throw new RuntimeException("failed to initialize " + path + ": directory could not be created.");
        }
    }

    if (!wdir.canWrite()) {
        throw new RuntimeException(wdir.getAbsolutePath() + " must be writable.");
    }

    return wdir;
}

From source file:net.pictulog.otgdb.task.BackupTask.java

@Override
protected void visitFile(FsDirectoryEntry file, File targetDirectory) throws IOException {
    if (file == null || !file.isFile()) {
        throw new IllegalArgumentException("entry must be an existing file");
    }/*from  www.j  ava2 s  .  c  o  m*/
    if (targetDirectory == null || !targetDirectory.exists() || !targetDirectory.isDirectory()
            || !targetDirectory.canWrite()) {
        throw new IllegalArgumentException(
                "targetDirectory '" + targetDirectory + "' must be an existing writable directory");
    }
    String entryName = file.getName();
    String extensionUpper = FilenameUtils.getExtension(entryName).toUpperCase();
    String extensionLower = FilenameUtils.getExtension(entryName).toLowerCase();
    if (!extensions.isEmpty() && !extensions.contains(extensionUpper) && !extensions.contains(extensionLower)) {
        return;
    }
    if (copyFile(file.getFile(), new File(targetDirectory, entryName))) {
        if (delete) {
            fileToDelete.peek().add(entryName);
        }
    } else {
        failedToBackup.add(entryName);
    }
}