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.jenkinsci.plugins.os_ci.model.Product.java

private void moveExternalRpmsToRepoDirectory(String rpmsSrcFolder, String repoTargetFolder) {

    File repoFolder = new File(repoTargetFolder);

    for (File f : new File(rpmsSrcFolder).listFiles())
        try {//from  w  ww.j a va2s.c  om
            FileUtils.moveFileToDirectory(f, repoFolder, true);
        } catch (IOException e) {
        }
}

From source file:org.jumpmind.metl.core.runtime.resource.LocalFileDirectory.java

@Override
public void moveToDir(String fromFilePath, String toDirPath) {
    try {//from   w  ww. jav  a  2  s .c o  m
        File fromFile = new File(basePath, fromFilePath);
        File toDir = new File(basePath, toDirPath);
        File toFile = new File(toDir, fromFile.getName());
        toFile.delete();
        FileUtils.moveFileToDirectory(fromFile, toDir, true);
    } catch (IOException e) {
        throw new IoException(e);
    }
}

From source file:org.messic.server.api.APIAlbum.java

public long createOrUpdateAlbum(User user, Album album) throws IOException, ExistingMessicException {
    Long sidResult = 0l;/*from   ww w  .  ja v a  2  s. c om*/
    MDOGenre mdoGenre = null;
    MDOAlbum mdoAlbum = null;
    MDOAuthor mdoAuthor = null;
    MDOUser mdouser = daoUser.getUserByLogin(user.getLogin());
    char replacementChar = daoSettings.getSettings().getIllegalCharacterReplacement();
    MDOMessicSettings settings = daoSettings.getSettings();

    // 1st getting genre ###############################################################################
    if (album.getGenre() != null && album.getGenre().getSid() != null) {
        mdoGenre = daoGenre.get(album.getGenre().getSid());
    }
    if (mdoGenre == null) {
        if (album.getGenre() != null && album.getGenre().getName() != null
                && album.getGenre().getName().trim().length() > 0) {
            mdoGenre = daoGenre.getByName(user.getLogin(), album.getGenre().getName());
        }
    }
    if (mdoGenre == null && album.getGenre() != null && album.getGenre().getName() != null
            && album.getGenre().getName().trim().length() > 0) {
        mdoGenre = new MDOGenre(album.getGenre().getName(), mdouser);
    }

    // 2nd getting the album if exist
    // ###############################################################################
    if (album.getSid() > 0) {
        mdoAlbum = daoAlbum.get(album.getSid());
    }

    // 3rd getting the author ###############################################################################
    if (album.getAuthor().getSid() > 0) {
        // trying by sid
        mdoAuthor = daoAuthor.get(user.getLogin(), album.getAuthor().getSid());
    }
    if (mdoAuthor == null) {
        // trying by name
        mdoAuthor = daoAuthor.getByName(album.getAuthor().getName(), user.getLogin());
    }
    if (mdoAuthor != null) {
        // an existing album from this autor??
        if (mdoAlbum == null) {
            mdoAlbum = daoAlbum.getByName(mdoAuthor.getName(), album.getName(), user.getLogin());
        }
    }
    // let's create a new author
    if (mdoAuthor == null) {
        mdoAuthor = new MDOAuthor();
        mdoAuthor.setName(album.getAuthor().getName().trim());
        mdoAuthor.setOwner(mdouser);
        mdoAuthor.setLocation(
                Util.replaceIllegalFilenameCharacters(album.getAuthor().getName(), replacementChar));
    }
    // 4th new album if none ###############################################################################
    if (mdoAlbum == null) {
        mdoAlbum = new MDOAlbum();
    }

    boolean flagExistingAuthor = (mdoAuthor.getSid() != null && mdoAuthor.getSid() > 0);
    boolean flagAuthorNameChanged = false;
    boolean flagExistingAlbum = (mdoAlbum.getSid() != null && mdoAlbum.getSid() > 0);

    // checking if the user is trying to create a new album with the same name and author of another existing one.
    // the reason to forbide this is because of the filesystem. Both albums will have the same filesystem path, and
    // will merge their content!! panic!!
    List<MDOAlbum> albumsSameName = daoAlbum.findAlbum(album.getName(), user.getLogin());
    if (albumsSameName.size() > 0) {
        for (MDOAlbum mdoAlbumSameName : albumsSameName) {
            if (mdoAlbumSameName.getSid() != mdoAlbum.getSid()) {
                String authorName = mdoAlbumSameName.getAuthor().getName();
                if (authorName.toUpperCase().equals(album.getAuthor().getName().toUpperCase())) {
                    throw new ExistingMessicException();
                }
            }
        }
    }

    // old album path if the album was an existing one
    String oldAlbumPath = null;
    if (flagExistingAlbum) {
        oldAlbumPath = mdoAlbum.calculateAbsolutePath(settings);
    }

    // 5th updating / creating the album
    // ###############################################################################

    // if its an existing author and the name of the author has changed...wow!! we must do more things
    if (flagExistingAuthor && !album.getAuthor().getName().trim().toUpperCase()
            .equals(mdoAuthor.getName().trim().toUpperCase())) {
        // the name of the author has changed!!!
        flagAuthorNameChanged = true;
        mdoAuthor.setName(album.getAuthor().getName());
        mdoAuthor.setLocation(
                Util.replaceIllegalFilenameCharacters(album.getAuthor().getName(), replacementChar));
    }

    mdoAlbum.setName(album.getName());
    mdoAlbum.setLocation(Util.replaceIllegalFilenameCharacters(album.getName(), replacementChar));
    mdoAlbum.setAuthor(mdoAuthor);
    mdoAlbum.setComments(album.getComments());
    mdoAlbum.setGenre(mdoGenre);
    mdoAlbum.setOwner(mdouser);
    mdoAlbum.setYear(album.getYear());

    // 6th saving author, genre and album
    // ###############################################################################
    daoAuthor.save(mdoAuthor);
    if (mdoGenre != null) {
        daoGenre.save(mdoGenre);
    }
    daoAlbum.save(mdoAlbum);

    sidResult = mdoAlbum.getSid();
    if (sidResult <= 0) {
        mdoAlbum = daoAlbum.merge(mdoAlbum);
        sidResult = mdoAlbum.getSid();
    }

    // 7th moving album resources to definitive location
    // ###############################################################################

    String currentAlbumPath = mdoAlbum.calculateAbsolutePath(settings);
    File currentAlbumPathFile = new File(currentAlbumPath);
    String userTmpPath = mdouser.calculateTmpPath(settings, album.getCode());

    // creating album path
    currentAlbumPathFile.mkdirs();

    // 7.1 - Songs resources
    if (album.getSongs() != null && album.getSongs().size() > 0) {
        List<Song> songs = album.getSongs();
        for (Song song : songs) {
            MDOSong mdoSong = new MDOSong();
            File fnew = null;

            if (song.getSid() <= 0) {
                MDOSongStatistics ss = new MDOSongStatistics();
                ss.setTimesplayed(0);
                ss.setTimesstopped(0);
                daoSongStatistics.save(ss);

                // new song
                mdoSong.setStatistics(ss);
                mdoSong.setTrack(song.getTrack());
                mdoSong.setName(song.getName());
                String secureExtension = song.calculateSecureExtension(replacementChar);
                String theoricalFileName = mdoSong.calculateSongTheoricalFileName(secureExtension,
                        replacementChar);

                mdoSong.setLocation(theoricalFileName);
                mdoSong.setOwner(mdouser);
                mdoSong.setAlbum(mdoAlbum);
                daoSong.save(mdoSong);

                // moving resource to the new location
                File tmpRes = new File(
                        userTmpPath + File.separatorChar + song.calculateSecureFileName(replacementChar));
                fnew = new File(mdoSong.calculateAbsolutePath(settings));
                if (fnew.exists()) {
                    fnew.delete();
                }
                FileUtils.moveFile(tmpRes, fnew);
            } else {
                // existing song...
                mdoSong = daoSong.get(user.getLogin(), song.getSid());
                if (mdoSong != null) {
                    mdoSong.setTrack(song.getTrack());
                    mdoSong.setName(song.getName());
                    String oldLocation = mdoSong.calculateAbsolutePath(settings);
                    String theoricalFileName = mdoSong.calculateSongTheoricalFileName(mdoSong.getExtension(),
                            replacementChar);
                    mdoSong.setLocation(theoricalFileName);
                    daoSong.save(mdoSong);

                    File fold = new File(oldLocation);
                    fnew = new File(mdoSong.calculateAbsolutePath(settings));
                    if (!fold.getAbsolutePath().equals(fnew.getAbsolutePath())) {
                        FileUtils.moveFile(fold, fnew);
                    }
                }
            }

            AudioTaggerTAGWizardPlugin atp = new AudioTaggerTAGWizardPlugin();
            org.messic.server.api.tagwizard.service.Album salbum = new org.messic.server.api.tagwizard.service.Album();
            salbum.author = mdoAlbum.getAuthor().getName();
            salbum.name = mdoAlbum.getName();
            if (mdoAlbum.getComments() != null)
                salbum.comments = mdoAlbum.getComments();
            if (mdoAlbum.getGenre() != null)
                salbum.genre = mdoAlbum.getGenre().getName();
            salbum.year = mdoAlbum.getYear();

            org.messic.server.api.tagwizard.service.Song ssong = new org.messic.server.api.tagwizard.service.Song();
            ssong.track = mdoSong.getTrack();
            ssong.name = mdoSong.getName();
            try {
                atp.saveTags(salbum, ssong, fnew);
            } catch (CannotReadException e) {
                log.error(e);
                // throw new IOException( e.getMessage(), e.getCause() );
            } catch (TagException e) {
                log.error(e);
                // throw new IOException( e.getMessage(), e.getCause() );
            } catch (ReadOnlyFileException e) {
                log.error(e);
                // throw new IOException( e.getMessage(), e.getCause() );
            } catch (InvalidAudioFrameException e) {
                log.error(e);
                // throw new IOException( e.getMessage(), e.getCause() );
            } catch (CannotWriteException e) {
                log.error(e);
                // throw new IOException( e.getMessage(), e.getCause() );
            }

        }
    }
    // 7.2 - Artwork resources
    if (album.getArtworks() != null && album.getArtworks().size() > 0) {
        List<org.messic.server.api.datamodel.File> files = album.getArtworks();
        for (org.messic.server.api.datamodel.File file : files) {
            if (file.getSid() <= 0) {
                MDOArtwork mdopr = new MDOArtwork();
                mdopr.setLocation(file.calculateSecureFileName(replacementChar));
                mdopr.setOwner(mdouser);
                mdopr.setAlbum(mdoAlbum);

                org.messic.server.api.datamodel.File fcover = album.getCover();
                if (fcover != null && file.getFileName().equals(album.getCover().getFileName())) {
                    mdopr.setCover(true);
                }

                daoPhysicalResource.save(mdopr);
                mdoAlbum.getArtworks().add(mdopr);

                // moving resource to the new location
                File tmpRes = new File(
                        userTmpPath + File.separatorChar + file.calculateSecureFileName(replacementChar));
                File newFile = new File(
                        currentAlbumPath + File.separatorChar + file.calculateSecureFileName(replacementChar));
                if (newFile.exists()) {
                    newFile.delete();
                }
                FileUtils.moveFileToDirectory(tmpRes, currentAlbumPathFile, false);
            } else {
                // existing artwork...
                MDOAlbumResource resource = daoAlbumResource.get(user.getLogin(), file.getSid());
                if (resource != null) {
                    String oldLocation = resource.calculateAbsolutePath(settings);
                    resource.setLocation(file.calculateSecureFileName(replacementChar));
                    daoAlbumResource.save(resource);

                    File fold = new File(oldLocation);
                    File fnew = new File(resource.calculateAbsolutePath(settings));
                    if (!fold.getAbsolutePath().equals(fnew.getAbsolutePath())) {
                        FileUtils.moveFile(fold, fnew);
                    }
                }
            }
        }
        daoAlbum.save(mdoAlbum);
    }

    // 7.3 - Other resources
    if (album.getOthers() != null && album.getOthers().size() > 0) {
        List<org.messic.server.api.datamodel.File> files = album.getOthers();
        for (org.messic.server.api.datamodel.File file : files) {
            if (file.getSid() <= 0) {
                MDOOtherResource mdopr = new MDOOtherResource();
                mdopr.setLocation(file.calculateSecureFileName(replacementChar));
                mdopr.setOwner(mdouser);
                mdopr.setAlbum(mdoAlbum);
                daoPhysicalResource.save(mdopr);
                mdoAlbum.getOthers().add(mdopr);

                // moving resource to the new location
                File tmpRes = new File(
                        userTmpPath + File.separatorChar + file.calculateSecureFileName(replacementChar));
                File newFile = new File(mdopr.calculateAbsolutePath(settings));
                if (newFile.exists()) {
                    newFile.delete();
                }
                FileUtils.moveFileToDirectory(tmpRes, currentAlbumPathFile, false);
            } else {
                // existing artwork...
                MDOAlbumResource resource = daoAlbumResource.get(user.getLogin(), file.getSid());
                if (resource != null) {
                    String oldLocation = resource.calculateAbsolutePath(settings);
                    resource.setLocation(file.calculateSecureFileName(replacementChar));
                    daoAlbumResource.save(resource);

                    File fold = new File(oldLocation);
                    File fnew = new File(resource.calculateAbsolutePath(settings));
                    if (!fold.getAbsolutePath().equals(fnew.getAbsolutePath())) {
                        FileUtils.moveFile(fold, fnew);
                    }
                }
            }
        }

        daoAlbum.save(mdoAlbum);
    }

    // let's see if the album was an existing one... then it should moved to the new location
    if (oldAlbumPath != null && !oldAlbumPath.equals(currentAlbumPath)) {
        List<MDOAlbumResource> resources = mdoAlbum.getAllResources();
        for (int i = 0; i < resources.size(); i++) {
            MDOAlbumResource resource = resources.get(i);
            String resourceNewPath = resource.calculateAbsolutePath(settings);
            String resourceCurrentPath = oldAlbumPath + File.separatorChar + resource.getLocation();
            File fnewPath = new File(resourceNewPath);
            File foldPath = new File(resourceCurrentPath);
            if (foldPath.exists()) {
                FileUtils.moveFile(foldPath, fnewPath);
            }
        }

        File fAlbumOldPath = new File(oldAlbumPath);
        FileUtils.deleteDirectory(fAlbumOldPath);
        // if the author have changed the name, we have only moved those resources from this album, but the author
        // could have other albums, we need to move also.
        if (flagAuthorNameChanged) {
            File newAuthorLocation = new File(mdoAuthor.calculateAbsolutePath(settings));
            // we must move all the authors albums to the new one folder
            File oldAuthorFolder = fAlbumOldPath.getParentFile();
            File[] oldfiles = oldAuthorFolder.listFiles();
            for (File file2 : oldfiles) {
                if (file2.isDirectory()) {
                    FileUtils.moveDirectoryToDirectory(file2, newAuthorLocation, true);
                }
            }

            // finally we remove the old location
            FileUtils.deleteDirectory(oldAuthorFolder);
        }
    }

    return sidResult;
}

From source file:org.nuxeo.launcher.config.ServerConfigurator.java

/**
 * Check server paths; warn if existing deprecated paths. Override this method to perform server specific checks.
 *
 * @throws ConfigurationException If deprecated paths have been detected
 * @since 5.4.2/*ww  w  . j  a  va2  s  .co  m*/
 */
public void checkPaths() throws ConfigurationException {
    File badInstanceClid = new File(generator.getNuxeoHome(),
            getDefaultDataDir() + File.separator + "instance.clid");
    if (badInstanceClid.exists() && !getDataDir().equals(badInstanceClid.getParentFile())) {
        log.warn(String.format("Moving %s to %s.", badInstanceClid, getDataDir()));
        try {
            FileUtils.moveFileToDirectory(badInstanceClid, getDataDir(), true);
        } catch (IOException e) {
            throw new ConfigurationException("NXP-6722 move failed: " + e.getMessage(), e);
        }
    }

    File oldPackagesPath = new File(getDataDir(), getDefaultPackagesDir());
    if (oldPackagesPath.exists() && !oldPackagesPath.equals(getPackagesDir())) {
        log.warn(String.format(
                "NXP-8014 Packages cache location changed. You can safely delete %s or move its content to %s",
                oldPackagesPath, getPackagesDir()));
    }

}

From source file:org.openmicroscopy.shoola.env.data.views.calls.ArchivedImageLoader.java

/**
 * Copies the specified file to the folder.
 * /*www .ja va 2  s .  co  m*/
 * @param f The file to copy.
 * @param folder The destination folder.
 * @return The destination file.
 * @throws Exception Thrown if an error occurred during the copy.
 */
private File copyFile(File f, File folder) throws Exception {
    //First check that the file exists
    File[] files = folder.listFiles();
    int count = 0;
    String fname = f.getName();
    String extension = FilenameUtils.getExtension(fname);
    String baseName = FilenameUtils.getBaseName(FilenameUtils.removeExtension(fname));
    if (files != null) {
        for (int i = 0; i < files.length; i++) {
            String v = files[i].getName();
            String value = baseName + "_(" + count + ")." + extension;
            if (v.equals(fname) || v.equals(value)) {
                count++;
            }
        }
    }
    if (count > 0) { //rename the file first.
        File to;
        if (override) {
            to = new File(folder, f.getName());
            to.delete();
        } else {
            to = new File(f.getParentFile(), baseName + "_(" + count + ")." + extension);
            FileUtils.copyFile(f, to);
            f = to;
        }
    }
    FileUtils.moveFileToDirectory(f, folder, false);
    return new File(folder, f.getName());
}

From source file:org.pieShare.pieShareApp.service.configurationService.ApplicationConfigurationService.java

@Override
public void setDatabaseFolder(File folder) {
    File db = getDatabaseFolder();
    addProperty("databaseDir", folder.toPath().toString());
    IPieDatabaseManagerFactory fact = beanService.getBean(PieDatabaseManagerFactory.class);
    fact.closeDB();//  ww w  . ja  v  a2  s .co  m
    try {
        for (File file : db.listFiles()) {
            if (file.isDirectory()) {
                FileUtils.moveDirectory(file, folder);
            } else {
                FileUtils.moveFileToDirectory(file, folder, false);
            }
        }
    } catch (IOException ex) {
        PieLogger.error(this.getClass(), "Error copy database to new location", ex);
    }

    fact.init();
}

From source file:org.pieshare.piespring.service.ApplicationConfigurationService.java

@Override
public void setDatabaseFolder(File folder) {
    File db = getDatabaseFolder();
    addProperty("databaseDir", folder.toPath().toString());
    //todo-sv: i thing this does not belong here!! if we move this then the class can go back to the pieShareApp package
    IPieDatabaseManagerFactory fact = beanService.getBean(DatabaseFactory.class);
    fact.closeDB();//from   w  w  w .  j a va2  s. c  o  m
    try {
        for (File file : db.listFiles()) {
            if (file.isDirectory()) {
                FileUtils.moveDirectory(file, folder);
            } else {
                FileUtils.moveFileToDirectory(file, folder, false);
            }
        }
    } catch (IOException ex) {
        PieLogger.error(this.getClass(), "Error copy database to new location", ex);
    }

    fact.init();
}

From source file:org.polymap.p4.imports.ops.ShapeImportOperation.java

@Override
public IStatus execute(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
    String shpBasename = FilenameUtils.getBaseName(shpFile.get().getAbsolutePath());

    try (ExceptionCollector<?> excs = Streams.exceptions();
            Updater update = P4Plugin.localCatalog().prepareUpdate();) {
        // filter basename, copy files to dataDir
        Arrays.stream(shpFile.get().getParentFile().listFiles())
                .filter(f -> f.getName().startsWith(shpBasename)).forEach(f -> excs.check(() -> {
                    if (!getDataDir().getAbsolutePath().equals(f.getParentFile().getAbsolutePath())) {
                        FileUtils.moveFileToDirectory(f, getDataDir(), true);
                    }//from w w w.j  a v  a 2s  . co  m
                    return null;
                }));

        // createcatalog entry
        String shpFileURL = new File(getDataDir(), shpFile.get().getName()).toURI().toURL().toString();
        update.newEntry(metadata -> {
            metadata.setTitle(shpFile.get().getName());
            metadata.setConnectionParams(ShapefileServiceResolver.createParams(shpFileURL));
        });
        update.commit();
        return Status.OK_STATUS;
    } catch (Exception e) {
        throw new ExecutionException(e.getMessage(), e);
    }
}

From source file:org.protocoderrunner.apprunner.api.PFileIO.java

@ProtoMethod(description = "Move a file to a directory", example = "")
@ProtoMethodParam(params = { "name", "destination" })
public void moveFileToDir(String name, String to) {
    File fromFile = new File(AppRunnerSettings.get().project.getStoragePath() + File.separator + name);
    File dir = new File(AppRunnerSettings.get().project.getStoragePath() + File.separator + to);

    dir.mkdirs();//from w  ww  .  j  av a2  s. c om
    try {
        FileUtils.moveFileToDirectory(fromFile, dir, false);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.silverpeas.core.io.file.SilverpeasFile.java

/**
 * Moves this file into the specified directory. If the directory doesn't exist, it is then
 * created before. Once the file is moved, it is not more existing. If the file doesn't exist,
 * then nothing is done and {@code NO_FILE} is returned.
 * <p>/*w  ww.  jav  a2 s .  com*/
 * A chain of post-processors will be ran once this file is moved to the directory to perform
 * possible additional treatments on the the moved file.
 * <p>
 * The moving operation will create a new file in the specified directory with the content of this
 * file and then delete this file. Consequently, a chain of post-processors will be ran against
 * the deleted file to perform additional treatments at file deletion.
 * @param directoryPath the absolute path of the directory into which this file has to be moved.
 * @return the SilverpeasFile located at the specified directory.
 * @throws java.io.IOException if an error occurs while moving this file into the specified
 * directory
 */
public SilverpeasFile moveInto(String directoryPath) throws IOException {
    SilverpeasFile movedFile = NO_FILE;
    if (exists()) {
        FileUtils.moveFileToDirectory(this, new File(directoryPath), true);
        movedFile = new SilverpeasFile(getComponentInstanceId(), directoryPath + File.separatorChar + getName(),
                getMimeType());
        SilverpeasFileProvider.processAfter(movedFile, SilverpeasFileProcessor.ProcessingContext.MOVING);
    }
    return movedFile;
}