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.evolveum.midpoint.tools.gui.PropertiesGenerator.java

private void cleanupTargetFolder(List<File> existingFiles, File target) throws IOException {
    Collection<File> files = FileUtils.listFiles(target, new String[] { "properties" }, true);

    for (File file : files) {
        if (existingFiles.contains(file)) {
            continue;
        }/*from   w  w w  . j av  a2s . c  om*/
        System.out.println("File to be deleted: " + file.getAbsolutePath());

        if (!config.isDisableBackup()) {
            File backupFile = new File(target, file.getName() + ".backup");
            FileUtils.moveFile(file, backupFile);
        } else {
            file.delete();
        }
    }
}

From source file:com.seleniumtests.it.stubclasses.StubTestClass.java

@Test(groups = "stub", description = "a test with steps")
public void testAndSubActions() throws IOException {
    TestStep step1 = new TestStep("step 1", TestLogging.getCurrentTestResult(), new ArrayList<>());
    step1.addAction(new TestAction("click button", false, new ArrayList<>()));
    step1.addAction(new TestAction("sendKeys to text field", true, new ArrayList<>()));

    ScreenShot screenshot = new ScreenShot();
    File tmpImg = File.createTempFile("img_with_very_very_very_long_name_to_be_shortened", ".png");
    File tmpHtml = File.createTempFile("html_with_very_very_very_long_name_to_be_shortened", ".html");

    screenshot.setImagePath("screenshot/" + tmpImg.getName());
    screenshot.setHtmlSourcePath("htmls/" + tmpHtml.getName());
    FileUtils.moveFile(tmpImg, new File(screenshot.getFullImagePath()));
    FileUtils.moveFile(tmpHtml, new File(screenshot.getFullHtmlPath()));

    step1.addSnapshot(new Snapshot(screenshot), 1, null);
    step1.setActionException(new WebDriverException("driver exception"));
    TestStep subStep1 = new TestStep("step 1.3: open page", TestLogging.getCurrentTestResult(),
            new ArrayList<>());
    subStep1.addAction(new TestAction("click link", false, new ArrayList<>()));
    subStep1.addMessage(new TestMessage("a message", MessageType.LOG));
    subStep1.addAction(new TestAction("sendKeys to password field", false, new ArrayList<>()));
    step1.addAction(subStep1);/*from   w w w . java 2  s . co  m*/
    WaitHelper.waitForSeconds(3);
    step1.setDuration(1230L);
    TestStep step2 = new TestStep("step 2", TestLogging.getCurrentTestResult(), new ArrayList<>());
    step2.setDuration(14030L);
    TestLogging.logTestStep(step1);
    TestLogging.logTestStep(step2);
}

From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java

/**
 * Detects whether using old configuration model and upgrades if necessary.
 * /* w ww.  ja v a 2  s. c  om*/
 * @param global
 * @throws SiteWhereException
 */
public static void migrateProjectStructureIfNecessary(IGlobalConfigurationResolver global)
        throws SiteWhereException {
    File root = new File(global.getConfigurationRoot());
    if (!root.exists()) {
        throw new SiteWhereException("Configuration root does not exist.");
    }
    File templateFolder = new File(root, FileSystemTenantConfigurationResolver.DEFAULT_TENANT_TEMPLATE_FOLDER);
    if (!templateFolder.exists()) {
        if (!templateFolder.mkdir()) {
            throw new SiteWhereException("Unable to create template folder.");
        }
        for (String filename : OLD_TEMPLATE_FILENAMES) {
            File templateFile = new File(root, filename);
            if (templateFile.exists()) {
                migrateTemplateFile(root, templateFolder, filename);
                migrateResources(root, templateFolder);
                break;
            }
        }
    }

    // Migrate tenant configuration files to separate directories.
    File tenants = new File(root, FileSystemTenantConfigurationResolver.TENANTS_FOLDER);
    if (!tenants.exists()) {
        if (!tenants.mkdir()) {
            throw new SiteWhereException("Unable to create tenant resources folder.");
        }
    }
    Collection<File> oldConfigs = FileUtils.listFiles(root, FileFilterUtils.suffixFileFilter("-tenant.xml"),
            null);
    for (File oldConfig : oldConfigs) {
        int dash = oldConfig.getName().lastIndexOf('-');
        String tenantName = oldConfig.getName().substring(0, dash);
        File tenantFolder = new File(tenants, tenantName);
        try {
            FileUtils.copyDirectory(templateFolder, tenantFolder);
            File tenantConfig = new File(tenantFolder,
                    FileSystemTenantConfigurationResolver.DEFAULT_TENANT_CONFIGURATION_FILE + "."
                            + FileSystemTenantConfigurationResolver.TENANT_SUFFIX_ACTIVE);
            if (tenantConfig.exists()) {
                tenantConfig.delete();
            }
            FileUtils.moveFile(oldConfig, tenantConfig);
            oldConfig.delete();
        } catch (IOException e) {
            throw new SiteWhereException("Unable to copy template folder for tenant.");
        }
    }
}

From source file:de.uzk.hki.da.cb.ShortenFileNamesAction.java

@Override
public boolean implementation() throws FileNotFoundException, IOException {

    String metadataFile = o.getMetadata_file();

    // rename results of conversions
    for (Event e : o.getLatestPackage().getEvents()) {

        logger.debug("checking if event is CONVERT for {}", e);

        if (!"CONVERT".equals(e.getType()))
            continue;

        logger.debug("event is CONVERT: {}", e);

        DAFile daFile = e.getTarget_file();
        if (!daFile.getRep_name().startsWith(WorkArea.TMP_PIPS))
            continue;

        final File file = wa.toFile(daFile);
        final String filePath = daFile.getRelative_path();
        logger.debug("filePath: " + filePath);
        String extension = FilenameUtils.getExtension(filePath);
        logger.debug("extension: " + extension);

        String newFilePath;//from  w w w . ja  v  a2s  .com
        if (filePath.equals(metadataFile)) {
            logger.warn("Metadata file should not be subject to a conversion!");
            continue;
        } else {
            final String hash = DigestUtils.md5Hex(filePath);
            logger.debug("hash: " + hash);
            newFilePath = "_" + hash + "." + extension;
        }

        logger.debug("newFilePath: " + newFilePath);
        File newFile = new File(file.getAbsolutePath().replaceAll(Pattern.quote(filePath) + "$", newFilePath));
        logger.debug("newFile: " + newFile.getAbsolutePath());

        daFile.setRelative_path(newFilePath);
        FileUtils.moveFile(file, newFile);
        map.put(newFilePath, filePath);

        deleteEmptyDirsRecursively(file.getAbsolutePath());

    }

    return true;

}

From source file:com.linkedin.pinot.tools.admin.command.StarTreeOnHeapToOffHeapConverter.java

@Override
public boolean execute() throws Exception {
    File indexDir = new File(_segmentDir);
    long start = System.currentTimeMillis();

    LOGGER.info("Loading segment {}", indexDir.getName());
    IndexSegment segment = Loaders.IndexSegment.load(indexDir, ReadMode.heap);

    long end = System.currentTimeMillis();
    LOGGER.info("Loaded segment {} in {} ms ", indexDir.getName(), (end - start));

    start = end;/*  w w  w. j a  v  a  2 s.  c  om*/
    StarTreeInterf starTreeOnHeap = segment.getStarTree();
    File starTreeOffHeapFile = new File(TMP_DIR,
            (V1Constants.STAR_TREE_INDEX_FILE + System.currentTimeMillis()));

    // Convert the star tree on-heap to off-heap format.
    StarTreeSerDe.writeTreeOffHeapFormat(starTreeOnHeap, starTreeOffHeapFile);

    // Copy all the indexes into output directory.
    File outputDir = new File(_outputDir);
    FileUtils.deleteQuietly(outputDir);
    FileUtils.copyDirectory(indexDir, outputDir);

    // Delete the existing star tree on-heap file from the output directory.
    FileUtils.deleteQuietly(new File(_outputDir, V1Constants.STAR_TREE_INDEX_FILE));

    // Move the temp star tree off-heap file into the output directory.
    FileUtils.moveFile(starTreeOffHeapFile, new File(_outputDir, V1Constants.STAR_TREE_INDEX_FILE));
    end = System.currentTimeMillis();

    LOGGER.info("Converted segment: {} ms", (end - start));
    return true;
}

From source file:com.qualinsight.mojo.cobertura.core.AbstractCleaningReportMojo.java

private void cleanupFileSystem(final File classesDirectory, final File backupClassesDirectory,
        final File baseDataFile, final File destinationDataFile) throws MojoExecutionException {
    getLog().debug("Cleaning up file system after Cobertura report generation");
    try {/*from w  w  w . j av  a  2  s .  c om*/
        FileUtils.forceDelete(classesDirectory);
        FileUtils.moveDirectory(backupClassesDirectory, classesDirectory);
        FileUtils.moveFile(baseDataFile, destinationDataFile);
    } catch (final IOException e) {
        final String message = "An error occurred during file system cleanup: ";
        getLog().error(message, e);
        throw new MojoExecutionException(message, e);
    }
}

From source file:fr.sanofi.fcl4transmart.controllers.listeners.clinicalData.SelectIdentifiersListener.java

@Override
public void handleEvent(Event event) {
    //write in a new file
    File file = new File(this.dataType.getPath().toString() + File.separator
            + this.dataType.getStudy().toString() + ".columns.tmp");
    try {//from   w w  w  .jav  a 2 s.  c  o  m
        Vector<String> subjectIds = this.setSubjectsIdUI.getSubjectIds();
        for (String s : subjectIds) {
            if (s.compareTo("") == 0) {
                this.setSubjectsIdUI.displayMessage("Subjects identifier columns have to be choosen");
                return;
            }
        }

        FileWriter fw = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fw);
        out.write(
                "Filename\tCategory Code\tColumn Number\tData Label\tData Label Source\tControlled Vocab Code\n");

        //subject identifier
        Vector<File> rawFiles = ((ClinicalData) this.dataType).getRawFiles();
        for (int i = 0; i < rawFiles.size(); i++) {
            int columnNumber = FileHandler.getHeaderNumber(rawFiles.elementAt(i), subjectIds.elementAt(i));
            if (columnNumber != -1) {
                out.write(rawFiles.elementAt(i).getName() + "\t\t" + columnNumber + "\tSUBJ_ID\t\t\n");
            }
        }
        if (((ClinicalData) this.dataType).getCMF() == null) {
            out.close();
            File fileDest = new File(this.dataType.getPath().toString() + File.separator
                    + this.dataType.getStudy().toString() + ".columns");
            FileUtils.moveFile(file, fileDest);
            ((ClinicalData) this.dataType).setCMF(fileDest);
            WorkPart.updateSteps();
        } else {
            try {
                BufferedReader br = new BufferedReader(new FileReader(((ClinicalData) this.dataType).getCMF()));
                String line = br.readLine();
                while ((line = br.readLine()) != null) {
                    String[] s = line.split("\t", -1);
                    if (s[3].compareTo("SUBJ_ID") != 0) {
                        out.write(line + "\n");
                    }
                }
                br.close();
            } catch (Exception e) {
                this.setSubjectsIdUI.displayMessage("Error: " + e.getLocalizedMessage());
                e.printStackTrace();
                out.close();
            }
            out.close();
            try {
                String fileName = ((ClinicalData) this.dataType).getCMF().getName();
                ((ClinicalData) this.dataType).getCMF().delete();
                File fileDest = new File(this.dataType.getPath() + File.separator + fileName);
                FileUtils.moveFile(file, fileDest);
                ((ClinicalData) this.dataType).setCMF(fileDest);
            } catch (IOException ioe) {
                this.setSubjectsIdUI.displayMessage("File errorrror: " + ioe.getLocalizedMessage());
                return;
            }

        }
    } catch (Exception e) {
        this.setSubjectsIdUI.displayMessage("Error: " + e.getLocalizedMessage());
        e.printStackTrace();
    }
    this.setSubjectsIdUI.displayMessage("Column mapping file updated");
    WorkPart.updateSteps();
    WorkPart.updateFiles();
    UsedFilesPart.sendFilesChanged(dataType);
}

From source file:it.duplication.CrossModuleDuplicationsTest.java

@Test
// SONAR-6184//  w  ww. ja  va 2 s  .c o m
public void testGhostDuplication() throws IOException {
    analyzeProject(projectDir, PROJECT_KEY, true);

    verifyDuplicationMeasures(PROJECT_KEY + ":module1", 1, 27, 1, 45);
    verifyDuplicationMeasures(PROJECT_KEY + ":module2", 1, 27, 1, 75);

    // move File2 from module1 to module2
    File src = FileUtils.getFile(projectDir, "module1", "src", "main", "xoo", "sample", "File2.xoo");
    File dst = FileUtils.getFile(projectDir, "module2", "src", "main", "xoo", "sample", "File2.xoo");
    FileUtils.moveFile(src, dst);

    src = new File(src.getParentFile(), "File2.xoo.measures");
    dst = new File(dst.getParentFile(), "File2.xoo.measures");
    FileUtils.moveFile(src, dst);

    // duplication should remain unchanged (except for % of duplication)
    analyzeProject(projectDir, PROJECT_KEY, false);
    verifyDuplicationMeasures(PROJECT_KEY + ":module1", 1, 27, 1, 75);
    verifyDuplicationMeasures(PROJECT_KEY + ":module2", 1, 27, 1, 45);
}

From source file:com.github.cbismuth.fdupes.io.PathOrganizer.java

private void onTimestampPath(final PathElement pathElement, final Path timestampPath) {
    try {//from ww w . ja  v a2 s.  c om
        FileUtils.moveFile(pathElement.getPath().toFile(), timestampPath.toFile());
    } catch (final IOException e) {
        LOGGER.error(e.getMessage());
    }
}

From source file:com.jaeksoft.searchlib.config.ConfigFileRotation.java

public void delete(VersionFile versionFile) throws IOException {
    lock.rl.lock();//from w  w w  .j  a v  a2 s .c om
    try {
        freeTempPrintWriter();
        if (oldFile.exists())
            oldFile.delete();
        if (masterFile.exists())
            FileUtils.moveFile(masterFile, oldFile);
        versionFile.increment();
    } finally {
        lock.rl.unlock();
    }
}