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.alibaba.jstorm.daemon.worker.Worker.java

public void redirectOutput() {

    if (System.getenv("REDIRECT") == null || !System.getenv("REDIRECT").equals("true")) {
        return;//from w  w w  .j  ava 2s  .  co  m
    }

    String DEFAULT_OUT_TARGET_FILE = JStormUtils.getLogFileName();
    if (DEFAULT_OUT_TARGET_FILE == null) {
        DEFAULT_OUT_TARGET_FILE = "/dev/null";
    } else {
        DEFAULT_OUT_TARGET_FILE += ".out";
    }

    String outputFile = ConfigExtension.getWorkerRedirectOutputFile(workerData.getStormConf());
    if (outputFile == null) {
        outputFile = DEFAULT_OUT_TARGET_FILE;
    } else {
        try {
            File file = new File(outputFile);
            if (file.exists() == false) {
                PathUtils.touch(outputFile);
            } else {
                if (file.isDirectory() == true) {
                    LOG.warn("Failed to write " + outputFile);
                    outputFile = DEFAULT_OUT_TARGET_FILE;
                } else if (file.canWrite() == false) {
                    LOG.warn("Failed to write " + outputFile);
                    outputFile = DEFAULT_OUT_TARGET_FILE;
                }
            }
        } catch (Exception e) {
            LOG.warn("Failed to touch " + outputFile, e);
            outputFile = DEFAULT_OUT_TARGET_FILE;
        }
    }

    try {
        JStormUtils.redirectOutput(outputFile);
    } catch (Exception e) {
        LOG.warn("Failed to redirect to " + outputFile, e);
    }

}

From source file:org.geowebcache.storage.DefaultStorageFinder.java

/**
 * Looks for <br>/*  w  ww  .  j av  a  2 s.  c o m*/
 * 1) GEOWEBCACHE_CACHE_DIR<br>
 * 2) GEOSERVER_DATA_DIR<br>
 * 3) %TEMP%, $TEMP<br>
 * <br>
 * Using<br>
 * A) Java environment variable<br>
 * B) Servlet context parameter<br>
 * C) System environment variable<br>
 * 
 */
private void determineDefaultPrefix() {
    ServletContext serlvCtx = context.getServletContext();

    final String[] typeStrs = { "Java environment variable ", "Servlet context parameter ",
            "System environment variable " };

    final String[] varStrs = { GWC_CACHE_DIR, GS_DATA_DIR, "TEMP", "TMP" };

    String msgPrefix = null;
    int iVar = 0;
    for (int i = 0; i < varStrs.length && defaultPrefix == null; i++) {
        for (int j = 0; j < typeStrs.length && defaultPrefix == null; j++) {
            String value = null;
            String varStr = varStrs[i];
            String typeStr = typeStrs[j];

            switch (j) {
            case 0:
                value = System.getProperty(varStr);
                break;
            case 1:
                value = serlvCtx.getInitParameter(varStr);
                break;
            case 2:
                value = System.getenv(varStr);
                break;
            }

            if (value == null || value.equalsIgnoreCase("")) {
                if (log.isDebugEnabled()) {
                    log.debug(typeStr + varStr + " is unset");
                }
                continue;
            }

            File fh = new File(value);

            // Being a bit pessimistic here
            msgPrefix = "Found " + typeStr + varStr + " set to " + value;

            if (!fh.exists()) {
                log.error(msgPrefix + " , but this path does not exist");
                continue;
            }
            if (!fh.isDirectory()) {
                log.error(msgPrefix + " , which is not a directory");
                continue;
            }
            if (!fh.canWrite()) {
                log.error(msgPrefix + " , which is not writeable");
                continue;
            }

            // Sweet, we can work with this
            this.defaultPrefix = value;
            iVar = i;
        }
    }
    String logMsg;

    if (this.defaultPrefix == null) {
        String tmpDir = System.getProperty("java.io.tmpdir");
        if (tmpDir != null) {
            File temp = new File(tmpDir, "geowebcache");
            logMsg = "Reverting to java.io.tmpdir " + this.defaultPrefix + " for storage. " + "Please set "
                    + GWC_CACHE_DIR + ".";
            if (!temp.exists() && !temp.mkdirs()) {
                throw new RuntimeException("Can't create " + temp.getAbsolutePath());
            }
            this.defaultPrefix = temp.getAbsolutePath();
        } else {
            logMsg = "Unable to determine temp directory. Proceeding with undefined results.";
        }
    } else {
        switch (iVar) {
        case 0: // GEOWEBCACHE_CACHE_DIR, do nothing
            break;

        case 1: // GEOSERVER_DATA_DIR, prefix
            this.defaultPrefix = this.defaultPrefix + File.separator + "gwc";
            break;

        case 2: // TEMP directories
        case 3:
            this.defaultPrefix = this.defaultPrefix + File.separator + "geowebcache";
        }

        logMsg = msgPrefix + ", using it as the default prefix.";
    }

    String warnStr = "*** " + logMsg + " ***";
    StringBuilder stars = new StringBuilder();
    for (int i = 0; i < warnStr.length(); i++) {
        stars.append("*");
    }

    log.info(stars.toString());
    log.info(warnStr);
    log.info(stars.toString());
}

From source file:fr.gouv.culture.thesaurus.autoload.VocabularyAutoload.java

/**
 * Constructeur.//from w ww  .j  a v  a2  s  .co  m
 * 
 * @param lookupDir
 *            Rpertoire  scruter
 * @param successDir
 *            rpertoire de transfert des fichiers imports avec succs
 * @param failureDir
 *            rpertoire de transfert des fichiers en checs.
 * @throws InvalidParameterException
 */
public VocabularyAutoload(File lookupDir, File successDir, File failureDir) throws InvalidParameterException {
    super();

    // Rpertoire  scruter.
    if (!lookupDir.exists() || !lookupDir.isDirectory()) {
        String message = "lookupDir n'est pas un rpertoire";
        log.error(message);
        throw new InvalidParameterException(message);
    } else if (!lookupDir.canRead() || !lookupDir.canWrite()) {
        String message = "lookupDir n'est pas accessible en lecture et/ou en criture";
        log.error(message);
        throw new InvalidParameterException(message);
    }
    this.lookupDir = lookupDir;

    // Rpertoire de succs
    checkMoveDir(successDir, "successDir");
    this.successDir = successDir;

    // Rpertoire d'chec
    checkMoveDir(failureDir, "failureDir");
    this.failureDir = failureDir;

    // Fichier de lock.
    lockFile = new File(this.lookupDir, LOCK_FILE);
    if (log.isInfoEnabled()) {
        log.info("Scrutation active pour l'ajout automatique de vocabulaires :");
        log.info("\tRpertoire scrut : " + this.lookupDir.getAbsolutePath());
        log.info("\tRpertoire de dplacement des vocabulaires traits avec succs : "
                + this.successDir.getAbsolutePath());
        log.info("\tRpertoire de dplacement des vocabulaires en chec : "
                + this.failureDir.getAbsolutePath());
        log.info(
                "\tNom du fichier de lock utilis (si ce fichier existe, l'ajout automatique est dsactiv le temps de son existence) : "
                        + this.lockFile.getAbsolutePath());
        log.info("\tIntervalle de scrutation (dfaut): " + this.sleepTime + "ms");
        log.info("\tNombre de scrutations avant chec (dfaut): " + this.maxTriesByFile);
    }
}

From source file:io.manasobi.utils.FileUtils.java

/**
 * ? ?? outputStream . append true?   ??  ? ??.
 * //from  ww w  .ja va2  s .  c  o m
 * @param file   ? ?
 * @param append  ?? ? ???  
 * @return ? ??  FileOutputStream
 */
public static FileOutputStream openOutputStream(File file, boolean append) {

    if (file.exists()) {

        if (file.isDirectory()) {
            return null;
        }
        if (!file.canWrite()) {
            return null;
        }
    } else {
        File parent = file.getParentFile();
        if (parent != null) {
            if (!parent.mkdirs() && !parent.isDirectory()) {
                return null;
            }
        }
    }

    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(file, append);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fos;
}

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

/**
 * Check if the directory exists and is writable and create it if needed.
 * The complete path down to the directory is created. If the directory
 * creation fails a PermissionDenied exception is thrown.
 *
 * @param dir The directory to create//  w  w w  . j  ava  2  s  .c om
 * @throws ArgumentNotValid If dir is null or its name is the empty string
 * @throws PermissionDenied If directory cannot be created for any reason,
 * or is not writable.
 * @return true if dir created.
 */
public static boolean createDir(File dir) throws PermissionDenied {
    ArgumentNotValid.checkNotNull(dir, "File dir");
    ArgumentNotValid.checkNotNullOrEmpty(dir.getName(), "File dir");
    boolean didCreate = false;
    if (!dir.exists()) {
        didCreate = true;
        int i = 0;
        //retrying creation due to sun bug (race condition)
        //See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4742723
        while ((i++ < CREATE_DIR_RETRIES) && !(dir.isDirectory() && dir.canWrite())) {
            dir.mkdirs();
        }
        if (!(dir.isDirectory() && dir.canWrite())) {
            String msg = "Could not create directory '" + dir.getAbsolutePath() + "'";
            log.warn(msg);
            throw new PermissionDenied(msg);
        }
    } else {
        if (!dir.isDirectory()) {
            String msg = "Cannot make directory '" + dir.getAbsolutePath() + "' - a file is in the way";
            log.warn(msg);
            throw new PermissionDenied(msg);
        }
    }
    if (!dir.canWrite()) {
        String msg = "Cannot write to required directory '" + dir.getAbsolutePath() + "'";
        log.warn(msg);
        throw new PermissionDenied(msg);
    }
    return didCreate;
}

From source file:fr.gouv.culture.thesaurus.autoload.VocabularyAutoload.java

/**
 * Vrifie qu'un rpertoire de destination (succs ou chec) existe (le cr
 * sinon), est un rpertoire et est accessible en criture.
 * /*from   ww  w.  j a  v a  2s.co  m*/
 * @param moveDir
 *            le repertoire  vrifier.
 * @param propertyName
 *            Le nom de la proprit (pour les logs)
 * @throws InvalidParameterException
 *             Si le repertoire n'est pas un rpertoire ou n'est pas
 *             accessible en criture.
 */
private void checkMoveDir(File moveDir, String propertyName) throws InvalidParameterException {
    if (!moveDir.exists()) {
        log.warn(propertyName + " n'existe pas et va tre cr");
        moveDir.mkdir();
    } else if (!moveDir.isDirectory()) {
        String message = propertyName + " n'est pas un rpertoire";
        log.error(message);
        throw new InvalidParameterException(message);
    } else if (!moveDir.canWrite()) {
        String message = propertyName + " n'est pas accessible en criture";
        log.error(message);
        throw new InvalidParameterException(message);
    }
}

From source file:io.manasobi.utils.FileUtils.java

/**
* ? ?? FileWriter . append true?   ??  ? ??.
* 
* @param file ? ?//from w w  w. j  a va  2s .  c  o  m
* @param append  ?? ? ???  
* @return ? ??  FileWriter
*/
public static FileWriter openWriter(File file, boolean append) {

    if (file.exists()) {

        if (file.isDirectory()) {
            return null;
        }
        if (!file.canWrite()) {
            return null;
        }
    } else {

        File parent = file.getParentFile();

        if (parent != null) {

            if (!parent.mkdirs() && !parent.isDirectory()) {
                return null;
            }
        }
    }

    FileWriter fileWriter = null;

    try {
        fileWriter = new FileWriter(file, append);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fileWriter;
}

From source file:de.vandermeer.skb.mvn.pm.model.ModelLoader.java

/**
 * Tests the project directory./*from  w  w  w . ja  v a  2  s. co  m*/
 * @param prjDir the project directory to test
 * @return errors if any occurred, empty if all was ok
 */
protected StrBuilder testProjectDirectory(File prjDir) {
    StrBuilder errors = new StrBuilder();

    //do individual texts to provide specific error messages (is there are better way to do that?)
    if (!prjDir.exists()) {
        errors.append("project directory does not exist: <").append(prjDir).append('>').appendNewLine();
    } else if (!prjDir.isDirectory()) {
        errors.append("project directory is not a directory: <").append(prjDir).append('>').appendNewLine();
    } else if (!prjDir.canRead()) {
        errors.append("project directory not readable: <").append(prjDir).append('>').appendNewLine();
    } else if (!prjDir.canWrite()) {
        errors.append("project directory not writable: <").append(prjDir).append('>').appendNewLine();
    }

    return errors;
}

From source file:edu.stanford.nlp.parser.ensemble.Ensemble.java

public Ensemble(String[] args) {
    Arguments.parse(args, this);
    SystemLogger.instance().setSystemVerbosityLevel(logLevel);

    ///*from  www  . j a v a2 s . c  om*/
    // sanity checks
    //
    File md = new File(modelDirectory);
    if (!md.exists()) {
        throw new RuntimeException("ERROR: Model directory " + md.getAbsolutePath() + " does not exist!");
    }
    if (!md.isDirectory()) {
        throw new RuntimeException("ERROR: Model directory " + md.getAbsolutePath() + " is not a directory!");
    }
    if (!md.canWrite()) {
        throw new RuntimeException(
                "ERROR: Must have write permission to model directory " + md.getAbsolutePath() + "!");
    }

    File wd = new File(workingDirectory);
    if (!wd.exists()) {
        throw new RuntimeException("ERROR: Working directory " + wd.getAbsolutePath() + " does not exist!");
    }
    if (!wd.isDirectory()) {
        throw new RuntimeException("ERROR: Working directory " + wd.getAbsolutePath() + " is not a directory!");
    }
    if (!wd.canWrite()) {
        throw new RuntimeException(
                "ERROR: Must have write permission to working directory " + wd.getAbsolutePath() + "!");
    }

    baseModels = baseModelNames.split(",");

    int len = baseModels.length;
    featureModels = new String[len];
    String[] models = featureModelNames.split(",");
    for (int i = 0; i < len; i++) {
        if (i < models.length) {
            featureModels[i] = models[i];
        } else {
            featureModels[i] = "<default>";
        }
    }

    rightToLeft = false;
    rtl_pseudo_projective = false;
    ltr_pseudo_projective = false;
    for (String bm : baseModels) {
        if (!BASE_MODELS.contains(bm)) {
            throw new RuntimeException("Unknown base model: " + bm);
        }
        if (bm.lastIndexOf("rtl") != -1) {
            rightToLeft = true;

            if (bm.endsWith("+PP")) {
                rtl_pseudo_projective = true;
            }
        } else if (bm.endsWith("+PP")) {
            ltr_pseudo_projective = true;
        }
    }

    if (!run.equals(Const.RUN_TEST) && !run.equals(Const.RUN_TRAIN)) {
        throw new RuntimeException("Unknown run mode: " + run);
    }

    if (run.equalsIgnoreCase(Const.RUN_TRAIN)) {
        if (trainCorpus == null) {
            throw new RuntimeException("Training corpus must be specified if --run train!");
        }
        File f = new File(trainCorpus);
        if (!f.exists()) {
            throw new RuntimeException("ERROR: Training corpus " + f.getAbsolutePath() + " does not exist!");
        }
        if (!f.isFile()) {
            throw new RuntimeException("ERROR: Training corpus " + f.getAbsolutePath() + " is not a file!");
        }
        if (!f.canRead()) {
            throw new RuntimeException(
                    "ERROR: Must have read permission to training corpus " + f.getAbsolutePath() + "!");
        }
        SystemLogger.logger().info("Will run in TRAIN mode.\n");
    }
    if (run.equalsIgnoreCase(Const.RUN_TEST)) {
        if (testCorpus == null) {
            throw new RuntimeException("Test corpus must be specified if --run test!");
        }
        File f = new File(testCorpus);
        if (!f.exists()) {
            throw new RuntimeException("ERROR: Test corpus " + f.getAbsolutePath() + " does not exist!");
        }
        if (!f.isFile()) {
            throw new RuntimeException("ERROR: Test corpus " + f.getAbsolutePath() + " is not a file!");
        }
        if (!f.canRead()) {
            throw new RuntimeException(
                    "ERROR: Must have read permission to test corpus " + f.getAbsolutePath() + "!");
        }
        SystemLogger.logger().info("Will run in TEST mode.\n");
    }
}

From source file:com.wirelessmoves.cl.MainActivity.java

private void saveCellChangeKMLDataToFile(String LocalCellChangeKmlWriteBuffer) {
    /* write measurement data to the output file */
    try {/*w w w . ja v a 2s  . c o m*/
        File root = Environment.getExternalStorageDirectory();
        if (root.canWrite()) {
            File logfile = new File(root, cellChangeFileName);
            FileWriter logwriter = new FileWriter(logfile, true); /* true = append */
            BufferedWriter out = new BufferedWriter(logwriter);

            out.write(LocalCellChangeKmlWriteBuffer);
            out.close();
        }
    } catch (IOException e) {
        /* don't do anything for the moment */
    }
}