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

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

Introduction

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

Prototype

public static void moveDirectory(File srcDir, File destDir) throws IOException 

Source Link

Document

Moves a directory.

Usage

From source file:com.blackducksoftware.integration.hub.detect.detector.go.DepPackager.java

private String getGopkgLockContents(final File file, final String goDepExecutable) throws IOException {
    String gopkgLockContents = null;

    final File gopkgLockFile = new File(file, "Gopkg.lock");
    if (gopkgLockFile.exists()) {
        try (FileInputStream fis = new FileInputStream(gopkgLockFile)) {
            gopkgLockContents = IOUtils.toString(fis, Charset.defaultCharset());
            logger.debug(gopkgLockContents);
        } catch (final Exception e) {
            gopkgLockContents = null;/* w w  w. j  a  va 2  s .co  m*/
        }
        return gopkgLockContents;
    }

    // by default, we won't run 'init' and 'ensure' anymore so just return an empty string
    if (!detectConfiguration.getBooleanProperty(DetectProperty.DETECT_GO_RUN_DEP_INIT,
            PropertyAuthority.None)) {
        logger.info("Skipping Dep commands 'init' and 'ensure'");
        return "";
    }

    final File gopkgTomlFile = new File(file, "Gopkg.toml");
    final File vendorDirectory = new File(file, "vendor");
    final boolean vendorDirectoryExistedBefore = vendorDirectory.exists();
    final File vendorDirectoryBackup = new File(file, "vendor_old");
    if (vendorDirectoryExistedBefore) {
        logger.info(String.format("Backing up %s to %s", vendorDirectory.getAbsolutePath(),
                vendorDirectoryBackup.getAbsolutePath()));
        FileUtils.moveDirectory(vendorDirectory, vendorDirectoryBackup);
    }

    final String goDepInitString = String.format("%s 'init' on path %s", goDepExecutable,
            file.getAbsolutePath());
    try {
        logger.info("Running " + goDepInitString);
        final Executable executable = new Executable(file, goDepExecutable, Arrays.asList("init"));
        executableRunner.execute(executable);
    } catch (final ExecutableRunnerException e) {
        logger.error(String.format("Failed to run %s: %s", goDepInitString, e.getMessage()));
    }

    final String goDepEnsureUpdateString = String.format("%s 'ensure -update' on path %s", goDepExecutable,
            file.getAbsolutePath());
    try {
        logger.info("Running " + goDepEnsureUpdateString);
        final Executable executable = new Executable(file, goDepExecutable, Arrays.asList("ensure", "-update"));
        executableRunner.execute(executable);
    } catch (final ExecutableRunnerException e) {
        logger.error(String.format("Failed to run %s: %s", goDepEnsureUpdateString, e.getMessage()));
    }

    if (gopkgLockFile.exists()) {
        try (FileInputStream fis = new FileInputStream(gopkgLockFile)) {
            gopkgLockContents = IOUtils.toString(fis, Charset.defaultCharset());
        } catch (final Exception e) {
            gopkgLockContents = null;
        }
        gopkgLockFile.delete();
        gopkgTomlFile.delete();
        FileUtils.deleteDirectory(vendorDirectory);
        if (vendorDirectoryExistedBefore) {
            logger.info(String.format("Restoring back up %s from %s", vendorDirectory.getAbsolutePath(),
                    vendorDirectoryBackup.getAbsolutePath()));
            FileUtils.moveDirectory(vendorDirectoryBackup, vendorDirectory);
        }
    }

    return gopkgLockContents;
}

From source file:inet.encode.Monitor.java

public static boolean moveToDeletedFolder(String idStr, String channel) {
    boolean result = true;
    String outputFolderRelative = Encoder.getOutputFolderRelativeFromIdAndChannel(idStr, channel);
    String outputFolderAbsolute = Encoder.getOutputFolderAbsoluteFromIdAndChannel(idStr, channel);

    //String processingFile = INPUT_FOLDER_TO_SCAN + File.separatorChar + FOLDER_PROCESSING + File.separatorChar + inputFile;
    String deletedFile = DELETED_FOLDER_ROOT_WITH_SLASH + outputFolderRelative;
    Logger.log(outputFolderAbsolute + " will be deleted: " + deletedFile);
    try {/*from  w  w w  .j a v a2 s.c om*/
        File f = new File(outputFolderAbsolute);
        File df = new File(deletedFile);
        FileUtils.moveDirectory(f, df);
    } catch (Exception ex) {
        Logger.log(ex);
        result = false;
    }

    return result;
}

From source file:i.am.jiongxuan.deapk.Deapk.java

public boolean decodeResources() {
    System.out.println(">>> (1/5) Decompiling all resource files and smali files...");

    Logger.getLogger(AndrolibResources.class.getName()).setLevel(Level.OFF);
    Logger.getLogger(Androlib.class.getName()).setLevel(Level.OFF);
    ApkDecoder apkDecoder = new ApkDecoder();
    try {//from w w w  .j  av a2s  .co m
        apkDecoder.setKeepBrokenResources(true);
        apkDecoder.setBaksmaliDebugMode(false);
        apkDecoder.setDebugMode(false);
        apkDecoder.setOutDir(mProjectDir);
        apkDecoder.setApkFile(mApkDir);
        apkDecoder.decode();
    } catch (AndrolibException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    if (mSmaliDir.exists()) {
        try {
            FileUtils.moveDirectory(mSmaliDir, mSrcDir);
        } catch (IOException e) {
            e.printStackTrace();
            // Rename the smali to src is not required, skip it if error.
        }
    }

    return true;
}

From source file:net.grinder.AgentUpdateHandler.java

void decompressDownloadPackage() {
    File interDir = new File(agentConfig.getHome().getTempDirectory(), "update_package_unpacked");
    File toDir = new File(agentConfig.getCurrentDirectory(), "update_package");
    interDir.mkdirs();/*from   w  w w  . j  a  va  2  s .  co m*/
    toDir.mkdirs();

    if (FilenameUtils.isExtension(download.getName(), "tar")) {
        File outFile = new File(toDir, "ngrinder-agent.tar");
        CompressionUtils.untar(download, interDir);
        FileUtils.deleteQuietly(outFile);
    } else {
        LOGGER.error("{} is not allowed to be unpacked.", download.getName());
    }

    try {
        FileUtils.deleteQuietly(toDir);
        FileUtils.moveDirectory(new File(interDir, "ngrinder-agent"), toDir);
    } catch (IOException e) {
        LOGGER.error("Error while moving a file ", e);
    }
    FileUtils.deleteQuietly(download);
    FileUtils.deleteQuietly(interDir);
}

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

/**
 * Migrate assets and scripts into template directory.
 * //from  w  w  w .  j  av  a2  s  .c  o m
 * @param root
 * @param templateFolder
 * @throws SiteWhereException
 */
protected static void migrateResources(File root, File templateFolder) throws SiteWhereException {
    // Move assets.
    File assets = new File(root, "assets");
    if (assets.exists()) {
        try {
            File newAssets = new File(templateFolder, FileSystemTenantConfigurationResolver.ASSETS_FOLDER);
            FileUtils.moveDirectory(assets, newAssets);
        } catch (IOException e) {
            throw new SiteWhereException("Unable to move assets folder to template.");
        }
    }

    // Move Groovy scripts.
    File scripts = new File(templateFolder, FileSystemTenantConfigurationResolver.SCRIPTS_FOLDER);
    if (!scripts.exists()) {
        if (!scripts.mkdir()) {
            throw new SiteWhereException("Unable to create scripts folder in template folder.");
        }
        try {
            File groovy = new File(root, "groovy");
            if (groovy.exists()) {
                File newGroovy = new File(scripts, "groovy");
                FileUtils.moveDirectory(groovy, newGroovy);
            }
        } catch (IOException e) {
            throw new SiteWhereException("Unable to move assets folder to template.");
        }
    }
}

From source file:modmanager.backend.Modification.java

private void load(File path) {
    logger.log(Level.INFO, "Loading modification from {0}", path.getAbsolutePath());

    if (!path.isDirectory()) {
        return;/* w w w .  j av  a2 s . c  o m*/
    }

    /**
     * Precheck: dir empty? (failed extraction)
     */
    if (path.list().length == 0) {
        path.delete();
        return;
    }

    /**
     * Precheck: archive ghost dir?
     */
    {
        File[] entries = path.listFiles();

        if (entries.length == 1) {
            File one = entries[0];

            if (one.isDirectory()) {
                if (!one.getName().equalsIgnoreCase("data")) {
                    try {
                        logger.log(Level.INFO,
                                "Moving directory, because someone decided it's good to pack all data into a sub directory ...");

                        /**
                         * It's a directory. Change filesystem by
                         * reparenting
                         */
                        File tmp = new File(path.getAbsolutePath() + ".tmp");

                        FileUtils.moveDirectory(one, tmp);
                        FileUtils.deleteDirectory(path);
                        FileUtils.moveDirectory(tmp, path);
                    } catch (IOException ex) {
                        logger.log(Level.SEVERE, ex.getMessage());

                        return;
                    }
                }
            }
        }
    }

    this.directory = path;

    /**
     * Read name
     */
    this.name = path.getName();

    /**
     * Wizard indicates
     */
    if ((new File(path, "Wizard.txt")).exists()) {
        this.type = Type.MULTIOPTION;
    } else {
        this.type = Type.MULTIOPTION;

        for (File sub : path.listFiles()) {
            if (FilenameUtils.wildcardMatch(sub.getName(), "*.bsa", IOCase.INSENSITIVE)) {
                this.type = Type.SIMPLE;
                break;
            } else if (FilenameUtils.wildcardMatch(sub.getName(), "*.esp", IOCase.INSENSITIVE)) {
                this.type = Type.SIMPLE;
                break;
            } else if (FilenameUtils.wildcardMatch(sub.getName(), "Meshes", IOCase.INSENSITIVE)) {
                this.type = Type.SIMPLE;
                break;
            } else if (FilenameUtils.wildcardMatch(sub.getName(), "Textures", IOCase.INSENSITIVE)) {
                this.type = Type.SIMPLE;
                break;
            } else if (FilenameUtils.wildcardMatch(sub.getName(), "data", IOCase.INSENSITIVE)) {
                this.type = Type.SIMPLE;
                break;
            }
        }
    }

    logger.log(Level.INFO, "... mod type detected: {0}", this.type);

    /**
     * OK, load the mod types from given type
     */
    switch (this.type) {
    /**
     * This is intended!
     */
    case MULTIOPTION: {
        for (File sub : path.listFiles()) {
            if (sub.isDirectory() && !sub.getName().equalsIgnoreCase("fomod")
                    && !sub.getName().toLowerCase().contains("readme")
                    && !sub.getName().toLowerCase().contains("manual")) {
                ModificationOption opt = new ModificationOption(this, sub);

                if (opt.getFileCount() != 0) {
                    options.put(opt.getName(), opt);
                }
            }
        }
    }
        break;
    case SIMPLE:

    {
        //Create new option based on modification path
        ModificationOption opt = new ModificationOption(this, path);

        if (opt.getFileCount() != 0) {
            options.put(opt.getName(), opt);
        }
    }

        break;
    }

    /**
     * Load screenshots
     */
    for (File file : getScreenshotImages()) {
        status.addScreenshotImage(file);
    }

    if (!options.isEmpty()) {
        loaded = true;
    } else {
        logger.log(Level.WARNING, "Ignoring {0}: Empty!", name);
    }

}

From source file:brooklyn.util.io.FileUtil.java

public static void moveDir(File srcDir, File destDir) throws IOException, InterruptedException {
    if (!Os.isMicrosoftWindows()) {
        String cmd = "mv '" + srcDir.getAbsolutePath() + "' '" + destDir.getAbsolutePath() + "'";
        Process proc = Runtime.getRuntime().exec(cmd);
        proc.waitFor();/*ww w .  j a v a  2s .co  m*/
        if (proc.exitValue() == 0)
            return;
    }

    FileUtils.moveDirectory(srcDir, destDir);
}

From source file:com.door43.translationstudio.core.TargetTranslationMigrator.java

/**
 * Updated the id format of target translations
 * @param path/*from   w  w  w .jav a 2 s.  c o m*/
 * @return
 */
private static File v5(File path) throws Exception {
    File manifestFile = new File(path, MANIFEST_FILE);
    JSONObject manifest = new JSONObject(FileUtils.readFileToString(manifestFile));

    // pull info to build id
    String targetLanguageCode = manifest.getJSONObject("target_language").getString("id");
    String projectSlug = manifest.getJSONObject("project").getString("id");
    String translationTypeSlug = manifest.getJSONObject("type").getString("id");
    String resourceSlug = null;
    if (translationTypeSlug.equals("text")) {
        resourceSlug = manifest.getJSONObject("resource").getString("id");
    }

    // build new id
    String id = targetLanguageCode + "_" + projectSlug + "_" + translationTypeSlug;
    if (translationTypeSlug.equals("text") && resourceSlug != null) {
        id += "_" + resourceSlug;
    }

    // add license file
    File licenseFile = new File(path, "LICENSE.md");
    if (!licenseFile.exists()) {
        AssetManager am = AppContext.context().getAssets();
        InputStream is = am.open("LICENSE.md");
        if (is != null) {
            FileUtils.copyInputStreamToFile(is, licenseFile);
        } else {
            throw new Exception("Failed to open the template license file");
        }
    }

    // update package version
    manifest.put("package_version", 6);
    FileUtils.write(manifestFile, manifest.toString(2));

    // update target translation dir name
    File newPath = new File(path.getParentFile(), id.toLowerCase());
    FileUtilities.safeDelete(newPath);
    FileUtils.moveDirectory(path, newPath);
    return newPath;
}

From source file:com.linkedin.thirdeye.hadoop.backfill.BackfillControllerAPIs.java

/**
 * Downloads a segment from the controller, given the table name and segment name
 * @param segmentName/*from   w w  w .  j  ava2  s .c  o m*/
 * @param hdfsSegmentPath
 * @throws IOException
 * @throws ArchiveException
 */
public void downloadSegment(String segmentName, Path hdfsSegmentPath) throws IOException, ArchiveException {

    FileSystem fs = FileSystem.get(new Configuration());
    HttpClient controllerClient = new DefaultHttpClient();
    HttpGet req = new HttpGet(SEGMENTS_ENDPOINT + URLEncoder.encode(tableName, UTF_8) + "/"
            + URLEncoder.encode(segmentName, UTF_8));
    HttpResponse res = controllerClient.execute(controllerHttpHost, req);
    try {
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new IllegalStateException(res.getStatusLine().toString());
        }
        LOGGER.info("Fetching segment {}", segmentName);
        InputStream content = res.getEntity().getContent();

        File tempDir = new File(Files.createTempDir(), "thirdeye_temp");
        tempDir.mkdir();
        LOGGER.info("Creating temporary dir for staging segments {}", tempDir);
        File tempSegmentDir = new File(tempDir, segmentName);
        File tempSegmentTar = new File(tempDir, segmentName + ThirdEyeConstants.TAR_SUFFIX);

        LOGGER.info("Downloading {} to {}", segmentName, tempSegmentTar);
        OutputStream out = new FileOutputStream(tempSegmentTar);
        IOUtils.copy(content, out);
        if (!tempSegmentTar.exists()) {
            throw new IllegalStateException("Download of " + segmentName + " unsuccessful");
        }

        LOGGER.info("Extracting segment {} to {}", tempSegmentTar, tempDir);
        TarGzCompressionUtils.unTar(tempSegmentTar, tempDir);
        File[] files = tempDir.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return !name.endsWith(ThirdEyeConstants.TAR_SUFFIX) && new File(dir, name).isDirectory();
            }
        });
        if (files.length == 0) {
            throw new IllegalStateException("Failed to extract " + tempSegmentTar + " to " + tempDir);
        } else if (!files[0].getName().equals(tempSegmentDir.getName())) {
            LOGGER.info("Moving extracted segment to the segment dir {}", tempSegmentDir);
            FileUtils.moveDirectory(files[0], tempSegmentDir);
        }
        if (!tempSegmentDir.exists()) {
            throw new IllegalStateException("Failed to move " + files[0] + " to " + tempSegmentDir);
        }

        LOGGER.info("Copying segment from {} to hdfs {}", tempSegmentDir, hdfsSegmentPath);
        fs.copyFromLocalFile(new Path(tempSegmentDir.toString()), hdfsSegmentPath);
        Path hdfsSegmentDir = new Path(hdfsSegmentPath, segmentName);
        if (!fs.exists(hdfsSegmentDir)) {
            throw new IllegalStateException("Failed to copy segment " + segmentName + " from local path "
                    + tempSegmentDir + " to hdfs path " + hdfsSegmentPath);
        }
    } finally {
        if (res.getEntity() != null) {
            EntityUtils.consume(res.getEntity());
        }
    }
    LOGGER.info("Successfully downloaded segment {} to {}", segmentName, hdfsSegmentPath);
}

From source file:it.greenvulcano.util.file.FileManager.java

/**
 * Move a file/directory on the local file system.<br>
 *
 * @param oldPath//from   ww w . j a v  a2 s. c  o  m
 *            Absolute pathname of the file/directory to be renamed
 * @param newPath
 *            Absolute pathname of the new file/directory
 * @param filePattern
 *            A regular expression defining the name of the files to be copied. Used only if
 *            srcPath identify a directory. Null or "" disable file filtering.
 * @throws Exception
 */
public static void mv(String oldPath, String newPath, String filePattern) throws Exception {
    File src = new File(oldPath);
    if (!src.isAbsolute()) {
        throw new IllegalArgumentException("The pathname of the source is NOT absolute: " + oldPath);
    }
    File target = new File(newPath);
    if (!target.isAbsolute()) {
        throw new IllegalArgumentException("The pathname of the destination is NOT absolute: " + newPath);
    }
    if (target.isDirectory()) {
        if ((filePattern == null) || filePattern.equals("")) {
            FileUtils.deleteQuietly(target);
        }
    }
    if (src.isDirectory()) {
        if ((filePattern == null) || filePattern.equals("")) {
            logger.debug("Moving directory " + src.getAbsolutePath() + " to " + target.getAbsolutePath());
            FileUtils.moveDirectory(src, target);
        } else {
            Set<FileProperties> files = ls(oldPath, filePattern);
            for (FileProperties file : files) {
                logger.debug("Moving file " + file.getName() + " from directory " + src.getAbsolutePath()
                        + " to directory " + target.getAbsolutePath());
                File finalTarget = new File(target, file.getName());
                FileUtils.deleteQuietly(finalTarget);
                if (file.isDirectory()) {
                    FileUtils.moveDirectoryToDirectory(new File(src, file.getName()), finalTarget, true);
                } else {
                    FileUtils.moveFileToDirectory(new File(src, file.getName()), target, true);
                }
            }
        }
    } else {
        if (target.isDirectory()) {
            File finalTarget = new File(target, src.getName());
            FileUtils.deleteQuietly(finalTarget);
            logger.debug("Moving file " + src.getAbsolutePath() + " to directory " + target.getAbsolutePath());
            FileUtils.moveFileToDirectory(src, target, true);
        } else {
            logger.debug("Moving file " + src.getAbsolutePath() + " to " + target.getAbsolutePath());
            FileUtils.moveFile(src, target);
        }
    }
}