Example usage for org.apache.commons.io FileUtils moveToDirectory

List of usage examples for org.apache.commons.io FileUtils moveToDirectory

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils moveToDirectory.

Prototype

public static void moveToDirectory(File src, File destDir, boolean createDestDir) throws IOException 

Source Link

Document

Moves a file or directory to the destination directory.

Usage

From source file:com.qcadoo.plugin.internal.filemanager.DefaultPluginFileManager.java

@Override
public boolean installPlugin(final String... filenames) {
    if (!checkFileRightsToWrite(pluginsPath)) {
        return false;
    }/*from   w w w  .  j a  v a  2s.  c  o m*/
    for (String filename : filenames) {
        if (!checkFileExists(filename, pluginsTmpPath)) {
            return false;
        }
    }
    for (String filename : filenames) {
        try {
            FileUtils.moveToDirectory(new File(pluginsTmpPath + getProperty(L_FILE_SEPARATOR) + filename),
                    new File(pluginsPath), false);
        } catch (IOException e) {
            LOG.error("Problem with moving plugin file - " + e.getMessage());
            throw new PluginException(e.getMessage(), e);
        }
    }
    return true;
}

From source file:com.simpligility.maven.plugins.androidndk.common.UnpackedLibHelper.java

public void extractAarLib(Artifact aarArtifact) throws MojoExecutionException {
    final File aarFile = artifactResolverHelper.resolveArtifactToFile(aarArtifact);
    if (aarFile.isDirectory()) {
        log.warn("The aar artifact points to '" + aarFile + "' which is a directory; skipping unpacking it.");
        return;// w ww .  j  ava2  s .  c  o m
    }

    final UnArchiver unArchiver = new ZipUnArchiver(aarFile) {
        @Override
        protected Logger getLogger() {
            return new ConsoleLogger(log.getThreshold(), "dependencies-unarchiver");
        }
    };

    final File aarDirectory = getUnpackedLibFolder(aarArtifact);
    aarDirectory.mkdirs();
    unArchiver.setDestDirectory(aarDirectory);
    log.debug("Extracting AAR to " + aarDirectory);
    try {
        unArchiver.extract();
    } catch (ArchiverException e) {
        throw new MojoExecutionException("ArchiverException while extracting " + aarDirectory.getAbsolutePath()
                + ". Message: " + e.getLocalizedMessage(), e);
    }

    // Move native libraries from libs to jni folder for legacy AARs.
    // This ensures backward compatibility with older AARs where libs are in "libs" folder.
    final File jniFolder = new File(aarDirectory, UnpackedLibHelper.AAR_NATIVE_LIBRARIES_FOLDER);
    final File libsFolder = new File(aarDirectory, UnpackedLibHelper.APKLIB_NATIVE_LIBRARIES_FOLDER);
    if (!jniFolder.exists() && libsFolder.isDirectory() && libsFolder.exists()) {
        String[] natives = libsFolder.list(new PatternFilenameFilter("^.*(?<!(?i)\\.jar)$"));
        if (natives.length > 0) {
            log.debug("Moving AAR native libraries from libs to jni folder");
            for (String nativeLibPath : natives) {
                try {
                    FileUtils.moveToDirectory(new File(libsFolder, nativeLibPath), jniFolder, true);
                } catch (IOException e) {
                    throw new MojoExecutionException("Could not move native libraries from " + libsFolder, e);
                }
            }
        }
    }
}

From source file:com.jayway.maven.plugins.android.common.UnpackedLibHelper.java

public void extractAarLib(Artifact aarArtifact) throws MojoExecutionException {
    final File aarFile = artifactResolverHelper.resolveArtifactToFile(aarArtifact);
    if (aarFile.isDirectory()) {
        log.warn("The aar artifact points to '" + aarFile + "' which is a directory; skipping unpacking it.");
        return;//www.  j av a2  s  .  c o  m
    }

    final UnArchiver unArchiver = new ZipUnArchiver(aarFile) {
        @Override
        protected Logger getLogger() {
            return new ConsoleLogger(log.getThreshold(), "dependencies-unarchiver");
        }
    };

    final File aarDirectory = getUnpackedLibFolder(aarArtifact);
    aarDirectory.mkdirs();
    unArchiver.setDestDirectory(aarDirectory);
    log.debug("Extracting AAR to " + aarDirectory);
    try {
        unArchiver.extract();
    } catch (ArchiverException e) {
        throw new MojoExecutionException("ArchiverException while extracting " + aarDirectory.getAbsolutePath()
                + ". Message: " + e.getLocalizedMessage(), e);
    }

    // Move native libraries from libs to jni folder for legacy AARs.
    // This ensures backward compatibility with older AARs where libs are in "libs" folder.
    final File jniFolder = new File(aarDirectory, AarMojo.NATIVE_LIBRARIES_FOLDER);
    final File libsFolder = new File(aarDirectory, ApklibMojo.NATIVE_LIBRARIES_FOLDER);
    if (!jniFolder.exists() && libsFolder.isDirectory() && libsFolder.exists()) {
        String[] natives = libsFolder.list(new PatternFilenameFilter("^.*(?<!(?i)\\.jar)$"));
        if (natives.length > 0) {
            log.debug("Moving AAR native libraries from libs to jni folder");
            for (String nativeLibPath : natives) {
                try {
                    FileUtils.moveToDirectory(new File(libsFolder, nativeLibPath), jniFolder, true);
                } catch (IOException e) {
                    throw new MojoExecutionException("Could not move native libraries from " + libsFolder, e);
                }
            }
        }
    }
}

From source file:eu.chocolatejar.eclipse.plugin.cleaner.Cleaner.java

/**
 * Removes and back duplicates up.// w  w w.  j av  a 2 s  .  co  m
 * 
 * @param duplicates
 *            list of artifacts to remove
 * @param type
 *            either {@link #PLUGINS} or {@link #FEATURES}
 */
private void removeAndBackupDuplicates(final Set<Artifact> duplicates, final String type) {
    File destinationTypeFolder = FileUtils.getFile(backupFolder, type);

    for (Artifact artifact : duplicates) {
        logger.info("Cleaning {}", artifact);
        try {
            FileUtils.moveToDirectory(artifact.getLocation(), destinationTypeFolder, true);
            logger.info(" OK");
        } catch (FileExistsException e1) {
            // the bundle was already copied there from an other
            // location, so it means we have more duplicates in multiple
            // location(s) with the same version, simply just delete it!
            boolean wasDeleted = FileUtils.deleteQuietly(artifact.getLocation());
            if (wasDeleted) {
                logger.warn(
                        " --> The duplicate `{}` was deleted directly without creating a copy in the destination folder due to \n   `{}`.",
                        artifact, e1.getLocalizedMessage());
            } else {
                logger.warn(" Unable to remove the duplicate '{}' from '{}'.", artifact,
                        artifact.getLocation());
            }
        } catch (Exception e) {
            logger.error("Unable to remove the duplicate '{}'.", artifact, e);
        }

    }
}

From source file:com.twinsoft.convertigo.eclipse.wizards.setup.SetupWizard.java

@Override
public boolean performFinish() {
    try {/*from www.j a va 2  s.c  om*/
        EnginePropertiesManager.saveProperties(false);
    } catch (Exception e) {
    }

    if (workspaceMigrationPage != null) {
        File userWorkspace = new File(Engine.USER_WORKSPACE_PATH);

        File eclipseWorkspace = new File(Engine.PROJECTS_PATH);

        ConvertigoPlugin
                .logInfo("The current Eclipse workspace is a pre-6.2.0 CEMS workspace. Migration starting ");

        boolean projectsMoveFailed = false;

        for (File file : eclipseWorkspace.listFiles()) {
            if (!file.getName().equals(".metadata")) {
                try {
                    ConvertigoPlugin.logInfo("Migration in progress: moving " + file.getName() + " ");
                    FileUtils.moveToDirectory(file, userWorkspace, false);
                } catch (IOException e) {
                    projectsMoveFailed = projectsMoveFailed || file.getName().equals("projects");
                    ConvertigoPlugin.logInfo("Migration in progress: failed to move " + file.getName() + " ! ("
                            + e.getMessage() + ")");
                }
            }
        }

        if (!projectsMoveFailed) {
            ConvertigoPlugin.logInfo(
                    "Migration in progress: move move back CEMS projects to the Eclipse workspace ");
            File exMetadata = new File(userWorkspace, "projects/.metadata");
            try {
                FileUtils.copyDirectoryToDirectory(exMetadata, eclipseWorkspace);
                FileUtils.deleteQuietly(exMetadata);
            } catch (IOException e1) {
                ConvertigoPlugin.logInfo(
                        "Migration in progress: failed to merge .metadata ! (" + e1.getMessage() + ")");
            }

            for (File file : new File(userWorkspace, "projects").listFiles()) {
                try {
                    ConvertigoPlugin.logInfo("Migration in progress: moving the file " + file.getName()
                            + " into the Eclipse Workspace ");
                    FileUtils.moveToDirectory(file, eclipseWorkspace, false);
                } catch (IOException e) {
                    ConvertigoPlugin.logInfo("Migration in progress: failed to move " + file.getName() + " ! ("
                            + e.getMessage() + ")");
                }
            }

            ConvertigoPlugin.logInfo("Migration of workspace done !\n" + "Migration of the folder: "
                    + eclipseWorkspace.getAbsolutePath() + "\n" + "Eclipse Workspace with your CEMS projects: "
                    + eclipseWorkspace.getAbsolutePath() + "\n"
                    + "Convertigo Workspace with your CEMS configuration: " + userWorkspace.getAbsolutePath());
        } else {
            ConvertigoPlugin
                    .logInfo("Migration incomplet: cannot move back CEMS projects to the Eclipse workspace !");
        }
    }

    File pscFile = new File(Engine.USER_WORKSPACE_PATH, "studio/psc.txt");
    try {
        FileUtils.writeStringToFile(pscFile,
                //               pscKeyPage.getCertificateKey(), "utf-8");
                pscKeyValidationPage.getCertificateKey(), "utf-8");
    } catch (IOException e) {
        ConvertigoPlugin.logError("Failed to write the PSC file: " + e.getMessage());
    }

    if (!Engine.isStarted) {
        EnginePropertiesManager.unload();
    } else {
        ConvertigoPlugin.configureDeployConfiguration();
    }

    return true;
}

From source file:com.coinblesk.client.backup.BackupRestoreDialogFragment.java

private void cleanupBeforeRestore() {
    stopWalletService();/*w  w  w .  ja v a 2s . c  o  m*/

    // clear files directory (by moving everything to an archive folder)

    File filesDir = getActivity().getFilesDir();
    File archiveDir = new File(filesDir, "archive_" + System.currentTimeMillis());
    File[] filesInFilesDir = filesDir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String filename) {
            // exclude archive dirs
            return !filename.startsWith("archive_");
        }
    });
    for (File file : filesInFilesDir) {
        try {
            FileUtils.moveToDirectory(file, archiveDir, true);
            Log.d(TAG, "Moved file '" + file + "' to '" + archiveDir + "'");
        } catch (IOException e) {
            Log.w(TAG, "Could not move file: " + file.toString());
        }
    }
}

From source file:com.manydesigns.mail.queue.FileSystemMailQueue.java

public void markSent(String id) throws QueueException {
    checkDirectories();//w w w .j a  v a 2 s  .c  om
    try {
        File emailFile = getEmailFile(id);
        if (emailFile.exists()) {
            File attachmentsDir = getEmailAttachmentsDirectory(id);
            if (keepSent) {
                logger.info("Moving email with id {} to sent directory", id);
                FileUtils.moveToDirectory(emailFile, sentDirectory, false);
                if (attachmentsDir.exists()) {
                    FileUtils.moveToDirectory(attachmentsDir, sentDirectory, false);
                }
            } else {
                logger.info("Deleting sent email with id {}", id);
                boolean success = emailFile.delete();
                if (attachmentsDir.exists()) {
                    for (File attachmentFile : attachmentsDir.listFiles()) {
                        success = attachmentFile.delete() && success;
                    }
                    success = attachmentsDir.delete() && success;
                }
                if (!success) {
                    throw new QueueException("Couldn't mark mail as sent");
                }
            }
        } else {
            logger.debug("Not marking email with id {} as sent", id);
        }
    } catch (IOException e) {
        throw new Error("Couldn't mark mail as sent", e);
    }
}

From source file:com.coinblesk.client.utils.upgrade.UpgradeUtils.java

private void doMigrateFrom_v1_0_262(Context context, NetworkParameters migrationParams) throws IOException {
    Log.d(TAG, "********* MIGRATION FROM v1.0.262 - " + migrationParams.getId() + "*********");

    final File rootDir = context.getFilesDir();
    final File storageDir;
    final File archiveDir = new File(rootDir, "archive_" + System.currentTimeMillis());
    final File walletFile;
    final File chainFile;

    final File newWalletFile;
    final File newChainFile;

    if (ClientUtils.isMainNet(migrationParams)) {
        String walletFilesPrefix = AppConfig.MainNetConfig.get().getWalletFilesPrefix();
        storageDir = new File(rootDir, "mainnet_wallet__uuid_object_storage");
        walletFile = new File(rootDir, "mainnet_wallet_.wallet");
        newWalletFile = new File(rootDir, walletFilesPrefix + ".wallet");
        chainFile = new File(rootDir, "mainnet_wallet_.spvchain");
        newChainFile = new File(rootDir, walletFilesPrefix + ".spvchain");
    } else if (ClientUtils.isTestNet(migrationParams)) {
        String walletFilesPrefix = AppConfig.TestNetConfig.get().getWalletFilesPrefix();
        storageDir = new File(rootDir, "testnet_wallet__uuid_object_storage");
        walletFile = new File(rootDir, "testnet_wallet_.wallet");
        newWalletFile = new File(rootDir, walletFilesPrefix + ".wallet");
        chainFile = new File(rootDir, "testnet_wallet_.spvchain");
        newChainFile = new File(rootDir, walletFilesPrefix + ".spvchain");
    } else {//from  ww  w  .j a  v a  2 s  .  c o m
        throw new RuntimeException("Network params not supported (unknown): " + migrationParams.toString());
    }

    final File keyFile = new File(storageDir, "ECKeyWrapper.json");

    if (keyFile.exists() && walletFile.exists()) {

        // Keys: stored in ECKeyWrapper.json
        /* Key format (JSON):
          {
        "...uuid1...": {
            "isPublicOnly": true,
            "keyPayload": [...bytes (integers)...],
            "name": "remote_server_public_key",
            "uuid": "...uuid1..."
        },
        "...uuid2...": {
            "isPublicOnly": false,
            "keyPayload": [...bytes (integers)...],
            "name": "remote_client_public_key",
            "uuid": "...uuid2..."
        }
          }
        */

        Log.d(TAG, "Key file found: " + keyFile);
        String keyFileJson = FileUtils.readFileToString(keyFile);
        Type type = new TypeToken<Map<String, ECKeyWrapper>>() {
        }.getType();
        // Note: do not use gson from serializeutils (key is not stored in base64).
        Map<String, ECKeyWrapper> keys = new Gson().fromJson(keyFileJson, type);
        ECKey serverKey = null;
        ECKey clientKey = null;
        for (ECKeyWrapper key : keys.values()) {
            if (key.isPublicOnly && key.name.equals("remote_server_public_key")) {
                serverKey = ECKey.fromPublicOnly(key.keyPayload);
            } else if (!key.isPublicOnly && key.name.equals("remote_client_public_key")) {
                clientKey = ECKey.fromPrivate(key.keyPayload);
            } else {
                Log.d(TAG, "Unknown key name: " + key.name);
            }
        }

        if (clientKey != null && serverKey != null) {
            Log.d(TAG, "Found client and server keys - store in shared preferences.");
            try {

                /********** Actual Migration Code **********/
                SharedPrefUtils.setClientKey(context, migrationParams, clientKey);
                SharedPrefUtils.setServerKey(context, migrationParams, serverKey, "n/a - migration");
                Log.d(TAG, "Migrated keys:" + " clientPubKey=" + clientKey.getPublicKeyAsHex()
                        + ", serverPubKey=" + serverKey.getPublicKeyAsHex());

                // move wallet file
                Log.d(TAG, "Migrate wallet file: " + walletFile.toString() + " -> " + newWalletFile.toString());
                FileUtils.copyFile(walletFile, newWalletFile);
                Log.d(TAG, "Migrate chain file: " + chainFile.toString() + " -> " + newChainFile.toString());
                FileUtils.copyFile(chainFile, newChainFile);

                SharedPrefUtils.enableMultisig2of2ToCltvForwarder(context);

                // move everything to an archive file.
                Log.d(TAG, "Move old files to archive dir: " + archiveDir.toString());
                FileUtils.moveToDirectory(storageDir, archiveDir, true);
                FileUtils.moveToDirectory(walletFile, archiveDir, true);
                FileUtils.moveToDirectory(chainFile, archiveDir, true);

            } catch (Exception e) {
                Log.d(TAG, "Exception: ", e);
                // clear the changes made.
                SharedPrefUtils.setClientKey(context, migrationParams, null);
                SharedPrefUtils.setServerKey(context, migrationParams, null, "");
                if (newWalletFile.exists()) {
                    newWalletFile.delete();
                }
            }
        }
    } else {
        Log.d(TAG,
                "Key file or wallet file not found - no migration required - " + String.format(
                        "keyFile: %s (exists: %s), walletFile: %s (exists: %s)", keyFile.toString(),
                        keyFile.exists(), walletFile.toString(), walletFile.exists()));
    }

    Log.d(TAG, "********* MIGRATION FROM v1.0.262 FINISHED *********");
}

From source file:com.manydesigns.mail.queue.FileSystemMailQueue.java

public void markFailed(String id) throws QueueException {
    checkDirectories();//from  w  ww .  ja va 2 s. com
    try {
        File emailFile = getEmailFile(id);
        if (emailFile.exists()) {
            File attachmentsDir = getEmailAttachmentsDirectory(id);
            logger.info("Marking email with id {} as failed", id);
            FileUtils.moveToDirectory(emailFile, failedDirectory, false);
            if (attachmentsDir.exists()) {
                FileUtils.moveToDirectory(attachmentsDir, failedDirectory, false);
            }
        } else {
            logger.debug("Not marking email with id {} as failed", id);
        }
    } catch (IOException e) {
        throw new QueueException("Couldn't mark mail as failed", e);
    }
}

From source file:fr.gael.dhus.database.DatabasePostInit.java

private boolean doIncomingRepopulate() {
    boolean force_relocate = Boolean.getBoolean("Archive.incoming.relocate");

    logger.info("Archives incoming relocate (Archive.incoming.relocate)" + " requested by user ("
            + force_relocate + ")");

    if (!force_relocate)
        return false;

    String incoming_path = System.getProperty("Archive.incoming.relocate.path",
            incomingManager.getIncomingBuilder().getRoot().getPath());

    // Force reset the counter.
    HierarchicalDirectoryBuilder output_builder = new HierarchicalDirectoryBuilder(new File(incoming_path),
            cfgManager.getArchiveConfiguration().getIncomingConfiguration().getMaxFileNo());

    Iterator<Product> products = productDao.getAllProducts();
    while (products.hasNext()) {
        Product product = products.next();
        boolean shared_path = false;

        // Copy the product path
        File old_path = new File(product.getPath().getPath());
        File new_path = null;

        // Check is same products are use for path and download
        if (product.getDownloadablePath().equals(old_path.getPath()))
            shared_path = true;/* w  w  w  .j  av  a  2 s  . c  o m*/

        if (incomingManager.isInIncoming(old_path)) {
            new_path = getNewProductPath(output_builder);
            try {
                logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath());
                FileUtils.moveToDirectory(old_path, new_path, true);

                File path = old_path;
                while (!incomingManager.isAnIncomingElement(path)) {
                    path = path.getParentFile();
                }
                FileUtils.cleanDirectory(path);
            } catch (IOException e) {
                logger.error("Cannot move directory " + old_path.getPath() + " to " + new_path.getPath(), e);
                logger.error("Aborting relocation process.");
                return false;
            }

            URL product_path = null;
            try {
                product_path = new File(new_path, old_path.getName()).toURI().toURL();
            } catch (MalformedURLException e) {
                logger.error("Unrecoverable error : aboting relocate.", e);
                return false;
            }
            product.setPath(product_path);
            // Commit this change
            productDao.update(product);
            searchService.index(product);
        }

        // copy the downloadable path
        if (product.getDownload().getPath() != null) {
            if (shared_path) {
                product.getDownload().setPath(product.getPath().getPath());
            } else {
                new_path = getNewProductPath(output_builder);
                old_path = new File(product.getDownload().getPath());
                try {
                    logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath());
                    FileUtils.moveFileToDirectory(old_path, new_path, false);
                } catch (IOException e) {
                    logger.error(
                            "Cannot move downloadable file " + old_path.getPath() + " to " + new_path.getPath(),
                            e);
                    logger.error("Aborting relocation process.");
                    return false;
                }
                product.getDownload().setPath(new File(new_path, old_path.getName()).getPath());
                // Commit this change
            }
            productDao.update(product);
        }

        // Copy Quicklooks
        new_path = null;
        if (product.getQuicklookFlag()) {
            old_path = new File(product.getQuicklookPath());
            if (new_path == null)
                new_path = output_builder.getDirectory();
            try {
                logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath());
                FileUtils.moveToDirectory(old_path, new_path, false);
            } catch (IOException e) {
                logger.error("Cannot move quicklook file " + old_path.getPath() + " to " + new_path.getPath(),
                        e);
                logger.error("Aborting relocation process.");
                return false;
            }
            File f = new File(new_path, old_path.getName());
            product.setQuicklookPath(f.getPath());
            product.setQuicklookSize(f.length());
            productDao.update(product);
        }
        // Copy Thumbnails in the same incoming path as quicklook
        if (product.getThumbnailFlag()) {
            old_path = new File(product.getThumbnailPath());
            if (new_path == null)
                new_path = output_builder.getDirectory();
            try {
                logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath());

                FileUtils.moveToDirectory(old_path, new_path, false);
            } catch (IOException e) {
                logger.error("Cannot move thumbnail file " + old_path.getPath() + " to " + new_path.getPath(),
                        e);
                logger.error("Aborting relocation process.");
                return false;
            }
            File f = new File(new_path, old_path.getName());
            product.setThumbnailPath(f.getPath());
            product.setThumbnailSize(f.length());
            productDao.update(product);
        }
    }
    // Remove unused directories
    try {
        cleanupIncoming(incomingManager.getIncomingBuilder().getRoot());
    } catch (Exception e) {
        logger.error("Cannot cleanup incoming folder", e);
    }
    return true;
}