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.ironiacorp.scm.fs.FilesystemRepositoryTransaction.java

/**
 * Set the repository directory. The directory will be created if it does
 * not exist.//from ww w .j a  v a 2s .  com
 * 
 * @param repdir Directory that holds the project's files.
 * 
 * @throws RepositoryTransactionError If the directory cannot be used.
 */
protected void setRepdir(String repdir) {
    File dir = new File(repdir);
    if (dir.exists() && !dir.isDirectory()) {
        throw new RepositoryTransactionError("exception.repositoryTransaction.invalidWorkdir");
    }
    try {
        dir.mkdirs();
        dir.canWrite();
    } catch (SecurityException se) {
        throw new RepositoryTransactionError("exception.repositoryTransaction.invalidWorkdir");
    }
    this.repdir = repdir;
}

From source file:de.uniwue.info6.misc.properties.Cfg.java

/**
 *
 *
 * @param property/*  ww w. j a  v a  2 s .co  m*/
 */
private void checkIfValidPropertiesFile(File property) {
    if (!property.exists() || !property.isFile()) {
        throw new IllegalArgumentException(
                "Not a valid property file: \"" + property.getAbsolutePath() + "\"\n");
    } else if (!property.canRead() || !property.canWrite()) {
        throw new IllegalArgumentException("Check writing and reading permissions for property file: \""
                + property.getAbsolutePath() + "\"\n");
    }
}

From source file:net.urlgrey.mythpodcaster.transcode.FeedFileAccessorImpl.java

/**
 * @param seriesId//from   ww w.j a  v a 2 s.co m
 * @param transcodingProfileId
 * @param feed
 */
@SuppressWarnings("rawtypes")
public void purgeFeed(String seriesId, String transcodingProfileId, SyndFeed feed) {
    final File encodingDirectory = new File(feedFilePath, transcodingProfileId);

    // delete feed
    final File feedFile = new File(encodingDirectory, seriesId + feedFileExtension);
    if (feedFile.canWrite()) {
        feedFile.delete();
    }

    // delete feed thumbnail
    final File feedThumbnail = new File(encodingDirectory, seriesId + PNG_EXTENSION);
    if (feedThumbnail.canWrite()) {
        feedThumbnail.delete();
    }

    // delete feed transformation
    final File feedTransformationFile = new File(encodingDirectory,
            seriesId + feedTransformationOutputFileExtension);
    if (feedTransformationFile.canWrite()) {
        feedTransformationFile.delete();
    }

    if (feed != null) {
        final Iterator it = feed.getEntries().iterator();
        while (it.hasNext()) {
            SyndEntry entry = (SyndEntry) it.next();
            final List enclosures = entry.getEnclosures();
            if (enclosures.size() > 0) {
                Iterator enclosureIterator = enclosures.iterator();
                while (enclosureIterator.hasNext()) {
                    SyndEnclosure enclosure = (SyndEnclosure) enclosureIterator.next();
                    String encUrl = enclosure.getUrl();
                    encUrl = encUrl.substring(encUrl.lastIndexOf('/') + 1);

                    final TranscodingProfile profile = transcodingProfilesDao.findAllProfiles()
                            .get(transcodingProfileId);
                    if (profile != null) {
                        profile.deleteEncoding(this.feedFilePath, enclosure.getUrl(), entry.getUri());
                    } else {
                        // fabricate a profile for the purpose of deleting the encoding output
                        final TranscodingProfile fakeProfile = new TranscodingProfile();
                        fakeProfile.setId(transcodingProfileId);
                        if (enclosure.getUrl().endsWith(".m3u8")) {
                            fakeProfile.setMode(TranscoderType.ONE_PASS_HTTP_SEGMENTED_VOD);
                        } else {
                            fakeProfile.setMode(TranscoderType.ONE_PASS);
                        }

                        fakeProfile.deleteEncoding(this.feedFilePath, enclosure.getUrl(), entry.getUri());
                    }
                }
            } else {
                LOGGER.debug("No enclosures specified in the entry, continuing");
                continue;
            }
        }
    }

    // delete the encoding profile directory if it is empty following the purge
    if (encodingDirectory.list().length == 0) {
        LOGGER.info("Deleting empty encoding profile directory: " + encodingDirectory.getAbsolutePath());
        encodingDirectory.delete();
    }
}

From source file:org.openmeetings.servlet.outputhandler.Install.java

@Override
public Template handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
        Context ctx) {//from ww  w . j av a  2s  . co m

    try {
        ctx.put("APP_ROOT", OpenmeetingsVariables.webAppRootKey);

        if (getImportInitvalues() == null || getConfigurationmanagement() == null) {
            return getVelocityView().getVelocityEngine().getTemplate("booting_install.vm");
        }

        ctx.put("APP_NAME", getConfigurationmanagement().getAppName());
        String command = httpServletRequest.getParameter("command");

        String lang = httpServletRequest.getParameter("lang");
        if (lang == null)
            lang = "EN";

        String working_dir = getServletContext().getRealPath("/") + ScopeApplicationAdapter.configDirName
                + File.separatorChar;

        File installerFile = new File(working_dir, InstallationDocumentHandler.installFileName);

        if (command == null || !installerFile.exists()) {
            log.debug("command equals null");

            if (!installerFile.exists()) {

                File installerdir = new File(working_dir);

                log.debug("bb " + installerFile);

                boolean b = installerdir.canWrite();

                if (!b) {
                    // File could not be created so throw an error
                    ctx.put("error", "Could not Create File, Permission set? ");
                    ctx.put("path", working_dir);
                    return getVelocityView().getVelocityEngine().getTemplate("install_error_" + lang + ".vm");
                } else {
                    InstallationDocumentHandler.getInstance()
                            .createDocument(working_dir + InstallationDocumentHandler.installFileName, 0);
                    // File has been created so follow first step of
                    // Installation
                    return getVelocityView().getVelocityEngine().getTemplate("install_welcome_" + lang + ".vm");
                }

            } else {
                int i = InstallationDocumentHandler.getInstance().getCurrentStepNumber(working_dir);
                if (i == 0) {
                    return getStep2Template(httpServletRequest, ctx, lang);
                } else {
                    return getVelocityView().getVelocityEngine().getTemplate("install_step2_" + lang + ".vm");
                }
            }

        } else if (command.equals("step1")) {

            int i = InstallationDocumentHandler.getInstance().getCurrentStepNumber(working_dir);
            if (i == 0) {
                return getStep2Template(httpServletRequest, ctx, lang);
            } else {
                ctx.put("error",
                        "This Step of the installation has already been done. continue with step 2 <A HREF='?command=step2'>continue with step 2</A>");
                return getVelocityView().getVelocityEngine().getTemplate("install_exception_" + lang + ".vm");
            }

        } else if (command.equals("step2")) {

            int i = InstallationDocumentHandler.getInstance().getCurrentStepNumber(working_dir);
            if (i == 0) {

                log.debug("do init installation");

                String username = httpServletRequest.getParameter("username");
                String userpass = httpServletRequest.getParameter("userpass");
                String useremail = httpServletRequest.getParameter("useremail");
                String orgname = httpServletRequest.getParameter("orgname");
                InstallationConfig cfg = new InstallationConfig();
                cfg.allowFrontendRegister = httpServletRequest.getParameter("configdefault");

                cfg.mailReferer = httpServletRequest.getParameter("configreferer");
                cfg.smtpServer = httpServletRequest.getParameter("configsmtp");
                cfg.smtpPort = httpServletRequest.getParameter("configsmtpport");
                cfg.mailAuthName = httpServletRequest.getParameter("configmailuser");
                cfg.mailAuthPass = httpServletRequest.getParameter("configmailpass");
                cfg.mailUseTls = httpServletRequest.getParameter("mailusetls");
                cfg.replyToOrganizer = httpServletRequest.getParameter("replyToOrganizer");

                cfg.defaultLangId = httpServletRequest.getParameter("configdefaultLang");
                cfg.swfZoom = httpServletRequest.getParameter("swftools_zoom");
                cfg.swfJpegQuality = httpServletRequest.getParameter("swftools_jpegquality");
                cfg.swfPath = httpServletRequest.getParameter("swftools_path");
                cfg.imageMagicPath = httpServletRequest.getParameter("imagemagick_path");
                cfg.sendEmailAtRegister = httpServletRequest.getParameter("sendEmailAtRegister");
                cfg.sendEmailWithVerficationCode = httpServletRequest
                        .getParameter("sendEmailWithVerficationCode");
                cfg.createDefaultRooms = httpServletRequest.getParameter("createDefaultRooms");

                cfg.defaultExportFont = httpServletRequest.getParameter("default_export_font");

                cfg.cryptClassName = httpServletRequest.getParameter("crypt_ClassName");

                cfg.ffmpegPath = httpServletRequest.getParameter("ffmpeg_path");

                cfg.soxPath = httpServletRequest.getParameter("sox_path");

                cfg.screenViewer = httpServletRequest.getParameter("screen_viewer");

                // red5sip integration config
                cfg.red5SipEnable = httpServletRequest.getParameter("red5sip_enable");
                cfg.red5SipRoomPrefix = httpServletRequest.getParameter("red5sip_room_prefix");
                cfg.red5SipExtenContext = httpServletRequest.getParameter("red5sip_exten_context");

                // SIP Applet Configuration
                cfg.sipEnable = httpServletRequest.getParameter("sip_enable");
                cfg.sipRealm = httpServletRequest.getParameter("sip_realm");
                cfg.sipPort = httpServletRequest.getParameter("sip_port");
                cfg.sipProxyName = httpServletRequest.getParameter("sip_proxyname");
                cfg.sipTunnel = httpServletRequest.getParameter("sip_tunnel");
                cfg.sipCodebase = httpServletRequest.getParameter("sip_codebase");
                cfg.sipForceTunnel = httpServletRequest.getParameter("sip_forcetunnel");

                // OpenXG / OpenSIPg Configuration
                cfg.sipOpenxgEnable = httpServletRequest.getParameter("sip_openxg_enable");
                cfg.openxgWrapperUrl = httpServletRequest.getParameter("openxg_wrapper_url");
                cfg.openxgClientId = httpServletRequest.getParameter("openxg_client_id");
                cfg.openxgClientSecret = httpServletRequest.getParameter("openxg_client_secret");
                cfg.openxgClientDomain = httpServletRequest.getParameter("openxg_client_domain");
                cfg.openxgCommunityCode = httpServletRequest.getParameter("openxg_community_code");
                cfg.openxgLanguageCode = httpServletRequest.getParameter("openxg_language_code");
                cfg.openxgAdminId = httpServletRequest.getParameter("openxg_adminid");

                // SIP Phone Range Configuration
                cfg.sipLanguagePhoneCode = httpServletRequest.getParameter("sip_language_phonecode");
                cfg.sipPhoneRangeStart = httpServletRequest.getParameter("sip_phonerange_start");
                cfg.sipPhoneRange = httpServletRequest.getParameter("sip_phonerange");

                String timeZone = httpServletRequest.getParameter("timeZone");
                cfg.ical_timeZone = timeZone;

                cfg.jodPath = httpServletRequest.getParameter("jod_path");

                log.debug("step 0+ start init with values. " + username + " ***** " + useremail + " " + orgname
                        + " " + cfg);

                String filePath = getServletContext().getRealPath("/") + ImportInitvalues.languageFolderName;

                cfg.urlFeed = getServletContext().getInitParameter("url_feed");
                cfg.urlFeed2 = getServletContext().getInitParameter("url_feed2");

                getImportInitvalues().loadAll(filePath, cfg, username, userpass, useremail, orgname, timeZone,
                        false);

                // update to next step
                log.debug("add level to install file");
                InstallationDocumentHandler.getInstance()
                        .createDocument(working_dir + InstallationDocumentHandler.installFileName, 1);

                // return
                // getVelocityEngine().getTemplate("install_complete_"+lang+".vm");
                return getVelocityView().getVelocityEngine().getTemplate("install_step2_" + lang + ".vm");
            } else {
                ctx.put("error",
                        "This Step of the installation has already been done. continue with step 2 <A HREF='?command=step2'>continue with step 2</A>");
                return getVelocityView().getVelocityEngine().getTemplate("install_exception_" + lang + ".vm");
            }

        } else if (command.equals("step")) {

            int i = InstallationDocumentHandler.getInstance().getCurrentStepNumber(working_dir);
            if (i == 0) {

            }

        }

    } catch (IOException err) {
        log.error("Install: ", err);
    } catch (Exception err2) {
        log.error("Install: ", err2);
    }

    return null;
}

From source file:org.openbmap.activities.DialogPreferenceMaps.java

@Override
public void onItemClicked(MapDownload map) {
    if (mCurrentMapDownloadId > -1) {
        Toast.makeText(getContext(), getContext().getString(R.string.other_download_active), Toast.LENGTH_LONG)
                .show();//from   w  w w  .  j  ava  2  s. c o m
        return;
    }

    if (map.getUrl() == null) {
        Toast.makeText(getContext(), R.string.invalid_download, Toast.LENGTH_LONG).show();
        return;
    }

    Toast.makeText(getContext(), getContext().getString(R.string.downloading) + " " + map.getUrl(),
            Toast.LENGTH_LONG).show();
    // try to create directory
    final File folder = FileUtils.getMapFolder(getContext());
    Log.d(TAG, "Download destination" + folder.getAbsolutePath());

    boolean folderAccessible = false;
    if (folder.exists() && folder.canWrite()) {
        folderAccessible = true;
    }

    if (!folder.exists()) {
        folderAccessible = folder.mkdirs();
    }
    if (folderAccessible) {
        final String filename = map.getUrl().substring(map.getUrl().lastIndexOf('/') + 1);

        final File target = new File(folder.getAbsolutePath() + File.separator + filename);
        if (target.exists()) {
            Log.i(TAG, "Map file " + filename + " already exists. Overwriting..");
            target.delete();
        }

        try {
            // try to download to target. If target isn't below Environment.getExternalStorageDirectory(),
            // e.g. on second SD card a security exception is thrown
            final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(map.getUrl()));
            request.setDestinationUri(Uri.fromFile(target));
            mCurrentMapDownloadId = mDownloadManager.enqueue(request);
        } catch (final SecurityException sec) {
            // download to temp dir and try to move to target later
            Log.w(TAG, "Security exception, can't write to " + target + ", using "
                    + getContext().getExternalCacheDir());
            final File tempFile = new File(getContext().getExternalCacheDir() + File.separator + filename);

            final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(map.getUrl()));
            request.setDestinationUri(Uri.fromFile(tempFile));
            mCurrentMapDownloadId = mDownloadManager.enqueue(request);

            getDialog().dismiss();
        }
    } else {
        Toast.makeText(getContext(), R.string.error_save_file_failed, Toast.LENGTH_SHORT).show();
    }
    getDialog().dismiss();
}

From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java

/**
 * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#removeKeys(java.lang.String)
 *//*from   w w w  .  j  a v  a 2s  .  co m*/
public synchronized boolean removeKeys(final String guid) throws KeyManagementException {
    final String methodName = FileKeyManager.CNAME
            + "#removeKeys(final String guid) throws KeyManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", guid);
    }

    boolean isComplete = false;

    final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid);

    try {
        if (!(keyDirectory.exists())) {
            throw new KeyManagementException("Configured key directory does not exist");
        }

        if ((FileUtils.getFile(keyConfig.getKeyDirectory()).canWrite()) && (keyDirectory.canWrite())) {
            // delete the files ...
            for (File file : keyDirectory.listFiles()) {
                if (DEBUG) {
                    DEBUGGER.debug("File: {}", file);
                }

                if (!(file.delete())) {
                    throw new IOException("Failed to delete file: " + file);
                }
            }

            // ... then delete the dir
            if (keyDirectory.delete()) {
                isComplete = true;
            }
        } else {
            throw new IOException("Unable to remove user keys");
        }
    } catch (FileNotFoundException fnfx) {
        throw new KeyManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new KeyManagementException(iox.getMessage(), iox);
    }

    return isComplete;
}

From source file:org.openbmap.activities.DialogPreferenceCatalogs.java

@Override
public void onItemClicked(CatalogDownload catalog) {
    if (mCurrentCatalogDownloadId > -1) {
        Toast.makeText(getContext(), getContext().getString(R.string.other_download_active), Toast.LENGTH_LONG)
                .show();/*from   w  ww.  jav  a2s .  c o m*/
        return;
    }

    if (catalog.getUrl() == null) {
        Toast.makeText(getContext(), R.string.invalid_download, Toast.LENGTH_LONG).show();
        return;
    }

    Toast.makeText(getContext(), getContext().getString(R.string.downloading) + " " + catalog.getUrl(),
            Toast.LENGTH_LONG).show();
    // try to create directory
    final File folder = FileUtils.getCatalogFolder(getContext());
    Log.d(TAG, "Download destination" + folder.getAbsolutePath());

    boolean folderAccessible = false;
    if (folder.exists() && folder.canWrite()) {
        folderAccessible = true;
    }

    if (!folder.exists()) {
        folderAccessible = folder.mkdirs();
    }
    if (folderAccessible) {
        final String filename = catalog.getUrl().substring(catalog.getUrl().lastIndexOf('/') + 1);

        final File target = new File(folder.getAbsolutePath() + File.separator + filename);
        if (target.exists()) {
            Log.i(TAG, "Catalog file " + filename + " already exists. Overwriting..");
            target.delete();
        }

        try {
            // try to download to target. If target isn't below Environment.getExternalStorageDirectory(),
            // e.g. on second SD card a security exception is thrown
            final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(catalog.getUrl()));
            request.setDestinationUri(Uri.fromFile(target));
            mCurrentCatalogDownloadId = mDownloadManager.enqueue(request);
        } catch (final SecurityException sec) {
            // download to temp dir and try to move to target later
            Log.w(TAG, "Security exception, can't write to " + target + ", using "
                    + getContext().getExternalCacheDir());
            final File tempFile = new File(getContext().getExternalCacheDir() + File.separator + filename);

            final DownloadManager.Request request = new DownloadManager.Request(Uri.parse(catalog.getUrl()));
            request.setDestinationUri(Uri.fromFile(tempFile));
            mCurrentCatalogDownloadId = mDownloadManager.enqueue(request);
            getDialog().dismiss();
        }
    } else {
        Toast.makeText(getContext(), R.string.error_save_file_failed, Toast.LENGTH_SHORT).show();
    }
    getDialog().dismiss();
}

From source file:gov.nih.nci.ncicb.tcga.dcc.qclive.common.action.ArchiveExpander.java

private File makeArchiveDir(final Archive archive) throws IOException, ProcessorException {
    File explodedDir = new File(archive.getExplodedArchiveDirectoryLocation());
    if (explodedDir.exists() && explodedDir.isDirectory()) {
        // clean up if exists
        boolean isDeleteSuccesfull = FileUtil.deleteDir(explodedDir);
        if (!isDeleteSuccesfull) {
            // something must be holding a lock , bail out
            throw new ProcessorException(new StringBuilder().append(" Unable to delete ")
                    .append(archive.getExplodedArchiveDirectoryLocation())
                    .append(" while expanding the archive: ").append(archive.getArchiveName()).toString());
        }/*from  w ww .j a va  2 s  .c o  m*/
    }

    final File archiveDir = FileUtil.makeDir(archive.getExplodedArchiveDirectoryLocation());
    if (!archiveDir.exists()) {
        throw new ProcessorException(
                new StringBuilder().append("Error expanding '").append(archive.getArchiveFile().getName())
                        .append("': could not create archive directory").toString());
    }
    if (!archiveDir.canWrite()) {
        throw new ProcessorException(
                new StringBuilder().append("Error expanding '").append(archive.getArchiveFile().getName())
                        .append("': can't write to ").append(archiveDir.getAbsolutePath()).toString());
    }
    return archiveDir;
}

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

/**
 * @see net.sf.ginp.setup.SetupManager#validConfigLoc(java.lang.String)
 *//*from   w  w w  .j  a  v a  2  s  .  c  o  m*/
public final Boolean validConfigLoc(final String path) {
    File pathDir = new File(path);

    if (!pathDir.isDirectory()) {
        return new Boolean(false);
    }

    if (!pathDir.canWrite()) {
        return new Boolean(false);
    }

    if (!pathDir.canRead()) {
        return new Boolean(false);
    }

    return new Boolean(true);
}

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

/**
 * @see net.sf.ginp.setup.SetupManager#validPicturesLoc(java.lang.String)
 *///from   w  ww  .j  a v a2s. c o m
public final Boolean validPicturesLoc(final String path) {
    File pathDir = new File(path);

    if (!pathDir.isDirectory()) {
        return new Boolean(false);
    }

    if (!pathDir.canWrite()) {
        return new Boolean(false);
    }

    if (!pathDir.canRead()) {
        return new Boolean(false);
    }

    return new Boolean(true);
}