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

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

Introduction

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

Prototype

public static void moveDirectory(File srcDir, File destDir) throws IOException 

Source Link

Document

Moves a directory.

Usage

From source file:org.jahia.services.content.impl.jackrabbit.RepositoryMigrator.java

private void swapRepositoryHome(File repoHomeCopy) throws IOException {
    String repoHomePath = repoHome.getAbsolutePath();
    try {//from  w  w w  .j a  v a2s .c o m
        if (keepBackup) {
            File backupDir = new File(repoHome.getParentFile(), "repository-original");
            FileUtils.moveDirectory(repoHome, backupDir);
            logger.info("Backup of the source repository folder at {}", backupDir);
        } else {
            try {
                FileUtils.deleteDirectory(repoHome);
            } catch (IOException e) {
                logger.warn("Issue while deleting the " + repoHomePath + " directory, we will try to empty it");
                FileUtils.cleanDirectory(repoHome);
            }
        }

        FileUtils.moveDirectory(repoHomeCopy, repoHome);
    } catch (IOException e) {
        logger.error("The migration was successful, except the last step: we are unable to delete directory {}."
                + " Jahia server will be stopped now.", repoHomePath);
        String repoHomeCopyPath = repoHomeCopy.getAbsolutePath();
        logger.error(
                "Please delete the directory {} manually (perhaps an OS reboot is required to free the file locks)"
                        + " and copy the content of {} to {}",
                new String[] { repoHomePath, repoHomeCopyPath, repoHomePath });
        logger.error(
                "Also delete the following folders if they are present:\n{}\\index\n{}\\workspaces\\default\\index\n{}\\workspaces\\live\\index",
                new String[] { repoHomePath, repoHomePath, repoHomePath });

        logger.error("Start Jahia server afterwards.",
                new String[] { repoHomePath, repoHomeCopyPath, repoHomePath });
        System.exit(1);
    }

    logger.info("Replaced repository with the migrated copy");
}

From source file:org.jahia.services.templates.ModuleBuildHelper.java

public JCRNodeWrapper createModule(final String moduleName, String artifactId, final String groupId,
        final String moduleType, final File moduleSources, final JCRSessionWrapper session)
        throws IOException, RepositoryException, BundleException {

    if (!isMavenConfigured()) {
        throw new JahiaRuntimeException("Cannot create module, either current instance is not "
                + "in development mode or maven configuration is not good");
    }/*from w  w  w  . ja va  2  s .c  o m*/
    if (StringUtils.isBlank(moduleName)) {
        throw new RepositoryException("Cannot create module because no module name has been specified");
    }
    if (StringUtils.isBlank(artifactId)) {
        artifactId = JCRContentUtils.generateNodeName(moduleName);
    }
    if (templatePackageRegistry.containsId(artifactId)) {
        throw new RepositoryException("Cannot create module " + artifactId
                + " because another module with the same artifactId exists");
    }

    File sources = moduleSources;
    if (sources == null) {
        sources = new File(SettingsBean.getInstance().getModulesSourcesDiskPath());
        if (!sources.exists() && !sources.mkdirs()) {
            throw new IOException("Unable to create path for: " + sources);
        }
    }

    String finalFolderName = null;

    if (!sources.exists()) {
        finalFolderName = sources.getName();
        sources = sources.getParentFile();
        if (sources == null) {
            sources = new File(SettingsBean.getInstance().getModulesSourcesDiskPath());
        }
        if (!sources.exists() && !sources.mkdirs()) {
            throw new IOException("Unable to create path for: " + sources);
        }
    }

    List<String> archetypeParams = new ArrayList<String>();
    archetypeParams.add(mavenArchetypePlugin + ":generate");
    archetypeParams.add("-DarchetypeCatalog=" + mavenArchetypeCatalog + ",local");
    archetypeParams.add("-DarchetypeGroupId=org.jahia.archetypes");
    archetypeParams.add("-DarchetypeArtifactId=jahia-" + moduleType + "-archetype");
    archetypeParams.add("-DarchetypeVersion=" + mavenArchetypeVersion);
    archetypeParams.add("-Dversion=1.0-SNAPSHOT");
    archetypeParams.add("\"-DmoduleName=" + moduleName + "\"");
    archetypeParams.add("-DartifactId=" + artifactId);
    if (StringUtils.isNotBlank(groupId)) {
        archetypeParams.add("-DgroupId=" + groupId);
    }
    archetypeParams.add("-DdigitalFactoryVersion=" + Constants.JAHIA_PROJECT_VERSION);
    archetypeParams.add("-DinteractiveMode=false");

    StringBuilder out = new StringBuilder();
    int ret = ProcessHelper.execute(mavenExecutable,
            archetypeParams.toArray(new String[archetypeParams.size()]), null, sources, out, out);

    if (ret > 0) {
        logger.error("Maven archetype call returned " + ret);
        logger.error("Maven out : " + out);
        return null;
    }

    File path = new File(sources, artifactId);
    if (finalFolderName != null && !path.getName().equals(finalFolderName)) {
        try {
            File newPath = new File(sources, finalFolderName);
            FileUtils.moveDirectory(path, newPath);
            path = newPath;
        } catch (IOException e) {
            logger.error("Cannot rename folder", e);
        }
    }

    JahiaTemplatesPackage pack = compileAndDeploy(artifactId, path, session);

    JCRNodeWrapper node = session.getNode("/modules/" + pack.getIdWithVersion());
    scmHelper.setSourcesFolderInPackageAndNode(pack, path, node);
    session.save();

    return node;
}

From source file:org.jahia.services.templates.SourceControlHelper.java

public JCRNodeWrapper checkoutModule(final File moduleSources, final String scmURI, final String branchOrTag,
        final String moduleId, final String version, final JCRSessionWrapper session)
        throws IOException, RepositoryException, BundleException {
    boolean newModule = moduleSources == null;
    File sources = ensureModuleSourceFolder(moduleSources);

    try {/*from   w w w . ja  v a 2 s  .com*/
        // checkout sources from SCM
        SourceControlManagement scm = sourceControlFactory.checkoutRepository(sources, scmURI, branchOrTag,
                false);

        // verify the sources and found out module information
        ModuleInfo moduleInfo = getModuleInfo(sources, scmURI, moduleId, version, branchOrTag);
        if (templatePackageRegistry.containsId(moduleInfo.id)
                && !moduleInfo.groupId.equals(templatePackageRegistry.lookupById(moduleInfo.id).getGroupId())) {
            FileUtils.deleteDirectory(sources);
            throw new ScmUnavailableModuleIdException("Cannot checkout module " + moduleInfo.id
                    + " because another module with the same artifactId exists", moduleInfo.id);
        }
        if (version != null && !version.equals(moduleInfo.version)) {
            FileUtils.deleteDirectory(sources);
            throw new ScmWrongVersionException("Sources don't match module version");
        }

        if (newModule) {
            File newPath = new File(sources.getParentFile(), moduleInfo.id + "_" + moduleInfo.version);
            int i = 0;
            while (newPath.exists()) {
                newPath = new File(sources.getParentFile(),
                        moduleInfo.id + "_" + moduleInfo.version + "_" + (++i));
            }

            FileUtils.moveDirectory(sources, newPath);
            moduleInfo.path = new File(moduleInfo.path.getPath().replace(sources.getPath(), newPath.getPath()));
            sources = newPath;
            scm = sourceControlFactory.getSourceControlManagement(moduleInfo.path);
        }

        if (sources.equals(moduleInfo.path)) {
            setSCMConfigInPom(sources, scmURI);
        }

        JahiaTemplatesPackage pack = ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                .compileAndDeploy(moduleInfo.id, moduleInfo.path, session);
        if (pack != null) {
            JCRNodeWrapper node = session.getNode("/modules/" + pack.getIdWithVersion());
            pack.setSourceControl(scm);
            setSourcesFolderInPackageAndNode(pack, moduleInfo.path, node);
            session.save();

            // flush resource bundle cache
            ResourceBundles.flushCache();
            NodeTypeRegistry.getInstance().flushLabels();

            return node;
        } else {
            FileUtils.deleteDirectory(sources);
        }
    } catch (BundleException e) {
        FileUtils.deleteQuietly(sources);
        throw e;
    } catch (RepositoryException e) {
        FileUtils.deleteQuietly(sources);
        throw e;
    } catch (IOException e) {
        FileUtils.deleteQuietly(sources);
        throw e;
    } catch (DocumentException e) {
        FileUtils.deleteQuietly(sources);
        throw new IOException(e);
    } catch (XmlPullParserException e) {
        FileUtils.deleteQuietly(sources);
        throw new IOException(e);
    }

    return null;
}

From source file:org.jboss.loom.actions.ModuleCreationAction.java

@Override
public void rollback() throws MigrationException {
    //if( this.isAfterPerform() )
    FileUtils.deleteQuietly(this.moduleDir);

    if (this.backupDir != null) {
        try {/*w  w w.  jav a 2  s.  c om*/
            FileUtils.moveDirectory(this.backupDir, this.moduleDir);
        } catch (Exception ex) {
            throw new ActionException(this, "Can't move " + backupDir + " to " + moduleDir + ": " + ex);
        }
    }
    setState(State.ROLLED_BACK);
}

From source file:org.jenkinsci.plugins.os_ci.model.Product.java

private void saveProductResourcesOnly(String srcDir, String tarDir) throws IOException {
    String plainId = artifact.getArtifactId().substring(0, artifact.getArtifactId().lastIndexOf('-'));
    FileUtils.forceMkdir(new File(Joiner.on(File.separator).join(tarDir, "heat")));
    FileUtils.forceMkdir(new File(Joiner.on(File.separator).join(tarDir, "deploy-scripts")));

    // save GLOBAL scripts
    File fgScripts = new File(Joiner.on(File.separator).join(srcDir, "deploy-scripts", "GLOBAL"));
    if (fgScripts.isDirectory()) {
        FileUtils.moveDirectory(fgScripts,
                new File(Joiner.on(File.separator).join(tarDir, "deploy-scripts", "GLOBAL")));
    }//from w  ww  .ja  v a  2s .  co m

    // save product resources
    File fHeat = new File(Joiner.on(File.separator).join(srcDir, "heat", plainId.toLowerCase()));
    if (fHeat.isDirectory()) {
        FileUtils.moveDirectory(fHeat,
                new File(Joiner.on(File.separator).join(tarDir, "heat", plainId.toLowerCase())));
    } else {
        throw new OsCiPluginException("HEAT template missing in repo for product" + plainId.toLowerCase());
    }

    File fScripts = new File(Joiner.on(File.separator).join(srcDir, "deploy-scripts", plainId.toUpperCase()));
    if (fScripts.isDirectory()) {
        FileUtils.moveDirectory(fScripts,
                new File(Joiner.on(File.separator).join(tarDir, "deploy-scripts", plainId.toUpperCase())));
    }

    // delete temp_archive directory - failed to delete pack file
    //FileUtils.forceDelete(new File(srcDir));
}

From source file:org.kalypso.calculation.plc.postprocessing.PLCPreprocessingSimulation.java

/**
 * move flood outputs to status quo//from  ww  w  .  jav a  2 s  .c  o m
 */
private void doFloodModel(final ISimulationDataProvider inputProvider, final File statusQuoFolder)
        throws SimulationException, IOException {
    if (!inputProvider.hasID(INPUT_FLOOD_MODEL))
        return;

    final File actualFloodModel = FileUtils.toFile((URL) inputProvider.getInputForID(INPUT_FLOOD_MODEL));
    FileUtils.copyFileToDirectory(actualFloodModel, new File(statusQuoFolder, "models")); //$NON-NLS-1$

    final File actualFloodResults = FileUtils
            .toFile((URL) inputProvider.getInputForID(INPUT_FLOOD_RESULT_FOLDER));
    final File statusQuoFloodResults = new File(statusQuoFolder, "events"); //$NON-NLS-1$
    FileUtils.moveDirectory(actualFloodResults, statusQuoFloodResults);
}

From source file:org.kalypso.calculation.plc.postprocessing.PLCPreprocessingSimulation.java

/**
 * move risk outputs to status quo//ww  w  .j  av  a 2s.  c o  m
 */
private void doRiskModel(final ISimulationDataProvider inputProvider, final File statusQuoFolder)
        throws SimulationException, IOException {
    if (!inputProvider.hasID(INPUT_RISK_MODEL))
        return;

    final File actualRasterModel = FileUtils.toFile((URL) inputProvider.getInputForID(INPUT_RISK_MODEL));
    FileUtils.copyFileToDirectory(actualRasterModel, statusQuoFolder);

    final File actualRasterFolderOutput = FileUtils
            .toFile((URL) inputProvider.getInputForID(INPUT_RISK_RESULT_FOLDER));
    final File statusQuoRasterFolderOutput = new File(statusQuoFolder, "raster/output"); //$NON-NLS-1$
    FileUtils.moveDirectory(actualRasterFolderOutput, statusQuoRasterFolderOutput);
}

From source file:org.kalypso.model.hydrology.NASimulationOperation.java

/**
 * This function deletes the old results and moves the new results to the results directory. The new results will also
 * be copied to a directory with a timestamp.
 * // www.  j  a  v  a  2  s . c  o  m
 * @param resultDir
 *          The directory of the results.
 */
private void handleResults(final File resultDir) throws CoreException {
    /* Create a filename with the timestamp format. */
    final SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy.MM.dd_(HH_mm_ss)"); //$NON-NLS-1$
    final String timestampFilename = timestampFormat.format(new Date());

    /* Get the current result directory. */
    final IFolder currentResultFolder = m_simulation.getCurrentCalculationResult().getFolder();
    final File currentResultDir = currentResultFolder.getLocation().toFile();

    /* Get the timestamp directory. */
    final IFolder calcResultFolder = m_simulation.getResultsFolder();
    final IFolder timestampFolder = calcResultFolder.getFolder(timestampFilename);
    final File timestampDir = timestampFolder.getLocation().toFile();

    try {
        /* Remove old 'Aktuell' dir. */
        if (currentResultDir.exists())
            FileUtils.forceDelete(currentResultDir);

        /* Move new result to calc Folder: move is way faster... */
        FileUtils.moveDirectory(new File(resultDir, NaSimulationDirs.DIR_CURRENT_RESULT), currentResultDir);

        /* Make copy with timestamp. */
        FileUtils.copyDirectory(currentResultDir, timestampDir);
    } catch (final IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, ModelNA.PLUGIN_ID, "Failed to copy result data", e)); //$NON-NLS-1$
    } finally {
        /* Refresh the folders. */
        currentResultFolder.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        timestampFolder.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
    }
}

From source file:org.kie.commons.java.nio.fs.file.SimpleFileSystemProvider.java

@Override
public void move(final Path source, final Path target, final CopyOption... options)
        throws DirectoryNotEmptyException, AtomicMoveNotSupportedException, IOException, SecurityException {
    checkNotNull("source", source);
    checkNotNull("target", target);
    checkCondition("source must exist", source.toFile().exists());

    if (target.toFile().exists()) {
        throw new FileAlreadyExistsException(target.toString());
    }/*from  w  w  w  .  j av a  2  s  .  c  o m*/

    if (source.toFile().isDirectory() && source.toFile().list().length > 0) {
        throw new DirectoryNotEmptyException(source.toString());
    }

    try {
        if (source.toFile().isDirectory()) {
            FileUtils.moveDirectory(source.toFile(), target.toFile());
        } else {
            FileUtils.moveFile(source.toFile(), target.toFile());
        }
    } catch (java.io.IOException ex) {
        throw new IOException(ex);
    }
}

From source file:org.mobicents.servlet.restcomm.rvd.storage.FsProjectStorage.java

public static void renameProject(String projectName, String newProjectName, WorkspaceStorage storage)
        throws StorageException {
    try {/*from   ww  w.  ja  v a  2s  .  co m*/
        File sourceDir = new File(storage.rootPath + File.separator + projectName);
        File destDir = new File(storage.rootPath + File.separator + newProjectName);
        FileUtils.moveDirectory(sourceDir, destDir);
    } catch (IOException e) {
        throw new StorageException(
                "Error renaming directory '" + projectName + "' to '" + newProjectName + "'");
    }
}