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

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

Introduction

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

Prototype

public static void moveFile(File srcFile, File destFile) throws IOException 

Source Link

Document

Moves a file.

Usage

From source file:com.microsoft.applicationinsights.internal.channel.common.TransmissionFileSystemOutput.java

private boolean renameToPermanentName(File tempTransmissionFile) {
    File transmissionFile = new File(folder,
            FilenameUtils.getBaseName(tempTransmissionFile.getName()) + TRANSMISSION_FILE_EXTENSION);
    try {/*from   ww  w .j  av  a  2s.c  o  m*/
        long fileLength = tempTransmissionFile.length();
        FileUtils.moveFile(tempTransmissionFile, transmissionFile);
        size.addAndGet(fileLength);
        return true;
    } catch (Exception e) {
        InternalLogger.INSTANCE.error("Rename To Permanent Name failed, exception: %s", e.getMessage());
    }

    return false;
}

From source file:edu.isi.wings.portal.controllers.ComponentController.java

public boolean renameComponentItem(String cid, String path, String newname) {
    try {/* w w w.  j  ava2 s  .co  m*/
        String loc = cc.getComponentLocation(cid);
        if (loc != null && path != null) {
            loc = loc + "/" + path;
            File f = new File(loc);
            File newf = new File(f.getParent() + newname);
            if (!newf.exists()) {
                if (f.isDirectory())
                    FileUtils.moveDirectory(f, newf);
                else if (f.isFile())
                    FileUtils.moveFile(f, newf);
                return true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        cc.end();
        dc.end();
        prov.end();
    }
    return false;
}

From source file:com.thoughtworks.go.plugin.infra.monitor.DefaultPluginJarLocationMonitorTest.java

@Test
void shouldNotifyRemoveEventBeforeAddEventInCaseOfFileRename() throws Exception {
    monitor.addPluginJarChangeListener(changeListener);
    monitor.start();//from w  w  w. ja  v  a2  s .c  o  m

    copyPluginToThePluginDirectory(bundledPluginDir, "descriptor-aware-test-plugin-1.jar");
    waitUntilNextRun(monitor);
    PluginFileDetails orgFile = pluginFileDetails(bundledPluginDir, "descriptor-aware-test-plugin-1.jar", true);
    verify(changeListener).pluginJarAdded(orgFile);

    PluginFileDetails newFile = pluginFileDetails(bundledPluginDir, "descriptor-aware-test-plugin-1-new.jar",
            true);
    FileUtils.moveFile(orgFile.file(), newFile.file());

    waitUntilNextRun(monitor);

    InOrder inOrder = inOrder(changeListener);
    inOrder.verify(changeListener).pluginJarRemoved(orgFile);
    inOrder.verify(changeListener).pluginJarAdded(newFile);
    verifyNoMoreInteractions(changeListener);
}

From source file:com.microsoft.applicationinsights.internal.channel.common.TransmissionFileSystemOutput.java

private Optional<File> renameToTemporaryName(File tempTransmissionFile) {
    File transmissionFile = null;
    try {//  w w  w. j ava  2 s.c o  m
        File renamedFile = new File(folder,
                FilenameUtils.getBaseName(tempTransmissionFile.getName()) + TEMP_FILE_EXTENSION);
        FileUtils.moveFile(tempTransmissionFile, renamedFile);
        size.addAndGet(-renamedFile.length());
        transmissionFile = renamedFile;
    } catch (Exception ignore) {
        InternalLogger.INSTANCE.error("Rename To Temporary Name failed, exception: %s", ignore.getMessage());
        // Consume the exception, since there isn't anything 'smart' to do now
    }

    return Optional.fromNullable(transmissionFile);
}

From source file:alluxio.multi.process.MultiProcessCluster.java

/**
 * Copies the work directory to the artifacts folder.
 *///from   w  w w  .  j  a v  a2 s .  c  o m
public synchronized void saveWorkdir() throws IOException {
    Preconditions.checkState(mState == State.STARTED,
            "cluster must be started before you can save its work directory");
    ARTIFACTS_DIR.mkdirs();

    File tarball = new File(mWorkDir.getParentFile(), mWorkDir.getName() + ".tar.gz");
    // Tar up the work directory.
    ProcessBuilder pb = new ProcessBuilder("tar", "-czf", tarball.getName(), mWorkDir.getName());
    pb.directory(mWorkDir.getParentFile());
    pb.redirectOutput(Redirect.appendTo(TESTS_LOG));
    pb.redirectError(Redirect.appendTo(TESTS_LOG));
    Process p = pb.start();
    try {
        p.waitFor();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
    // Move tarball to artifacts directory.
    File finalTarball = new File(ARTIFACTS_DIR, tarball.getName());
    FileUtils.moveFile(tarball, finalTarball);
    LOG.info("Saved cluster {} to {}", mClusterName, finalTarball.getAbsolutePath());
}

From source file:edu.wisc.nexus.auth.gidm.config.AbstractRefreshingFileLoader.java

private void saveConfiguration(final C configuration) {
    final Logger logger = this.getLogger();

    final File configurationFile = this.getConfigurationFile();
    try {//from w w  w . j  av  a 2  s . c o  m
        //Save to temp file then move into place to avoid breaking existing config file on error 
        final File tempFile = File.createTempFile(configurationFile.getName() + ".", ".tmp",
                configurationFile.getParentFile());

        Writer w = null;
        try {
            w = new FileWriter(tempFile);
            logger.info("Saving configuration file: " + configurationFile.getAbsolutePath());
            this.writeConfiguration(w, configuration);
        } finally {
            IOUtils.closeQuietly(w);
        }

        //Move dance to avoid losing data
        FileUtils.deleteQuietly(configurationFile);
        FileUtils.moveFile(tempFile, configurationFile);
        FileUtils.deleteQuietly(tempFile);
    } catch (final FileNotFoundException e) {
        logger.warn("Configuration file does not exist: " + configurationFile.getAbsolutePath()
                + ", nothing will be saved", e);
        return;
    } catch (final IOException e) {
        logger.warn("IOException while saving file: " + configurationFile.getAbsolutePath()
                + ", nothing will be saved", e);
        return;
    }

    this.lastModified = configurationFile.lastModified();
    this.lastSize = configurationFile.length();
}

From source file:edu.ucsb.eucalyptus.storage.fs.FileSystemStorageManager.java

public void renameObject(String bucket, String oldName, String newName) throws IOException {
    File oldObjectFile = new File(rootDirectory + FILE_SEPARATOR + bucket + FILE_SEPARATOR + oldName);
    File newObjectFile = new File(rootDirectory + FILE_SEPARATOR + bucket + FILE_SEPARATOR + newName);
    if (oldObjectFile.exists()) {
        FileUtils.forceDelete(oldObjectFile);
        FileUtils.moveFile(oldObjectFile, newObjectFile);
        //         newObjectFile.delete();
        //         if (!oldObjectFile.renameTo(newObjectFile)) {
        //            throw new IOException("Unable to rename " + oldObjectFile.getAbsolutePath() + " to "
        //                  + newObjectFile.getAbsolutePath());
        //         }
    }//w  ww .  ja va  2  s  . c  o  m
}

From source file:eu.edisonproject.training.execute.Main.java

private static void calculateTFIDF(String in, String out) throws IOException {
    File tmpFolder = null;//from  ww w .j ava2  s.c  om
    try {
        String contextName = FilenameUtils.removeExtension(in.substring(in.lastIndexOf(File.separator) + 1));
        ITFIDFDriver tfidfDriver = new TFIDFDriverImpl(contextName);
        File inFile = new File(in);

        String workingFolder = System.getProperty("working.folder");
        if (workingFolder == null) {
            workingFolder = prop.getProperty("working.folder", System.getProperty("java.io.tmpdir"));
        }

        tmpFolder = new File(workingFolder + File.separator + System.currentTimeMillis());

        tmpFolder.mkdir();
        tmpFolder.deleteOnExit();

        setTFIDFDriverImplPaths(inFile, tmpFolder);

        tfidfDriver.executeTFIDF(tmpFolder.getAbsolutePath());
        tfidfDriver.driveProcessResizeVector();
        File ctxPath = new File(TFIDFDriverImpl.CONTEXT_PATH);
        for (File f : ctxPath.listFiles()) {
            if (FilenameUtils.getExtension(f.getName()).endsWith("csv")) {
                FileUtils.moveFile(f, new File(out + File.separator + f.getName()));
            }
        }
    } finally {
        if (tmpFolder != null && tmpFolder.exists()) {
            tmpFolder.delete();
            FileUtils.forceDelete(tmpFolder);
        }
    }
}

From source file:de.blizzy.backup.database.Database.java

public void initialize() {
    try {/*from ww w.  ja  v  a  2 s.co  m*/
        int sha256Length = DigestUtils.sha256Hex(StringUtils.EMPTY).length();

        factory.query("CREATE TABLE IF NOT EXISTS backups (" + //$NON-NLS-1$
                "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " + //$NON-NLS-1$
                "run_time DATETIME NOT NULL, " + //$NON-NLS-1$
                "num_entries INT NULL" + //$NON-NLS-1$
                ")") //$NON-NLS-1$
                .execute();

        int sampleBackupPathLength = Utils.createSampleBackupFilePath().length();
        factory.query("CREATE TABLE IF NOT EXISTS files (" + //$NON-NLS-1$
                "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " + //$NON-NLS-1$
                "backup_path VARCHAR(" + sampleBackupPathLength + ") NOT NULL, " + //$NON-NLS-1$ //$NON-NLS-2$
                "checksum VARCHAR(" + sha256Length + ") NOT NULL, " + //$NON-NLS-1$ //$NON-NLS-2$
                "length BIGINT NOT NULL, " + //$NON-NLS-1$
                "compression TINYINT NOT NULL" + //$NON-NLS-1$
                ")") //$NON-NLS-1$
                .execute();
        factory.query("CREATE INDEX IF NOT EXISTS idx_old_files ON files " + //$NON-NLS-1$
                "(checksum, length)") //$NON-NLS-1$
                .execute();

        factory.query("CREATE TABLE IF NOT EXISTS entries (" + //$NON-NLS-1$
                "id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, " + //$NON-NLS-1$
                "parent_id INT NULL, " + //$NON-NLS-1$
                "backup_id INT NOT NULL, " + //$NON-NLS-1$
                "type TINYINT NOT NULL, " + //$NON-NLS-1$
                "creation_time DATETIME NULL, " + //$NON-NLS-1$
                "modification_time DATETIME NULL, " + //$NON-NLS-1$
                "hidden BOOLEAN NOT NULL, " + //$NON-NLS-1$
                "name VARCHAR(1024) NOT NULL, " + //$NON-NLS-1$
                "name_lower VARCHAR(1024) NOT NULL, " + //$NON-NLS-1$
                "file_id INT NULL" + //$NON-NLS-1$
                ")") //$NON-NLS-1$
                .execute();
        factory.query("CREATE INDEX IF NOT EXISTS idx_entries_files ON entries " + //$NON-NLS-1$
                "(file_id)") //$NON-NLS-1$
                .execute();
        factory.query("CREATE INDEX IF NOT EXISTS idx_folder_entries ON entries " + //$NON-NLS-1$
                "(backup_id, parent_id)") //$NON-NLS-1$
                .execute();
        factory.query("DROP INDEX IF EXISTS idx_entries_names") //$NON-NLS-1$
                .execute();
        factory.query("CREATE INDEX IF NOT EXISTS idx_entries_names2 ON entries " + //$NON-NLS-1$
                "(name, backup_id, parent_id)") //$NON-NLS-1$
                .execute();

        if (!isTableColumnExistent("FILES", "COMPRESSION")) { //$NON-NLS-1$ //$NON-NLS-2$
            factory.query(
                    "ALTER TABLE files ADD compression TINYINT NULL DEFAULT " + Compression.GZIP.getValue()) //$NON-NLS-1$
                    .execute();
            factory.update(Tables.FILES)
                    .set(Tables.FILES.COMPRESSION, Byte.valueOf((byte) Compression.GZIP.getValue())).execute();
            factory.query("ALTER TABLE files ALTER COLUMN compression TINYINT NOT NULL") //$NON-NLS-1$
                    .execute();
        }

        if (getTableColumnSize("FILES", "CHECKSUM") != sha256Length) { //$NON-NLS-1$ //$NON-NLS-2$
            factory.query("ALTER TABLE files ALTER COLUMN " + //$NON-NLS-1$
                    "checksum VARCHAR(" + sha256Length + ") NOT NULL") //$NON-NLS-1$ //$NON-NLS-2$
                    .execute();
        }

        if (!isTableColumnExistent("ENTRIES", "NAME_LOWER")) { //$NON-NLS-1$ //$NON-NLS-2$
            factory.query("ALTER TABLE entries ADD name_lower VARCHAR(1024) NULL") //$NON-NLS-1$
                    .execute();
            factory.update(Tables.ENTRIES).set(Tables.ENTRIES.NAME_LOWER, Tables.ENTRIES.NAME.lower())
                    .execute();
            factory.query("ALTER TABLE entries ALTER COLUMN name_lower VARCHAR(1024) NOT NULL") //$NON-NLS-1$
                    .execute();
        }
        factory.query("CREATE INDEX IF NOT EXISTS idx_entries_search ON entries " + //$NON-NLS-1$
                "(backup_id, name_lower)") //$NON-NLS-1$
                .execute();

        if (getTableColumnSize("FILES", "BACKUP_PATH") != sampleBackupPathLength) { //$NON-NLS-1$ //$NON-NLS-2$
            Cursor<Record> cursor = null;
            try {
                cursor = factory.select(Tables.FILES.ID, Tables.FILES.BACKUP_PATH).from(Tables.FILES)
                        .fetchLazy();
                while (cursor.hasNext()) {
                    Record record = cursor.fetchOne();
                    String backupPath = record.getValue(Tables.FILES.BACKUP_PATH);
                    String backupFileName = StringUtils.substringAfterLast(backupPath, "/"); //$NON-NLS-1$
                    if (backupFileName.indexOf('-') > 0) {
                        Integer id = record.getValue(Tables.FILES.ID);
                        File backupFile = Utils.toBackupFile(backupPath, outputFolder);
                        File folder = backupFile.getParentFile();
                        int maxIdx = Utils.getMaxBackupFileIndex(folder);
                        int newIdx = maxIdx + 1;
                        String newBackupFileName = Utils.toBackupFileName(newIdx);
                        File newBackupFile = new File(folder, newBackupFileName);
                        FileUtils.moveFile(backupFile, newBackupFile);
                        String newBackupPath = StringUtils.substringBeforeLast(backupPath, "/") + "/" //$NON-NLS-1$//$NON-NLS-2$
                                + newBackupFileName;
                        factory.update(Tables.FILES).set(Tables.FILES.BACKUP_PATH, newBackupPath)
                                .where(Tables.FILES.ID.equal(id)).execute();
                    }
                }

                factory.query("ALTER TABLE files ALTER COLUMN backup_path VARCHAR(" + sampleBackupPathLength //$NON-NLS-1$
                        + ") NOT NULL") //$NON-NLS-1$
                        .execute();
            } finally {
                closeQuietly(cursor);
            }
        }

        factory.query("ANALYZE") //$NON-NLS-1$
                .execute();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:max.hubbard.bettershops.Shops.FileShop.java

public boolean setOwner(OfflinePlayer owner) {
    if (!ShopManager.atLimit(owner)) {
        List<Shop> s = ShopManager.playerShops.get(getOwner().getUniqueId());
        s.remove(this);
        List<Shop> s1 = new ArrayList<>();
        if (ShopManager.playerShops.containsKey(owner.getUniqueId())) {
            s1 = ShopManager.playerShops.get(owner.getUniqueId());
        }/*from w  ww  .  j  a  va 2s  .co  m*/
        s1.add(this);
        ShopManager.playerShops.put(getOwner().getUniqueId(), s);
        ShopManager.playerShops.put(owner.getUniqueId(), s1);

        File fi = new File(Bukkit.getPluginManager().getPlugin("BetterShops").getDataFolder(),
                "Shops/" + owner.getUniqueId().toString() + "/" + getName() + ".yml");
        File old = file;
        try {
            FileUtils.moveFile(file, fi);
            file = fi;
            old.delete();
            setObject("Owner", owner.getUniqueId().toString());
            this.owner = owner;
            return true;
        } catch (Exception e) {
            return false;
        }
    } else {
        return false;
    }
}