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

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

Introduction

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

Prototype

public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) throws IOException 

Source Link

Document

Moves a file to a directory.

Usage

From source file:org.cleverbus.core.common.file.DefaultFileRepository.java

@Override
public void commitFile(String fileId, String fileName, FileContentTypeExtEnum contentType,
        List<String> subFolders) {
    Assert.hasText(fileId, "fileId must not be empty");
    Assert.hasText(fileName, "fileName must not be empty");
    Assert.notNull(subFolders, "subFolders must not be null");

    File tmpFile = new File(tempDir, fileId);

    // check file existence
    if (!tmpFile.exists() || !tmpFile.canRead()) {
        String msg = "temp file " + tmpFile + " doesn't exist or can't be read";
        Log.error(msg);/*from   w w w.j  av a 2 s. c  om*/
        throw new IntegrationException(InternalErrorEnum.E115, msg);
    }

    // move file to target directory
    String targetDirName = FilenameUtils.concat(fileRepoDir.getAbsolutePath(),
            StringUtils.join(subFolders, File.separator));
    targetDirName = FilenameUtils.normalize(targetDirName);

    File targetDir = new File(targetDirName);

    try {
        FileUtils.moveFileToDirectory(tmpFile, targetDir, true);

        Log.debug("File (" + tmpFile + ") was successfully moved to directory - " + targetDir);
    } catch (IOException e) {
        String msg = "error occurred during moving temp file " + tmpFile + " to target directory - "
                + targetDirName;
        Log.error(msg);
        throw new IntegrationException(InternalErrorEnum.E115, msg);
    }

    // rename file
    File targetTmpFile = new File(targetDir, fileId);

    String targetFileName = FilenameUtils.concat(targetDir.getAbsolutePath(),
            getFileName(fileName, contentType));
    targetFileName = FilenameUtils.normalize(targetFileName);

    try {
        FileUtils.moveFile(targetTmpFile, new File(targetFileName));

        Log.debug("File (" + tmpFile + ") was successfully committed. New path: " + targetFileName);
    } catch (IOException e) {
        String msg = "error occurred during renaming temp file " + tmpFile + " to target directory - "
                + targetDirName;
        Log.error(msg);
        throw new IntegrationException(InternalErrorEnum.E115, msg);
    }
}

From source file:org.craftercms.studio.impl.v1.repository.disk.DiskContentRepository.java

@Override
public boolean moveContent(String fromPath, String toPath, String newName) {

    boolean success = true;

    try {/*from   w w w .j a  v a 2 s  .  c  o  m*/
        File source = constructRepoPath(fromPath).toFile();
        File destDir = constructRepoPath(toPath).toFile();

        if (!destDir.exists()) {
            destDir.mkdirs();
        }

        File dest = destDir;
        if (StringUtils.isNotEmpty(newName)) {
            dest = new File(destDir, newName);
        }
        if (source.isDirectory()) {
            File[] dirList = source.listFiles();
            for (File file : dirList) {
                if (file.isDirectory()) {
                    FileUtils.moveDirectoryToDirectory(file, dest, true);
                } else {
                    FileUtils.moveFileToDirectory(file, dest, true);
                }
            }
            source.delete();
        } else {
            if (dest.isDirectory()) {
                FileUtils.moveFileToDirectory(source, dest, true);
            } else {
                source.renameTo(dest);
            }
        }
    } catch (Exception err) {
        // log this error
        success = false;
    }

    return success;
}

From source file:org.craftercms.studio.impl.v1.repository.git.GitContentRepository.java

@Override
public boolean moveContent(String site, String fromPath, String toPath, String newName) {
    boolean success = true;

    try {/*ww w. ja v a2 s  .  c om*/
        Repository repo;
        if (StringUtils.isEmpty(site)) {
            repo = getGlobalConfigurationRepositoryInstance();
        } else {
            repo = getSiteRepositoryInstance(site);
        }
        String gitFromPath = getGitPath(fromPath);
        RevTree fromTree = getTree(repo);
        TreeWalk fromTw = TreeWalk.forPath(repo, gitFromPath, fromTree);

        String gitToPath = getGitPath(toPath);
        RevTree toTree = getTree(repo);
        TreeWalk toTw = TreeWalk.forPath(repo, gitToPath, toTree);

        FS fs = FS.detect();
        File repoRoot = repo.getWorkTree();
        Path sourcePath = null;
        if (fromTw == null) {
            sourcePath = Paths.get(fs.normalize(repoRoot.getPath()), gitFromPath);
        } else {
            sourcePath = Paths.get(fs.normalize(repoRoot.getPath()), fromTw.getPathString());
        }
        Path targetPath = null;
        if (toTw == null) {
            targetPath = Paths.get(fs.normalize(repoRoot.getPath()), gitToPath);
        } else {
            targetPath = Paths.get(fs.normalize(repoRoot.getPath()), toTw.getPathString());
        }

        File source = sourcePath.toFile();
        File destDir = targetPath.toFile();
        File dest = destDir;
        if (StringUtils.isNotEmpty(newName)) {
            dest = new File(destDir, newName);
        }
        if (source.isDirectory()) {
            File[] dirList = source.listFiles();
            for (File file : dirList) {
                if (file.isDirectory()) {
                    FileUtils.moveDirectoryToDirectory(file, dest, true);
                } else {
                    FileUtils.moveFileToDirectory(file, dest, true);
                }
            }
            source.delete();
        } else {
            if (dest.isDirectory()) {
                FileUtils.moveFileToDirectory(source, dest, true);
            } else {
                source.renameTo(dest);
            }
        }
        Git git = new Git(repo);
        git.add().addFilepattern(gitToPath).call();
        git.rm().addFilepattern(gitFromPath).call();
        RevCommit commit = git.commit().setOnly(gitFromPath).setOnly(gitToPath).setMessage(StringUtils.EMPTY)
                .call();
    } catch (IOException | GitAPIException err) {
        // log this error
        logger.error("Error while moving content from {0} to {1}", err, fromPath, toPath);
        success = false;
    }

    return success;
}

From source file:org.cytoscape.app.internal.manager.App.java

/**
 * Default app uninstallation method that can be used by classes extending this class.
 * /*from  ww  w  .jav a2 s. c om*/
 * The default app uninstallation procedure consists of simply moving the app to the uninstalled apps
 * directory.
 * 
 * @param appManager The app manager responsible for managing apps, which is used to obtain
 * the path of the storage directories containing the installed and uninstalled apps
 * @throws AppUninstallException If there was an error while uninstalling the app, such as
 * attempting to uninstall an app that is not installed, or failure to move the app to
 * the uninstalled apps directory
 */
protected void defaultUninstall(AppManager appManager) throws AppUninstallException {
    // Check if the app is installed before attempting to uninstall.
    if (this.getStatus() != AppStatus.INSTALLED) {
        // If it is not installed, do not attempt to uninstall it.
        throw new AppUninstallException("App is not installed; cannot uninstall.");
    }

    // For an installed app whose file has been moved or is no longer available, do not
    // perform file moving. Instead, attempt to try to complete the uninstallation without 
    // regard to app's file.
    if (this.getAppFile() != null) {

        if (!this.getAppFile().exists()) {

            // Skip file moving if the file has been moved
            return;
        }

        // Check if the app is inside the directory containing currently installed apps.
        // If so, prepare to move it to the uninstalled directory.
        File appParentDirectory = this.getAppFile().getParentFile();
        try {
            // Obtain the path of the "uninstalled apps" subdirectory.
            String uninstalledAppsPath = appManager.getUninstalledAppsPath();

            if (appParentDirectory.getCanonicalPath().equals(appManager.getInstalledAppsPath())) {

                // Use the Apache commons library to copy over the file, overwriting existing files.
                try {
                    FileUtils.moveFileToDirectory(this.getAppFile(), new File(uninstalledAppsPath), true);
                } catch (IOException e) {
                    throw new AppUninstallException("Unable to move file: " + e.getMessage());
                }

                // Delete the source file after the copy operation
                String fileName = this.getAppFile().getName();

                //System.gc();
                //System.out.println("Deleting " + this.getAppFile().getPath() + ": " + App.delete(this.getAppFile()));
                this.setAppFile(new File(uninstalledAppsPath + File.separator + fileName));
            }
        } catch (IOException e) {
            throw new AppUninstallException("Unable to obtain path: " + e.getMessage());
        }
    }
}

From source file:org.devtoolbox.errorhandling.impl.OnErrorFileMover.java

/**
 * {@inheritDoc}//from  w w w.j a  v a 2 s .c  o  m
 *
 * @see org.devtoolbox.errorhandling.FileMover#move(org.apache.camel.Exchange)
 */
public void move(Exchange anExchange) throws FileMoverException {

    final String fileSeparator = System.getProperty("file.separator");

    String fileName = retrieveOriginalFileName(anExchange);
    String rootFolderPath = retrieveRootFolderPath(anExchange, fileName);
    String processingFolderPath = retrieveProcessingFolderPath(anExchange, fileName);
    String errorFolderPath = retrieveErrorFolderPath(anExchange, fileName);
    String processingPath = rootFolderPath + fileSeparator + processingFolderPath + fileSeparator + fileName;
    File processingFile = new File(processingPath);
    if (processingFile.exists()) {

        String errorPath = rootFolderPath + fileSeparator + errorFolderPath;
        File errorDirectory = new File(errorPath);
        boolean createDirectory = (!errorDirectory.exists());
        try {

            FileUtils.moveFileToDirectory(processingFile, errorDirectory, createDirectory);
        } catch (IOException e) {

            final String errorMsg = ""; //TODO add error message
            throw new FileMoverException(errorMsg);
        }
    }
}

From source file:org.eclipse.smarthome.model.core.internal.folder.FolderObserverTest.java

/**
 * The following method creates a hidden file in an existing directory. The file's extension is
 * in the configuration properties and there is a registered ModelParser for it.
 * addOrRefreshModel() method invocation is NOT expected, the model should be ignored since the file is hidden
 *
 * @throws Exception//  w  w w . j a  v  a 2 s . c om
 */
@Test
public void testHiddenFile() throws Exception {
    String validExtension = "java";

    configProps.put(EXISTING_SUBDIR_NAME, "txt,jpg," + validExtension);
    folderObserver.activate(context);

    String filename = ".HiddenNewlyCreatedMockFile." + validExtension;

    if (!SystemUtils.IS_OS_WINDOWS) {
        /*
         * In some OS, like MacOS, creating an empty file is not related to sending an ENTRY_CREATE event.
         * So, it's necessary to put some initial content in that file.
         */
        File file = new File(EXISTING_SUBDIR_PATH, filename);
        file.createNewFile();
        FileUtils.writeStringToFile(file, INITIAL_FILE_CONTENT);
    } else {
        /*
         * In windows a hidden file cannot be created with a single api call.
         * The file must be created and afterwards it needs a filesystem property set for a file to be hidden.
         * But the initial creation already triggers the folder observer mechanism,
         * therefore the file is created in an unobserved directory, hidden and afterwards moved to the observed
         * directory
         */
        UNWATCHED_DIRECTORY.mkdirs();
        File file = new File(UNWATCHED_DIRECTORY, filename);
        file.createNewFile();
        Files.setAttribute(file.toPath(), "dos:hidden", true);
        FileUtils.moveFileToDirectory(file, EXISTING_SUBDIR_PATH, false);
        FileUtils.deleteDirectory(UNWATCHED_DIRECTORY);
    }

    sleep(WAIT_EVENT_TO_BE_HANDLED);
    waitForAssert(() -> assertThat(modelRepo.isAddOrRefreshModelMethodCalled, is(false)));
}

From source file:org.ednovo.gooru.application.util.ResourceProcessor.java

private ResourceInstance saveResourceInstance(ResourceInstance resourceInstance, String resourcePath,
        Learnguide classplan) throws Exception {
    Resource resource = resourceInstance.getResource();
    if (resource.getResourceType().getName().equals(ResourceType.Type.QUIZ.getType())) {
        resourceInstance.setResource(resourceService.findResourceByContentGooruId(resource.getGooruOid()));
    } else if (resource.getResourceType().getName().equals(ResourceType.Type.TEXTBOOK.getType())) {
        resourceInstance.setResource(resourceService.findTextbookByContentGooruId(resource.getGooruOid()));
    }//from  w  w  w .j av a2s  .c  o  m

    resource.setUrl(GooruImageUtil.getFileName(resourcePath));

    resourceService.saveResourceInstance(resourceInstance);

    resource.setCategory(SLIDE);

    String destPath = resource.getOrganization().getNfsStorageArea().getInternalPath() + resource.getFolder();

    String fileHash = BaseUtil.getFileMD5Hash(resourcePath);

    resource.setFileHash(fileHash);

    File destDir = new File(destPath);

    if (!destDir.exists()) {
        destDir.mkdirs();
    }

    FileUtils.moveFileToDirectory(new File(resourcePath), destDir, false);

    resourceRepository.save(resource);

    s3ResourceApiHandler.updateOrganization(resource);

    String filePath = destPath + resource.getUrl();

    Map<String, Object> param = new HashMap<String, Object>();
    param.put(RESOURCE_FILE_PATH, filePath);
    param.put(RESOURCE_GOORU_OID, resource.getGooruOid());
    RequestUtil.executeRestAPI(param,
            settingService.getConfigSetting(ConfigConstants.GOORU_CONVERSION_RESTPOINT, 0,
                    TaxonomyUtil.GOORU_ORG_UID) + "/conversion/pdf-to-image",
            Method.POST.getName());
    indexProcessor.index(classplan.getGooruOid(), IndexProcessor.INDEX, COLLECTION);

    return resourceInstance;

}

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

public File releaseModule(final JahiaTemplatesPackage module, ModuleReleaseInfo releaseInfo, File sources,
        String scmUrl, JCRSessionWrapper session) throws RepositoryException, IOException, BundleException {

    File pom = new File(sources, "pom.xml");
    Model model;/*from   ww w.ja  v a 2  s .com*/
    try {
        model = PomUtils.read(pom);
        if (scmUrl != null && !StringUtils.equals(model.getScm().getConnection(), scmUrl)) {
            PomUtils.updateScm(pom, scmUrl);
            module.getSourceControl().add(pom);
            module.getSourceControl().commit("restore pom scm uri before release");
        }
    } catch (XmlPullParserException e) {
        throw new IOException(e);
    }
    String lastVersion = PomUtils.getVersion(model);
    if (!lastVersion.endsWith("-SNAPSHOT")) {
        throw new IOException("Cannot release a non-SNAPSHOT version");
    }
    String releaseVersion = StringUtils.substringBefore(lastVersion, "-SNAPSHOT");

    File generatedWar;
    try {
        generatedWar = moduleBuildHelper.releaseModuleInternal(model, lastVersion, releaseVersion, releaseInfo,
                sources, scmUrl);
    } catch (XmlPullParserException e) {
        throw new IOException(e);
    }

    File releasedModules = new File(settingsBean.getJahiaVarDiskPath(), "released-modules");
    if (generatedWar.exists()) {
        FileUtils.moveFileToDirectory(generatedWar, releasedModules, true);
        generatedWar = new File(releasedModules, generatedWar.getName());
    } else {
        throw new IOException("Module release failed.");
    }

    moduleManager.install(new FileSystemResource(generatedWar), null);

    JahiaTemplatesPackage pack = compileAndDeploy(module.getId(), sources, session);
    JCRNodeWrapper node = session.getNode("/modules/" + pack.getIdWithVersion());
    node.getNode("j:versionInfo").setProperty("j:sourcesFolder", sources.getPath());
    if (scmUrl != null) {
        node.getNode("j:versionInfo").setProperty("j:scmURI", scmUrl);
    }
    session.save();

    undeployModule(module);

    activateModuleVersion(module.getId(), releaseInfo.getNextVersion());

    if (releaseInfo.isPublishToMaven() || releaseInfo.isPublishToForge()) {
        releaseInfo.setArtifactUrl(forgeHelper.computeModuleJarUrl(releaseVersion, releaseInfo, model));
        if (releaseInfo.isPublishToForge() && releaseInfo.getForgeUrl() != null) {
            String forgeModuleUrl = forgeHelper.createForgeModule(releaseInfo, generatedWar);
            releaseInfo.setForgeModulePageUrl(forgeModuleUrl);
        } else if (releaseInfo.isPublishToMaven() && releaseInfo.getRepositoryUrl() != null) {
            deployToMaven(PomUtils.getGroupId(model), model.getArtifactId(), releaseInfo, generatedWar);
        }
    }

    return generatedWar;
}

From source file:org.jahia.utils.maven.plugin.osgi.ConvertToOSGiMojo.java

private void moveWithMerge(File src, File dst) throws IOException {
    // @todo this doesn't handle SVN directories properly
    File[] files = src.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return !name.startsWith(".");
        }/*from   w  w w . j a v a  2  s. c  o m*/
    });

    for (File file : files) {
        if (file.isDirectory()) {
            File subDir = new File(dst, file.getName());
            if (subDir.exists()) {
                moveWithMerge(file, subDir);
            } else {
                FileUtils.moveDirectoryToDirectory(file, dst, true);
            }
        } else {
            FileUtils.moveFileToDirectory(file, dst, true);
        }
    }
}

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

public boolean deploy(NexusClient nexusClient, OpenStackClient openStackClient,
        YumRepoParameters yumRepoParameters, DeployParmeters deployParmeters) throws Exception {
    final String targetFolder = Joiner.on(File.separator).join(build.getWorkspace().getRemote(), "archive");

    LogUtils.logSection(listener, "Deploy Product " + artifact.getArtifactId());

    List<String> fileTypes = new ArrayList<String>();
    fileTypes.add("pom");
    fileTypes.add("tar.gz");
    fileTypes.add("rpm");
    fileTypes.add("rh6");
    nexusClient.downloadProductArtifacts(getArtifact(),
            Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId()), fileTypes);
    //****************** get pom file dependencies ******************
    MavenPom mavenPom = new MavenPom(
            new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(), "pom.xml")));
    List<ArtifactParameters> subProducts = mavenPom.getPomProductDependencies();

    for (ArtifactParameters m : subProducts) {
        Product p = new Product(m, build, listener);
        boolean return_ = p.deploy(nexusClient, openStackClient, yumRepoParameters, deployParmeters);
        if (!return_)
            throw new ProductDeployPluginException(
                    "Deploy dependent product " + m.getArtifactId() + " failed.");
    }/*  www  . j a  va2s  . com*/

    String buildId = Joiner.on("-").join(new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss-SS").format(build.getTime()),
            deployParmeters.getDeployCounter());

    if (!new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(),
            "external_dependencies.tar.gz")).exists()) {
        // if there isn't an external_dependencies.tar.gz file
        // only a pom file => we're deploying a profile
        LogUtils.log(listener, "Finish Deploy: " + artifact.getArtifactId());
        return true;
    }

    CompressUtils.untarFile(new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(),
            "external_dependencies.tar.gz")));
    LogUtils.log(listener, "Untar File: " + Joiner.on(File.separator).join(targetFolder,
            artifact.getArtifactId(), "external_dependencies.tar.gz"));

    //****************** move deployment-scripts ******************
    // Push scripts to YUM repo machine
    copyFolderToRepoMachine(build, listener, yumRepoParameters,
            Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(), "archive", "deploy-scripts"),
            Joiner.on("/").join("/var", "www", "html", "build", buildId));
    LogUtils.log(listener, "Copy deployment-scripts folder to Yum Repo machine.");

    // move external rpms from archive/product/archive/rpms  to /archive/repo folder

    if (new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(), "archive", "repo"))
            .exists()) {
        moveExternalRpmsToRepoDirectory(
                Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(), "archive", "repo"),
                Joiner.on(File.separator).join(targetFolder, "repo"));
        LogUtils.log(listener, "Copied external RPMS to repo directory.");
    }

    File deploymentScriptsRPM = new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(),
            artifact.getArtifactId() + "-" + artifact.getVersion() + ".rpm"));
    if (deploymentScriptsRPM.exists()) {
        //            Rename RPM file according to rpm metadata
        if (!System.getProperty("os.name").toLowerCase().startsWith("windows")) {
            ExecUtils.executeLocalCommand(
                    "/usr/local/bin/download_rpm.sh " + deploymentScriptsRPM.getPath().replaceAll(" ", "\\ "),
                    deploymentScriptsRPM.getParentFile().getPath().replaceAll(" ", "\\ "));
            deploymentScriptsRPM.delete();
            deploymentScriptsRPM = new File(Joiner.on(File.separator).join(targetFolder,
                    artifact.getArtifactId(), "nds_" + artifact.getArtifactId() + "_deployment-scripts" + "-"
                            + artifact.getVersion() + "_1.noarch.rpm"));
        }

        LogUtils.log(listener, deploymentScriptsRPM.getParentFile().list().toString());
        FileUtils.moveFileToDirectory(deploymentScriptsRPM,
                new File(Joiner.on(File.separator).join(targetFolder, "repo")), true);
        LogUtils.log(listener, "Copied deployment-scripts to repo directory");
    }
    MavenPom mp = new MavenPom(
            new File(Joiner.on(File.separator).join(targetFolder, artifact.getArtifactId(), "pom.xml")));
    List<ArtifactParameters> rpms = mp.getPomModuleDependencies();

    // download rpms to archive/repo
    LogUtils.logSection(listener, "Download dependent RPMS.");
    for (ArtifactParameters m : rpms) {
        new NexusClient(m, build, listener).downloadRPM(Joiner.on(File.separator).join(targetFolder, "repo"));
    }

    // create yum repo
    createAndMoveYumRepo(build, listener, yumRepoParameters,
            Joiner.on(File.separator).join(targetFolder, "repo"),
            String.valueOf(deployParmeters.getDeployCounter()));
    LogUtils.log(listener, "YUM repository have been created.");

    // deploy stack
    String stackName = artifact.getArtifactId().toLowerCase().replace("-product", "");

    openStackClient.createStack(stackName, deployParmeters.getOverridingParameters(),
            deployParmeters.getGlobalOutputs(), Joiner.on(File.separator).join(targetFolder,
                    artifact.getArtifactId(), "archive", "heat", stackName));

    long startTime = System.currentTimeMillis();
    boolean createComplete = false;

    while (!createComplete && System.currentTimeMillis() - startTime < CREATE_TIMEOUT) {
        StackStatus stackStatus = openStackClient.getStackStatus(stackName);
        LogUtils.log(listener, "Waiting for stack creation for " + stackName + ". Status is: " + stackStatus);
        if (stackStatus == StackStatus.CREATE_COMPLETE) {
            createComplete = true;
            // update outputs map
            Map<String, String> stackOutputs = openStackClient.getStackOutputs(stackName);
            deployParmeters.setGlobalOutputsWithNewOutputs(stackOutputs);
        } else if (stackStatus == StackStatus.FAILED || stackStatus == StackStatus.CREATE_FAILED
                || stackStatus == StackStatus.UNDEFINED)
            throw new ProductDeployPluginException("Failed to Launch Stack " + stackName);
        else
            Thread.sleep(SLEEP_TIME);

    }
    // if stack is not complete after 40 minutes -  throw a timeout exception
    if (!createComplete)
        throw new TimeoutException("Create Stack- timeout exception");

    // clean files
    try {
        FileUtils.cleanDirectory(new File(Joiner.on(File.separator).join(targetFolder, "repo")));
    } catch (IOException e) {
        /*Swallow*/ }

    deployParmeters.increaseDeployCounter();
    LogUtils.log(listener, "Increased deployment counter.");

    return true;

}