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:dk.netarkivet.archive.bitarchive.distribute.BitarchiveServer.java

/**
 * The server creates an instance of the bitarchive it provides access to
 * and starts to listen to JMS messages on the incomming jms queue
 * <p/>/*from   w  w  w .  j  av a2s  .  co  m*/
 * Also, heartbeats are sent out at regular intervals to the Bitarchive
 * Monitor, to tell that this bitarchive is alive.
 *
 * @throws UnknownID        - if there was no heartbeat frequency or temp
 *                            dir defined in settings or if the
 *                            bitarchiveid cannot be created.
 * @throws PermissionDenied - if the temporary directory or the file
 *                            directory cannot be written
 */
private BitarchiveServer() throws UnknownID, PermissionDenied {
    System.setOut(
            new PrintStream(new LoggingOutputStream(LoggingOutputStream.LoggingLevel.INFO, log, "StdOut: ")));
    System.setErr(
            new PrintStream(new LoggingOutputStream(LoggingOutputStream.LoggingLevel.WARN, log, "StdErr: ")));
    boolean listening = false; // are we listening to queue ANY_BA
    File serverdir = FileUtils.getTempDir();
    if (!serverdir.exists()) {
        serverdir.mkdirs();
    }
    if (!serverdir.canWrite()) {
        throw new PermissionDenied("Not allowed to write to temp directory '" + serverdir + "'");
    }
    log.info("Storing temporary files at '" + serverdir.getPath() + "'");

    bitarchiveAppId = createBitarchiveAppId();

    allBa = Channels.getAllBa();
    anyBa = Channels.getAnyBa();
    baMon = Channels.getTheBamon();
    ba = Bitarchive.getInstance();
    con = JMSConnectionFactory.getInstance();
    con.setListener(allBa, this);
    baa = BitarchiveAdmin.getInstance();
    if (baa.hasEnoughSpace()) {
        con.setListener(anyBa, this);
        listening = true;
    } else {
        log.warn("Not enough space to guarantee store -- not listening " + "to " + anyBa.getName());
    }

    // create map for batchjobs
    batchProcesses = Collections.synchronizedMap(new HashMap<String, Thread>());

    // Create and start the heartbeat sender
    Timer timer = new Timer(true);
    heartBeatSender = new HeartBeatSender(baMon, this);
    long frequency = Settings.getLong(ArchiveSettings.BITARCHIVE_HEARTBEAT_FREQUENCY);
    timer.scheduleAtFixedRate(heartBeatSender, 0, frequency);
    log.info("Heartbeat frequency: '" + frequency + "'");
    // Next logentry depends on whether we are listening to ANY_BA or not
    String logmsg = "Created bitarchive server listening on: " + allBa.getName();
    if (listening) {
        logmsg += " and " + anyBa.getName();
    }

    log.info(logmsg);

    log.info("Broadcasting heartbeats on: " + baMon.getName());
}

From source file:net.sourceforge.jencrypt.CommandLineHelper.java

/**
 * Check if the decryption destination directory, base directory and key
 * file exists.//from   w  w  w . j  a v  a2  s  .c o m
 * 
 * @throws IOException
 */
public boolean isValid() throws IOException {

    // Cipheroptions contains -end or -dec
    if (cipherOptions != null && configFileString != null && passwordString != null) {

        File source = new File(sourceFileOrFolder);

        if (this.getCipherMode() == Cipher.DECRYPT_MODE) {

            if (targetPath == "") {
                targetPath = System.getProperty("user.dir");
            }
            File target = new File(targetPath);

            if (!source.exists()) {
                throw new IOException("Source archive '" + sourceFileOrFolder + "' does not exist.");
            } else if (!source.isFile()) {
                throw new IOException("Source archive '" + sourceFileOrFolder + "' is not a file");
            }

            if (!target.exists() || !target.canWrite()) {
                throw new IOException("Destination '" + target.getName() + "' not found or access denied");
            }

        }

        if (this.getCipherMode() == Cipher.ENCRYPT_MODE) {

            File targetFile = new File(targetPath);

            if (targetFile.isDirectory()) {
                throw new IOException("Destination '" + targetFile.getName() + "' is not a file");
            } else if (targetFile.exists()) {
                throw new IOException("File '" + targetFile.getName() + "' already exists");
            } else {
                try {
                    targetFile.createNewFile();
                } catch (IOException e) {
                    throw new SecurityException("Can't create file '" + targetPath + "': " + e.getMessage());
                } finally {
                    targetFile.delete();
                }
            }
            if (!source.exists() || !source.canRead()) {
                throw new IOException(
                        "Folder to encrypt '" + source.getName() + "' not found or access denied");
            }
        }

        return true;
    }
    return false;
}

From source file:net.sf.ginp.setup.SetupManagerImpl.java

/**
 * @param sampleConfig//from ww w.j a  va 2s .com
 * @return
 * @see net.sf.ginp.setup.SetupManager#getDirectoriesInPictureDirectory(
 * net.sf.ginp.setup.data.SetupVisit)
 */
public final List getDirectoriesInPictureDirectory(final SetupVisit sampleConfig) {
    File dir = new File(sampleConfig.getGinpPhotosPath());
    String[] strings = dir.list();
    ArrayList directories = new ArrayList();

    for (int x = 0; x < strings.length; x++) {
        String path = sampleConfig.getGinpPhotosPath() + System.getProperty("file.separator") + strings[x];
        File file = new File(path);

        if (!file.exists()) {
            path = sampleConfig.getGinpPhotosPath() + strings[x];
            file = new File(path);
        }

        if (file.canRead() && file.canWrite() && file.isDirectory()) {
            directories.add(file);
        }
    }

    return directories;
}

From source file:com.cedarsoft.app.DefaultApplicationHomeAccess.java

/**
 * Create a new application home access//from  w ww.  j  a  v a  2s  .c om
 *
 * @param applicationHome the application home
 * @param applicationName the application name
 * @throws IOException if any.
 */
public DefaultApplicationHomeAccess(@Nonnull File applicationHome, @Nonnull String applicationName)
        throws IOException {
    if (applicationName.length() < 3) {
        throw new IllegalArgumentException("application name is too short: " + applicationName);
    }
    this.applicationHome = applicationHome;
    this.applicationName = applicationName;

    if (!applicationHome.exists() || !applicationHome.isDirectory()) {
        applicationHome.mkdirs();
        LOG.info("Creating Application Directory: " + applicationHome.getAbsolutePath());
    }
    if (!applicationHome.canWrite()) {
        throw new IOException("Cannot write " + applicationHome.getAbsolutePath());
    }
}

From source file:cat.calidos.morfeu.utils.FileSaver.java

public void save() throws SavingException {

    File destinationFile = new File(destination);
    if (destinationFile.isDirectory()) {
        log.error("Cannot save to '{}' as it is a folder and not a file", destination);
        throw new SavingException("Could not save to '" + destination + "' as it is a folder and not a file");
    }//w  ww. jav a  2  s.  c  om

    try {
        FileUtils.touch(destinationFile);
    } catch (IOException e) {
        log.error("Cannot save to '{}' as we cannot even touch it", destination);
        throw new SavingException("Could not save to '" + destination + "' as we cannot write to it", e);
    }
    if (!destinationFile.canWrite()) {
        log.error("Cannot save to '{}' as we cannot write to it", destination);
        throw new SavingException("Could not save to '" + destination + "' as we cannot write to it");
    }
    if (destinationFile.exists()) {
        String backupPath = destinationFile.getAbsolutePath() + BACKUP_EXTENSION;
        log.info("Renaming old '{}' to '{}'", destination, backupPath);
        File backupFile = new File(backupPath);
        if (backupFile.exists()) {
            backupFile.delete();
        }
        destinationFile.renameTo(backupFile);
    }

    try {
        FileUtils.writeStringToFile(destinationFile, content, Config.DEFAULT_CHARSET);
    } catch (IOException e) {
        log.error("Removing old '{}' to replace it with new content", destination);
        throw new SavingException("Could not save to '" + destination + "' due to IO problems", e);
    }

}

From source file:com.eviware.soapui.DefaultSoapUICore.java

public String saveSettings() throws Exception {
    PropertyExpansionUtils.saveGlobalProperties();
    SecurityScanUtil.saveGlobalSecuritySettings();
    isSavingSettings = true;//  w w w.jav a  2 s.c om
    try {
        if (settingsFile == null)
            settingsFile = getRoot() + File.separatorChar + DEFAULT_SETTINGS_FILE;

        // Save settings to root or user.home
        File file = new File(settingsFile);
        if (!file.canWrite()) {
            file = new File(new File(System.getProperty("user.home", ".")), DEFAULT_SETTINGS_FILE);
        }

        SoapuiSettingsDocumentConfig settingsDocument = (SoapuiSettingsDocumentConfig) this.settingsDocument
                .copy();
        String password = settings.getString(SecuritySettings.SHADOW_PASSWORD, null);

        if (password != null && password.length() > 0) {
            try {
                byte[] data = settingsDocument.xmlText().getBytes();
                byte[] encryptedData = OpenSSL.encrypt("des3", password.toCharArray(), data);
                settingsDocument.setSoapuiSettings(null);
                settingsDocument.getSoapuiSettings().setEncryptedContent(encryptedData);
            } catch (UnsupportedEncodingException e) {
                log.error("Encryption error", e);
            } catch (IOException e) {
                log.error("Encryption error", e);
            } catch (GeneralSecurityException e) {
                log.error("Encryption error", e);
            }
        }

        FileOutputStream out = new FileOutputStream(file);
        settingsDocument.save(out);
        out.flush();
        out.close();
        log.info("Settings saved to [" + file.getAbsolutePath() + "]");
        lastSettingsLoad = file.lastModified();
        return file.getAbsolutePath();
    } finally {
        isSavingSettings = false;
    }
}

From source file:dk.netarkivet.archive.checksum.DatabaseChecksumArchive.java

private boolean checkDatabaseDir(File file) {
    // The file must exist.
    if (!file.isDirectory()) {
        log.warn("The file '{}' is not a valid directory.", file.getAbsolutePath());
        return false;
    }/*  w w w .  ja va2  s . c  o  m*/
    // It must be writable.
    if (!file.canWrite()) {
        log.warn("The directory '{}' is not writable", file.getAbsolutePath());
        return false;
    }
    return true;
}

From source file:com.evolveum.midpoint.tools.schemadist.SchemaDistMojo.java

private File initializeOutDir(File dir) throws MojoFailureException {
    getLog().info("Output dir: " + dir);
    if (dir.exists() && !dir.isDirectory()) {
        throw new MojoFailureException("Output directory is not a directory: " + dir);
    }/*from   w ww  .  j a v a  2 s  .  c  o m*/
    if (dir.exists() && !dir.canWrite()) {
        throw new MojoFailureException("Output directory is not writable: " + dir);
    }
    dir.mkdirs();
    return dir;
}

From source file:de.lmu.ifi.dbs.jfeaturelib.utils.Extractor.java

/**
 * Validates the input parameters like descriptor names (nullchecks) and ensures that the required files and
 * directories are existent./*from   www .  j a  v a  2s.co  m*/
 *
 * @throws IllegalArgumentException
 */
private void validateInput() throws IllegalArgumentException {
    log.debug("validating");
    if (descriptor == null) {
        throw new NullPointerException("descriptor must not be null");
    }

    try { // check if the descriptor class is valid
        String base = FeatureDescriptor.class.getPackage().getName();
        descriptorClazz = Class.forName(base + "." + descriptor);
        if (!FeatureDescriptor.class.isAssignableFrom(descriptorClazz)) {
            throw new IllegalArgumentException("The class must derive from FeatureDescriptor");
        }

        // check if masking is required and supported
        FeatureDescriptor fd = (FeatureDescriptor) descriptorClazz.newInstance();
        boolean supportsMasking = fd.supports().contains(Supports.Masking);
        if (maskDirectory != null && !supportsMasking) {
            log.warn(
                    "A masking directory is set but the chosen descriptor does NOT support masking. Masking will be ignored!");
            maskDirectory = null;
        }
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
        log.warn(ex.getMessage(), ex);
        throw new IllegalArgumentException("the descriptor class does not exist or cannot be created");
    }

    // can the image directory be accessed
    if (imageDirectory == null || !imageDirectory.isDirectory() || !imageDirectory.canRead()) {
        throw new IllegalArgumentException("the source directory cannot be read or does not exist");
    }

    // can the mask directory be accessed
    if (maskDirectory != null && (!maskDirectory.isDirectory() || !maskDirectory.canRead())) {
        throw new IllegalArgumentException("the mask directory cannot be read or does not exist");
    }

    // can the output file be written?
    if (outFile == null) {
        throw new IllegalArgumentException("the output file is not valid");
    }
    // further check the file if it is not stdout
    if (!outFile.equals("-")) {
        File f = new File(outFile);
        if (f.exists() && !f.canWrite()) {
            throw new IllegalArgumentException("the output file is not valid or not writable");
        }
        try { // create the output file or fail
            if (!outFile.equals("-")) {
                new File(outFile).createNewFile();
                fileExists = (f.exists() && f.length() > 0);
            }
        } catch (IOException ex) {
            log.warn(ex.getMessage(), ex);
            throw new IllegalArgumentException("the output file could not be created");
        }
    }

    // check if an image class is set and valid
    if (imageClass != null && !imageClass.matches("^\\w+$")) {
        throw new IllegalArgumentException(
                "the image class must only contain word characters and not whitespace");
    }
}

From source file:com.ctriposs.rest4j.tools.idlgen.Rest4JResourceModelExporter.java

private GeneratorResult generateIDLFiles(String apiName, String outdir,
        Map<String, ResourceModel> rootResourceMap, DocsProvider docsProvider) throws IOException {
    Result result = new Result();

    final File outdirFile = new File(outdir);
    if (!outdirFile.exists()) {
        if (!outdirFile.mkdirs()) {
            throw new RuntimeException("Output directory '" + outdir + "' could not be created!");
        }//  ww w.  java 2 s  .  c o  m
    }
    if (!outdirFile.isDirectory()) {
        throw new RuntimeException("Output directory '" + outdir + "' is not a directory");
    }
    if (!outdirFile.canRead() || !outdirFile.canWrite()) {
        throw new RuntimeException("Output directory '" + outdir + "' must be writeable");
    }

    final ResourceModelEncoder encoder = new ResourceModelEncoder(docsProvider);

    final List<ResourceSchema> rootResourceNodes = new ArrayList<ResourceSchema>();
    for (Entry<String, ResourceModel> entry : rootResourceMap.entrySet()) {
        final ResourceSchema rootResourceNode = encoder.buildResourceSchema(entry.getValue());
        rootResourceNodes.add(rootResourceNode);
    }

    for (ResourceSchema rootResourceNode : rootResourceNodes) {
        String fileName = rootResourceNode.getName();
        if (rootResourceNode.getNamespace() != null) {
            final String namespace = rootResourceNode.getNamespace();
            fileName = namespace + "." + fileName;
        }
        if (apiName != null && !apiName.isEmpty()) {
            fileName = apiName + "-" + fileName;
        }

        File writtenFile = writeIDLFile(outdirFile, fileName, rootResourceNode);
        result.addModifiedFile(writtenFile);
        result.addTargetFile(writtenFile);
    }

    return result;
}