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:org.red5.server.stream.RecordingListener.java

/**
 * Get the file we'd be recording to based on scope and given name.
 *
 * @param scope/*from ww w .  j  ava2s  .c o m*/
 *            scope
 * @param name
 *            name
 * @return file
 */
public static File getRecordFile(IScope scope, String name) {
    // get stream filename generator
    IStreamFilenameGenerator generator = (IStreamFilenameGenerator) ScopeUtils.getScopeService(scope,
            IStreamFilenameGenerator.class, DefaultStreamFilenameGenerator.class);
    // generate filename
    String fileName = generator.generateFilename(scope, name, ".flv", GenerationType.RECORD);
    File file = null;
    if (generator.resolvesToAbsolutePath()) {
        file = new File(fileName);
    } else {
        Resource resource = scope.getContext().getResource(fileName);
        if (resource.exists()) {
            try {
                file = resource.getFile();
                log.debug("File exists: {} writable: {}", file.exists(), file.canWrite());
            } catch (IOException ioe) {
                log.error("File error: {}", ioe);
            }
        } else {
            String appScopeName = ScopeUtils.findApplication(scope).getName();
            file = new File(
                    String.format("%s/webapps/%s/%s", System.getProperty("red5.root"), appScopeName, fileName));
        }
    }
    return file;
}

From source file:dk.netarkivet.common.utils.cdx.CDXUtils.java

/**
  * Applies createCDXRecord() to all ARC/WARC files in a directory, creating
  * one CDX file per ARC/WARC file.//w w w.  ja  va  2  s. co m
  * Note, any exceptions during index generation are logged at level FINE
  * but otherwise ignored.
  * Exceptions creating any cdx file are logged at level WARNING but
  * otherwise ignored.
  * CDX files are named as the ARC/WARC files except ".(w)arc" or
  * ".(w)arc.gz" is extended with ".cdx"
  *
  * @param archiveProfile archive profile including filters, patterns, etc.
  * @param archiveFileDirectory A directory with archive files to generate
  * index for
  * @param cdxFileDirectory A directory to generate CDX files in
  * @throws ArgumentNotValid if any of directories are null or is not an
  * existing directory, or if cdxFileDirectory is not writable.
  */
public static void generateCDX(ArchiveProfile archiveProfile, File archiveFileDirectory, File cdxFileDirectory)
        throws ArgumentNotValid {
    ArgumentNotValid.checkNotNull(archiveProfile, "ArchiveProfile archiveProfile");
    ArgumentNotValid.checkNotNull(archiveFileDirectory, "File archiveFileDirectory");
    ArgumentNotValid.checkNotNull(cdxFileDirectory, "File cdxFileDirectory");
    if (!archiveFileDirectory.isDirectory() || !archiveFileDirectory.canRead()) {
        throw new ArgumentNotValid(
                "The directory for arc files '" + archiveFileDirectory + "' is not a readable directory");
    }
    if (!cdxFileDirectory.isDirectory() || !cdxFileDirectory.canWrite()) {
        throw new ArgumentNotValid(
                "The directory for cdx files '" + archiveFileDirectory + "' is not a writable directory");
    }
    Map<File, Exception> exceptions = new HashMap<File, Exception>();
    File[] filesToProcess = archiveFileDirectory.listFiles(archiveProfile.filename_filter);
    if (filesToProcess.length == 0) {
        log.warn("Found no related arcfiles to process in the archive dir '"
                + archiveFileDirectory.getAbsolutePath() + "'.");
    } else {
        log.debug("Found " + filesToProcess.length + " related arcfiles to process in the archive dir '"
                + archiveFileDirectory.getAbsolutePath() + "'.");
    }
    for (File arcfile : filesToProcess) {
        File cdxfile = new File(cdxFileDirectory, arcfile.getName() + FileUtils.CDX_EXTENSION);
        try {
            OutputStream cdxstream = null;
            try {
                cdxstream = new FileOutputStream(cdxfile);
                writeCDXInfo(arcfile, cdxstream);
            } finally {
                if (cdxstream != null) {
                    cdxstream.close();
                }
            }
        } catch (Exception e) {
            exceptions.put(cdxfile, e);
        }
    }
    // Log any errors
    if (exceptions.size() > 0) {
        StringBuilder errorMsg = new StringBuilder("Exceptions during cdx file generation:\n");
        for (Map.Entry<File, Exception> fileException : exceptions.entrySet()) {
            errorMsg.append("Could not create cdxfile '");
            errorMsg.append(fileException.getKey().getAbsolutePath());
            errorMsg.append("':\n");
            errorMsg.append(ExceptionUtils.getStackTrace(fileException.getValue()));
            errorMsg.append('\n');
        }
        log.debug(errorMsg.toString());
    }
}

From source file:io.yields.math.framework.kpi.ScoreDAO.java

/**
 * Persists a #{ScoreResult}.//from   w  w w.  j  av  a 2s  .  c  om
 * If a system property yields.score.path is found, this result is written to that location.
 * Otherwise, this result is written to the path defined by the system property java.io.tmpDir.
 *
 * @param scoreResult Score Result to persist
 */
public static void save(ScoreResult scoreResult) {

    File destinationFolder = getRootFolder();

    if (!destinationFolder.exists()) {
        try {
            forceMkdir(destinationFolder);
        } catch (IOException ioe) {
            throw new IllegalStateException(format("Destination folder for scores could not be created at %s",
                    destinationFolder.getAbsolutePath()), ioe);
        }
    }

    if (!destinationFolder.isDirectory()) {
        throw new IllegalStateException(
                format("Destination path for scores %s is not a folder", destinationFolder.getAbsolutePath()));
    }

    if (!destinationFolder.canWrite()) {
        throw new IllegalStateException(format("Destination folder for scores %s is not writable",
                destinationFolder.getAbsolutePath()));
    }

    ObjectMapper jsonMapper = getObjectMapper();
    File destinationFile = new File(destinationFolder, scoreResult.getName().replaceAll("[^a-zA-Z0-9]", "_")
            + "_" + DATE_TIME_FORMATTER.format(LocalDateTime.now()) + "." + FILE_SUFFIX);
    try {
        scoreResult.setTimestamp(ZonedDateTime.now());
        jsonMapper.writeValue(destinationFile, scoreResult);
        logger.info("Written score result to {}", destinationFile.getAbsolutePath());
    } catch (IOException ioe) {
        logger.error("Could not write score result to file " + destinationFile.getAbsolutePath(), ioe);
        throw new IllegalStateException(
                format("Could not write score file at %s", destinationFile.getAbsolutePath()), ioe);
    }

}

From source file:com.meltmedia.cadmium.core.FileSystemManager.java

/**
 * Try's to create a directory and ensures that it is writable. 
 * @param logDir The File object to check.
 * @return The File object passed in for chaining call to it. This value will never be null.
 * @throws FileNotFoundException Thrown if logDir is null, exists, is not a directory, cannot be created, or cannot be written to.
 *//*from w w  w.  java2  s. com*/
public static File ensureDirectoryWriteable(File logDir) throws FileNotFoundException {
    try {
        FileUtils.forceMkdir(logDir);
    } catch (IOException e) {
        log.debug("Failed to create directory " + logDir, e);
        throw new FileNotFoundException(
                "Failed to create directory: " + logDir + " IOException: " + e.getMessage());
    }
    if (!logDir.canWrite()) {
        log.debug("Init param log dir cannot be used!");
        throw new FileNotFoundException("Directory is not writable: " + logDir);
    }
    return logDir;
}

From source file:net.ftb.util.OSUtils.java

/**
 * Gets the default installation path for the current OS.
 * @return a string containing the default install path for the current OS.
 *///from  w  w w . j a  v  a2 s .  co m
public static String getDefInstallPath() {
    switch (getCurrentOS()) {
    case WINDOWS:
        String defaultLocation = "c:\\ftb";
        File testFile = new File(defaultLocation);
        // existing directory and we can write
        if (testFile.canWrite()) {
            return defaultLocation;
        }

        // We can create default directory
        if (testFile.getParentFile().canWrite()) {
            return defaultLocation;
        }
        Logger.logWarn(
                "Can't use default installation location. Using current location of the launcher executable.");

    case MACOSX:
        return System.getProperty("user.home") + "/ftb";
    case UNIX:
        return System.getProperty("user.home") + "/ftb";
    default:
        try {
            CodeSource codeSource = LaunchFrame.class.getProtectionDomain().getCodeSource();
            File jarFile;
            jarFile = new File(codeSource.getLocation().toURI().getPath());
            return jarFile.getParentFile().getPath();
        } catch (URISyntaxException e) {
            Logger.logError("Unexcepted error", e);
        }

        return System.getProperty("user.home") + System.getProperty("path.separator") + "FTB";
    }
}

From source file:io.yields.math.framework.kpi.ExplorerDAO.java

public static void save(Explorer<?> explorer) {
    String group = explorer.getGroup();
    if (StringUtils.isBlank(group)) {
        group = NO_GROUP;// w  w w  .j av a 2s . c  o m
    }
    File destinationFolder = getRootFolder(group);

    if (!destinationFolder.exists()) {
        try {
            forceMkdir(destinationFolder);
        } catch (IOException ioe) {
            throw new IllegalStateException(
                    format("Destination folder for data export could not be created at %s",
                            destinationFolder.getAbsolutePath()),
                    ioe);
        }
    }

    if (!destinationFolder.isDirectory()) {
        throw new IllegalStateException(format("Destination path for data export %s is not a folder",
                destinationFolder.getAbsolutePath()));
    }

    if (!destinationFolder.canWrite()) {
        throw new IllegalStateException(format("Destination folder for data export %s is not writable",
                destinationFolder.getAbsolutePath()));
    }

    String fileName = explorer.getName().replaceAll("[^a-zA-Z0-9]", "_") + "_"
            + DATE_TIME_FORMATTER.format(LocalDateTime.now());

    File csvDestinationFile = new File(destinationFolder, fileName + "." + FILE_SUFFIX_CSV);
    csvExporter.export(explorer, csvDestinationFile);

    File jsonDestinationFile = new File(destinationFolder, fileName + "." + FILE_SUFFIX_JSON);
    jsonExporter.export(explorer, jsonDestinationFile);

}

From source file:com.puppycrawl.tools.checkstyle.Main.java

/**
 * Do validation of Command line options.
 * @param cmdLine command line object/*w  w  w . j  a  va  2 s . c o m*/
 * @return list of violations
 */
private static List<String> validateCli(CommandLine cmdLine) {
    final List<String> result = new ArrayList<>();
    // ensure a configuration file is specified
    if (cmdLine.hasOption(OPTION_C_NAME)) {
        // validate optional parameters
        if (cmdLine.hasOption(OPTION_F_NAME)) {
            final String format = cmdLine.getOptionValue(OPTION_F_NAME);
            if (!PLAIN_FORMAT_NAME.equals(format) && !XML_FORMAT_NAME.equals(format)) {
                result.add(String.format("Invalid output format." + " Found '%s' but expected '%s' or '%s'.",
                        format, PLAIN_FORMAT_NAME, XML_FORMAT_NAME));
            }
        }
        if (cmdLine.hasOption(OPTION_P_NAME)) {
            final String propertiesLocation = cmdLine.getOptionValue(OPTION_P_NAME);
            final File file = new File(propertiesLocation);
            if (!file.exists()) {
                result.add(String.format("Could not find file '%s'.", propertiesLocation));
            }
        }
        if (cmdLine.hasOption(OPTION_O_NAME)) {
            final String outputLocation = cmdLine.getOptionValue(OPTION_O_NAME);
            final File file = new File(outputLocation);
            if (file.exists() && !file.canWrite()) {
                result.add(String.format("Permission denied : '%s'.", outputLocation));
            }
        }
        final List<File> files = getFilesToProcess(cmdLine.getArgs());
        if (files.isEmpty()) {
            result.add("Must specify files to process, found 0.");
        }
    } else {
        result.add("Must specify a config XML file.");
    }

    return result;
}

From source file:edu.stanford.muse.util.Log4JUtils.java

public static synchronized void initialize() {
    // NOTE: do not use logger calls inside this method, as logging is still being set up
    if (initialized)
        return;//from w  w w  .  j a v  a 2  s .c o  m

    // LOG FILE will be set only once, either to <home>/.muse/muse.log (default) or overwritten with the help of muse.dirname and muse.log system props, typically to <home>/ePADD/epadd.log
    LOG_FILE = System.getProperty("user.home") + File.separatorChar + ".muse" + File.separatorChar + "muse.log";
    String newLogFile = System.getProperty("muse.log"); // for epadd this will be epadd.log, set in EpaddInitializer
    if (!Util.nullOrEmpty(newLogFile))
        LOG_FILE = newLogFile;

    File parent = new File(LOG_FILE).getParentFile();

    // check the parent directory of the log file first...
    // if the directory does not exist, create it
    if (!parent.exists()) {
        System.out.println("Creating " + parent);
        boolean result = parent.mkdirs();
        if (!result) {
            System.out.println("Sorry, unable to create: " + parent.getAbsolutePath());
            return;
        }
    } else if (!parent.isDirectory()) {
        System.out.println("Sorry, this needs to be a folder, not a file: " + parent.getAbsolutePath());
        return;
    } else if (!parent.canWrite()) {
        System.out.println("Sorry, this folder is not writable: " + parent.getAbsolutePath());
        return;
    }

    // now rename, truncate or create the actual log file
    try {
        /*
        try {
           File f = new File(LOG_FILE);
           if (f.exists())
           {
              // save the previous log file if it exists (shouldn't the rolling file appender take care of this??)
              RandomAccessFile raf = new RandomAccessFile(f, "rwd");
              raf.setLength(0);
              raf.close();
           }
        } catch (Exception e) { Util.print_exception(e);}
        */
        addLogFileAppender(LOG_FILE);

        // write a line so we can distinguish a new run in the log file
        String message = "________________________________________________________________________________________________ ";
        System.out.println(message);
        log.info(message);

        message = "Log messages will be recorded in " + LOG_FILE;
        System.out.println(message);
        log.info(message);
    } catch (Exception e) {
        Util.print_exception(e);
    }
    initialized = true;
}

From source file:de.willuhn.jameica.hbci.server.KontoauszugPdfUtil.java

/**
 * Loescht die angegebenen Kontoauszuege und bei Bedarf auch die Dateien.
 * @param deleteFiles true, wenn auch die Dateien geloescht werden sollen.
 * @param list die zu loeschenden Kontoauszuege.
 *//*from w  w  w  . j a v  a2 s.  c  o m*/
public static void delete(boolean deleteFiles, Kontoauszug... list) {
    if (list == null || list.length == 0)
        return;

    Kontoauszug tx = null;

    int count = 0;

    try {
        for (Kontoauszug k : list) {
            if (tx == null) {
                tx = k;
                tx.transactionBegin();
            }

            if (deleteFiles) {
                String uuid = k.getUUID();
                if (uuid != null && uuid.length() > 0) {
                    QueryMessage qm = new QueryMessage(uuid, null);
                    Application.getMessagingFactory().getMessagingQueue("jameica.messaging.del")
                            .sendSyncMessage(qm);
                } else {
                    final String pfad = k.getPfad();
                    final String name = k.getDateiname();
                    if (pfad == null || pfad.length() == 0 || name == null || name.length() == 0) {
                        Logger.warn("filename or path missing for account statements, skipping");
                    } else {
                        File file = new File(pfad, name);
                        if (file.exists() && file.canWrite()) {
                            if (!file.delete())
                                Logger.warn("deleting of file failed: " + file);
                        } else {
                            Logger.info("file does not exist, skipping: " + file);
                        }
                    }
                }
            }

            Konto konto = k.getKonto();
            konto.addToProtokoll(i18n.tr("Elektronischen Kontoauszug gelscht"), Protokoll.TYP_SUCCESS);
            k.delete();
            count++;
        }

        if (tx != null)
            tx.transactionCommit();

        if (count == 1)
            Application.getMessagingFactory().sendMessage(
                    new StatusBarMessage(i18n.tr("Kontoauszug gelscht."), StatusBarMessage.TYPE_SUCCESS));
        else
            Application.getMessagingFactory().sendMessage(
                    new StatusBarMessage(i18n.tr("{0} Kontoauszge gelscht.", Integer.toString(count)),
                            StatusBarMessage.TYPE_SUCCESS));
    } catch (Exception e) {
        Logger.error("deleting account statements failed", e);

        if (tx != null) {
            try {
                tx.transactionRollback();
            } catch (RemoteException re) {
                Logger.error("tx rollback failed", re);
            }
        }
    }
}

From source file:main.RankerOCR.java

/**
 * Evaluate any output files parameters.
 * <p>/*from   w  w w.  j  a  v a  2 s  .  c  om*/
 * @param s File path as a string
 * @param c Separator charter, require if must to create a new file
 * @return File if possible. Otherwise, stop the program and return an error
 * code
 */
private static File evalOutputFile(String s, char c) {
    File f = new File(s);
    if (!f.exists()) {
        try {
            f.createNewFile();
            //Write CSV title
            String[] t = { "Difference %", "Ranker name", "Original name", "Comparative name", "Original path",
                    "Comparative path", "Date & Time" };
            writeOutpuDocCsv(f, c, t);
        } catch (IOException ex) {
            printFormated(ex.getLocalizedMessage());
            System.exit(-35);
        }
    }
    if (!f.canWrite()) {
        printFormated("Can not write : " + s);
        System.exit(-34);
    }
    return f;
}