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:org.mule.module.launcher.DomainArchiveDeployer.java

private void deployBundleApps(Domain domain) {
    File domainFolder = new File(domainDeployer.getDeploymentDirectory(), domain.getArtifactName());
    File appsFolder = new File(domainFolder, DOMAIN_BUNDLE_APPS_FOLDER);
    if (appsFolder.exists()) {
        File[] files = appsFolder.listFiles(new FilenameFilter() {
            @Override/*from  w  w w . ja v a 2 s. c  o  m*/
            public boolean accept(File dir, String name) {
                return name.endsWith(".zip");
            }
        });
        for (File file : files) {
            try {
                FileUtils.moveFile(file,
                        new File(MuleContainerBootstrapUtils.getMuleAppsDir(), file.getName()));
            } catch (IOException e) {
                logger.warn(e.getMessage());
                if (logger.isDebugEnabled()) {
                    logger.debug(e);
                }
            }
        }
    }
}

From source file:org.mycontroller.standalone.backup.Backup.java

public static synchronized String backup(String prefix) throws McException, IOException {
    //backup database
    //backup configuration file
    //backup certificates
    //backup logback xml file
    String backupZipFileName = null;
    if (BRCommons.isBackupRestoreRunning()) {
        throw new BadRequestException("A backup or restore is running");
    }//from w  ww  . j a  v a2 s. co m

    BRCommons.setBackupRestoreRunning(true);
    String applicationBackupDir = AppProperties.getInstance().getBackupSettings().getBackupLocation() + prefix
            + BRCommons.FILE_NAME_IDENTITY + "_" + AppProperties.getInstance().getDbType().name().toLowerCase()
            + new SimpleDateFormat("-yyyy_MM_dd-HH_mm_ss").format(new Date());
    //Create parent dir if not exist
    try {
        FileUtils.forceMkdir(FileUtils.getFile(applicationBackupDir));
        boolean includeDdBackup = false;
        if (AppProperties.getInstance().getDbType() == DB_TYPE.H2DB_EMBEDDED) {
            includeDdBackup = true;
        } else if (AppProperties.getInstance().getDbType() == DB_TYPE.H2DB
                && AppProperties.getInstance().includeDbBackup()) {
            includeDdBackup = true;
        }

        if (includeDdBackup) {
            String databaseBackup = AppProperties.getInstance().getTmpLocation() + BRCommons.DATABASE_FILENAME;

            if (DataBaseUtils.backupDatabase(databaseBackup)) {
                //Copy database file
                FileUtils.moveFile(FileUtils.getFile(databaseBackup),
                        FileUtils.getFile(applicationBackupDir + File.separator + BRCommons.DATABASE_FILENAME));
                //copy static files
            } else {
                throw new McException("Database backup failed!");
            }
        }

        //copy static files
        copyStaticFiles(applicationBackupDir);
        _logger.debug("Copied all the files");
        //create zip file
        McUtils.createZipFile(applicationBackupDir, applicationBackupDir + ".zip");
        _logger.debug("zip file creation done");
        //clean temporary files
        FileUtils.deleteDirectory(FileUtils.getFile(applicationBackupDir));
        return backupZipFileName;

    } catch (IOException ex) {
        _logger.error("Exception,", ex);
        throw ex;
    } finally {
        BRCommons.setBackupRestoreRunning(false);
    }

}

From source file:org.mycontroller.standalone.BackupRestore.java

public static synchronized void backup(String prefix) {
    //backup database
    //backup configuration file
    //backup certificates
    //backup logback xml file

    if (isbackupRestoreRunning) {
        throw new BadRequestException("A backup or restore is running");
    }/*from   w w w. j  a va 2 s .  co m*/

    isbackupRestoreRunning = true;
    String applicationBackupDir = ObjectFactory.getAppProperties().getBackupSettings().getBackupLocation()
            + prefix + FILE_NAME_IDENTITY + new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss").format(new Date());
    //Create parent dir if not exist
    try {
        FileUtils.forceMkdir(FileUtils.getFile(applicationBackupDir));
        String databaseBackup = ObjectFactory.getAppProperties().getTmpLocation() + DATABASE_FILENAME;
        if (DataBaseUtils.backupDatabase(databaseBackup)) {
            //Copy database file
            FileUtils.moveFile(FileUtils.getFile(databaseBackup),
                    FileUtils.getFile(applicationBackupDir + "/" + DATABASE_FILENAME));
            //copy static files
            copyStaticFiles(applicationBackupDir);
            _logger.debug("Copied all the files");
            final ZipOutputStream outZip = new ZipOutputStream(
                    new FileOutputStream(applicationBackupDir + ".zip"));
            //add database file
            MycUtils.addToZipFile(applicationBackupDir + "/" + DATABASE_FILENAME, outZip);
            //add properties file
            MycUtils.addToZipFile(applicationBackupDir + "/" + APP_PROPERTIES_FILENAME, outZip);
            //add keystore file, if https enabled
            if (ObjectFactory.getAppProperties().isWebHttpsEnabled() && KEY_STORE_FILE != null) {
                MycUtils.addToZipFile(KEY_STORE_FILE, outZip);
            }
            //compress all the files
            outZip.close();
            _logger.debug("zip file creation done");
            //clean temporary files
            FileUtils.deleteDirectory(FileUtils.getFile(applicationBackupDir));
        } else {
            //Throw exception
        }
    } catch (IOException ex) {
        _logger.error("Exception,", ex);
    } finally {
        isbackupRestoreRunning = false;
    }

}

From source file:org.mycontroller.standalone.BackupRestore.java

public static void restore(BackupFile backupFile) throws IOException {
    if (isbackupRestoreRunning) {
        throw new BadRequestException("A backup or restore is running");
    }//from   w w w  .  j  a v  a2s . c o  m

    if (!backupFile.getName().contains(FILE_NAME_IDENTITY)) {
        throw new BadRequestException("backup file name should contain '" + FILE_NAME_IDENTITY
                + "'. Your input:" + backupFile.getName());
    }

    isbackupRestoreRunning = true;

    String extractedLocation = ObjectFactory.getAppProperties().getTmpLocation()
            + backupFile.getName().replaceAll(".zip", "");
    try {

        String oldDatabaseLocation = ObjectFactory.getAppProperties().getDbH2DbLocation();
        //Extract zip file
        _logger.debug("Zip file:{}", backupFile.getAbsolutePath());

        extractZipFile(backupFile.getAbsolutePath(), extractedLocation);
        _logger.debug("All the files extracted to '{}'", extractedLocation);

        //Validate required files
        if (!FileUtils.getFile(extractedLocation + "/" + DATABASE_FILENAME).exists()) {
            _logger.error("Unable to continue restore opration! selected file not found! File:{}",
                    extractedLocation + "/" + DATABASE_FILENAME);
            return;
        }

        //Stop all services
        StartApp.stopServices();

        //Remove old properties file
        FileUtils.deleteQuietly(FileUtils.getFile(APP_CONF_LOCATION + APP_PROPERTIES_FILENAME));

        //Restore properties file
        FileUtils.moveFile(FileUtils.getFile(extractedLocation + "/" + APP_PROPERTIES_FILENAME),
                FileUtils.getFile(APP_CONF_LOCATION + APP_PROPERTIES_FILENAME));
        //Load initial properties
        StartApp.loadInitialProperties();

        //Remove old files
        FileUtils.deleteQuietly(FileUtils.getFile(ObjectFactory.getAppProperties().getWebSslKeystoreFile()));

        if (ObjectFactory.getAppProperties().isWebHttpsEnabled()) {
            //restore key store file
            FileUtils.moveFile(
                    FileUtils.getFile(extractedLocation + "/"
                            + FileUtils.getFile(ObjectFactory.getAppProperties().getWebSslKeystoreFile())
                                    .getName()),
                    FileUtils.getFile(ObjectFactory.getAppProperties().getWebSslKeystoreFile()));
        }

        //remove old database
        if (FileUtils.deleteQuietly(FileUtils.getFile(oldDatabaseLocation + ".h2.db"))) {
            _logger.debug("Old database removed successfully");
        } else {
            _logger.warn("Unable to remove old database");
        }
        //restore database
        if (DataBaseUtils.restoreDatabase(extractedLocation + "/" + DATABASE_FILENAME)) {
            _logger.info("Restore completed successfully. Start '{}' server manually",
                    AppProperties.APPLICATION_NAME);
        } else {
            _logger.error("Restore failed!");
        }

    } finally {
        //clean tmp file
        FileUtils.deleteQuietly(FileUtils.getFile(extractedLocation));
        _logger.debug("Tmp location[{}] clean success", extractedLocation);
        isbackupRestoreRunning = false;
    }
    //Stop application
    System.exit(0);
}

From source file:org.netkernelroc.gradle.apposite.Package.java

public void install(Connection connection, File nkInstance) throws Exception {
    PackageVersion toInstall = versions.last();
    File packageFile = toInstall.download(nkInstance, connection);

    File expandedPackage = NetKernelConvention.createTempDir();
    NetKernelConvention.expandZip(packageFile, expandedPackage);

    Document manifestDocument = new Builder().build(new File(expandedPackage, "manifest.xml"));
    Nodes modulesNodes = manifestDocument.query("/manifest/module");

    final String setInstalledSql = "UPDATE PACKAGE_VERSIONS SET INSTALLED=TRUE WHERE ID=?;";
    final PreparedStatement setInstalledPS = connection.prepareStatement(setInstalledSql);

    final String addTransactionEventSql = "INSERT INTO PACKAGE_TRANSACTION_EVENTS VALUES (\n" + "    NULL,\n"
            + "    @TRANSACTIONID,\n" + "    1,\n" + "    ?\n" + ");";
    final PreparedStatement addTransactionEventPS = connection.prepareStatement(addTransactionEventSql);

    final String addModuleSql = "MERGE INTO MODULES (\n" + "    PACKAGEVID,\n" + "    IDENTITY,\n"
            + "    VERSION,\n" + "    LOCALSRC,\n" + "    RUNLEVEL,\n" + "    EXPANDED\n" + ")\n"
            + "KEY (IDENTITY, VERSION)\n" + "VALUES (\n" + "    ?,\n" + "    ?,\n" + "    ?,\n" + "    ?,\n"
            + "    ?,\n" + "    ?\n" + ");";
    final PreparedStatement addModulePS = connection.prepareStatement(addModuleSql);

    setInstalledPS.clearParameters();/*from  www.  j  a va 2s  .co m*/
    setInstalledPS.setLong(1, toInstall.getId());
    setInstalledPS.executeUpdate();

    addTransactionEventPS.clearParameters();
    addTransactionEventPS.setLong(1, id);
    addTransactionEventPS.executeUpdate();

    for (int moduleI = 0; moduleI < modulesNodes.size(); moduleI++) {
        Node moduleNode = modulesNodes.get(moduleI);

        String uri = moduleNode.query("uri").get(0).getValue();
        String version = moduleNode.query("version").get(0).getValue();
        int runLevel = Integer.parseInt(moduleNode.query("runlevel").get(0).getValue());
        String source = moduleNode.query("source").get(0).getValue();
        boolean expand = Boolean.parseBoolean(moduleNode.query("expand").get(0).getValue());

        Integer[] versionArray = RepositorySet.stringArrayToIntArray(version.split("\\."));

        File targetFile;
        if (uri.startsWith("urn:com:ten60:core:")) {
            expand = false;
            targetFile = new File(nkInstance, "lib");
        } else {
            targetFile = new File(nkInstance, "modules");
        }

        File moduleJar = new File(expandedPackage, source);

        String baseName = uri.replaceAll(":", ".") + "-" + version;

        File target;
        File jarTarget = new File(targetFile, baseName + ".jar");
        File expandedTarget = new File(targetFile, baseName);

        if (expand) {
            target = expandedTarget;
        } else {
            target = jarTarget;
        }

        if (target.exists()) {
            System.out.println("Not moving module into place as it already exists");
        } else {
            if (expand) {
                System.out.println("Expanding module " + uri + " to " + expandedTarget.getAbsolutePath());
                NetKernelConvention.expandZip(moduleJar, expandedTarget);
            } else {
                System.out.println("Moving module " + uri + " to " + jarTarget.getAbsolutePath());
                FileUtils.moveFile(moduleJar, jarTarget);
            }
        }

        addModulePS.clearParameters();
        addModulePS.setLong(1, toInstall.getId());
        addModulePS.setString(2, uri);
        addModulePS.setObject(3, versionArray);
        addModulePS.setString(4, nkInstance.toURI().relativize(target.toURI()).getPath());
        addModulePS.setInt(5, runLevel);
        addModulePS.setBoolean(6, expand);
        addModulePS.executeUpdate();
    }
    FileUtils.deleteDirectory(expandedPackage);

    latestInstalledVersion = toInstall;
}

From source file:org.nuessler.maven.plugin.cakupan.CakupanReportMojo.java

@Override
protected void executeReport(final Locale locale) throws MavenReportException {
    if (!canGenerateReport()) {
        return;/*from   w  ww.j a va2s  . co  m*/
    }
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }
    getLog().info("Start Cakupan report mojo");
    getLog().info("report output dir: " + getOutputDirectory());

    try {
        Collection<File> coverageFiles = FileUtils.listFiles(instrumentDestDir, new String[] { "xml" }, false);
        for (File file : coverageFiles) {
            FileUtils.copyFileToDirectory(file, outputDirectory);
        }
    } catch (IOException e) {
        throw new MavenReportException(e.getMessage());
    }

    CoverageIOUtil.setDestDir(outputDirectory);
    try {
        XSLTCakupanUtil.generateCoverageReport();
        File destFile = new File(outputDirectory, "index.html");
        if (destFile.exists()) {
            destFile.delete();
        }
        FileUtils.moveFile(new File(outputDirectory, "xslt_summary.html"), destFile);
        Collection<File> datFiles = FileUtils.listFiles(outputDirectory, new String[] { "dat" }, false);
        for (File file : datFiles) {
            file.delete();
        }
    } catch (XSLTCoverageException e) {
        if (e.getRefId() == XSLTCoverageException.NO_COVERAGE_FILE) {
            getLog().error("No coverage files found in " + outputDirectory.getPath());
        } else {
            throw new MavenReportException("Failed to create the Cakupan coverage report", e);
        }
    } catch (IOException e) {
        throw new MavenReportException("Failed to move coverage report to correct location", e);
    }
    getLog().info("End Cakupan report mojo");
}

From source file:org.nuxeo.ecm.platform.publisher.impl.localfs.LocalFSPublicationTree.java

private void moveFile(File srcFile, File destFile) {
    try {/* ww  w .j a v  a  2  s  .  c  om*/
        FileUtils.moveFile(srcFile, destFile);
    } catch (IOException e) {
        throw new NuxeoException(e);
    }
}

From source file:org.nuxeo.runtime.deployment.preprocessor.PackZip.java

protected void executePackaging() throws IOException, SAXException, ParserConfigurationException {
    // move non ejb jars to nuxeo.ear/lib
    moveNonEjbsToLib(nuxeoEar);//from   w w  w .j a v  a 2s .co  m
    // replace nuxeo-structure.xml with nuxeo-structure-zip.xml
    replaceStructureFile();
    // move libs in jboss/lib to nuxeo.ear/lib
    moveJarsFromJbossLib();
    // move nuxeo jboss deployer to nuxeo.ear/lib
    FileUtils.moveFile(deployerJar, new File(nuxeoEar, "lib" + File.separator + deployerJar.getName()));
    // zip the ear into target directory
    ZipUtils.zip(nuxeoEar.listFiles(), new File(target, "nuxeo.ear"));
    // copy nuxeo-ds.xml to target dir
    FileUtils.copyFileToDirectory(dsFile, target);
}

From source file:org.nuxeo.runtime.deployment.preprocessor.PackZip.java

protected void replaceStructureFile() throws IOException {
    File oldf = new File(nuxeoEar, "META-INF" + File.separator + "nuxeo-structure.xml");
    File newf = new File(nuxeoEar, "META-INF" + File.separator + "nuxeo-structure-zip.xml");
    if (oldf.exists() && !FileUtils.deleteQuietly(oldf)) {
        log.warn("Cannot delete " + oldf.getName() + ", it may not replace it with the new file.");
    }//from  w  w w .j av a2 s  .co m
    FileUtils.moveFile(newf, oldf);
}

From source file:org.omegat.core.team2.ProjectTeamSettings.java

/**
 * Update setting./*  w w  w . ja va  2s. co m*/
 */
public synchronized void set(String key, String newValue) {
    try {
        Properties p = new Properties();
        File f = configFile;
        File fNew = new File(configFile.getAbsolutePath() + ".new");
        if (f.exists()) {
            try (FileInputStream in = new FileInputStream(f)) {
                p.load(in);
            }
        } else {
            f.getParentFile().mkdirs();
        }
        if (newValue != null) {
            p.setProperty(key, newValue);
        } else {
            p.remove(key);
        }
        try (FileOutputStream out = new FileOutputStream(fNew)) {
            p.store(out, null);
        }
        f.delete();
        FileUtils.moveFile(fNew, f);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}