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:org.mobicents.servlet.restcomm.RvdProjectsMigrationHelper.java

public void renameProject(String source, String dest) throws IOException {
    File sourceDir = new File(workspacePath + File.separator + source);
    File destDir = new File(workspacePath + File.separator + dest);
    FileUtils.moveDirectory(sourceDir, destDir);
}

From source file:org.mule.module.git.GitConnectorTest.java

@Before
public void prepareExternalRepo() throws IOException {
    FileUtils.moveDirectory(new File(REMOTE_REPO, "git"), new File(REMOTE_REPO, ".git"));
}

From source file:org.mule.module.git.GitConnectorTest.java

@After
public void releaseExternalRepo() throws IOException {
    FileUtils.moveDirectory(new File(REMOTE_REPO, ".git"), new File(REMOTE_REPO, "git"));
}

From source file:org.mule.tools.npm.NPMModule.java

public void saveToFile(File file) throws MojoExecutionException {
    URL dl;//from w  w  w.  ja v  a 2 s .  c o  m
    OutputStream os = null;
    InputStream is = null;
    File outputFolderFileTmp = new File(file, name + "_tmp");
    File outputFolderFile = new File(file, name);

    if (outputFolderFile.exists()) {
        //Already downloaded nothing to do
        return;
    }

    outputFolderFileTmp.mkdirs();

    File tarFile = new File(outputFolderFileTmp, name + "-" + version + ".tgz");
    ProgressListener progressListener = new ProgressListener(log);
    log.debug("Downloading " + this.name + ":" + this.version);

    try {
        os = new FileOutputStream(tarFile);
        is = getDownloadURL().openStream();

        DownloadCountingOutputStream dcount = new DownloadCountingOutputStream(os);
        dcount.setListener(progressListener);

        getDownloadURL().openConnection().getHeaderField("Content-Length");

        IOUtils.copy(is, dcount);

    } catch (FileNotFoundException e) {
        throw new MojoExecutionException(String.format("Error downloading module %s:%s", name, version), e);
    } catch (IOException e) {
        throw new MojoExecutionException(String.format("Error downloading module %s:%s", name, version), e);
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
    }

    final TarGZipUnArchiver ua = new TarGZipUnArchiver();
    ua.enableLogging(new LoggerAdapter(log));
    ua.setSourceFile(tarFile);
    ua.setDestDirectory(outputFolderFileTmp);
    ua.extract();

    FileUtils.deleteQuietly(tarFile);

    File fileToMove;

    File[] files = outputFolderFileTmp.listFiles();
    if (files != null && files.length == 1) {
        fileToMove = files[0];

    } else {
        File aPackage = new File(outputFolderFileTmp, "package");
        if (aPackage.exists() && aPackage.isDirectory()) {
            fileToMove = aPackage;
        } else {
            throw new MojoExecutionException(String.format(
                    "Only one file should be present at the folder when " + "unpacking module %s:%s: ", name,
                    version));
        }
    }

    try {
        FileUtils.moveDirectory(fileToMove, outputFolderFile);
    } catch (IOException e) {
        throw new MojoExecutionException(String.format(
                "Error moving to the final folder when " + "unpacking module %s:%s: ", name, version), e);
    }

    try {
        FileUtils.deleteDirectory(outputFolderFileTmp);
    } catch (IOException e) {
        log.info("Error while deleting temporary folder: " + outputFolderFileTmp, e);
    }

}

From source file:org.onebusaway.admin.bundle.DirectoryStagingBundleSource.java

@Override
public void stage(String env, String bundleDir, String bundleName) throws Exception {
    File srcDir = new File(this.getMasterBundleDirectory().toString() + File.separator + bundleDir
            + File.separator + "builds" + File.separator + bundleName);
    File srcFile = new File(srcDir, bundleName + ".tar.gz");
    File destDir = this.getStagedBundleDirectory();
    _log.info("deleting " + destDir);
    // cleanup from past run
    try {// www  .j  a va2 s  .com
        FileUtils.deleteDirectory(destDir);
    } catch (Exception any) {
        _log.info("deleteDir failed with :", any);
    }

    FileUtility fu = new FileUtility();
    _log.info("making directory" + destDir);
    destDir.mkdir();

    _log.info("expanding " + srcFile + " to " + destDir);
    fu.unTargz(srcFile, destDir);
    File oldDir = new File(destDir + File.separator + bundleName);
    File newDir = new File(destDir + File.separator + env);
    _log.info("moving " + oldDir + " to " + newDir);
    FileUtils.moveDirectory(oldDir, newDir);
}

From source file:org.openbravo.erpCommon.modules.ImportModule.java

/**
 * Finishes local installation moving temporary module directories to actual ones.
 *//* w w  w.  j av  a  2  s  .  c  om*/
private boolean finishLocalInstallation(Module m) throws IOException {
    if ("0".equals(m.getModuleID())) {
        // Core is a special case, it is installed directly in its directory
        return true;
    }

    File tmpInstall = new File(obDir + "/tmp/localInstall/modules");
    File f = new File(tmpInstall, m.getPackageName());
    if (!f.exists()) {
        addLog("@ErrorInstallingLocallyFileNotFound@ " + f, MSG_ERROR);
        FileUtils.deleteDirectory(tmpInstall);
        rollback();
        return false;
    } else {
        File dest = new File(obDir + "/modules/" + m.getPackageName());
        log4j.debug("Moving " + f + " to " + dest);
        FileUtils.moveDirectory(f, dest);
    }
    return true;
}

From source file:org.opendatakit.common.android.provider.impl.FormsDiscoveryRunnable.java

/**
 * Construct a directory name that is unused in the stale path and move
 * mediaPath there.//from  w  w  w  . jav a 2 s .  c om
 *
 * @param mediaPath
 * @param baseStaleMediaPath
 *          -- the stale directory corresponding to the mediaPath container
 * @return the directory within the stale directory that the mediaPath was
 *         renamed to.
 * @throws IOException
 */
private final File moveToStaleDirectory(File mediaPath, String baseStaleMediaPath) throws IOException {
    // we have a 'framework' form in the forms directory.
    // Move it to the stale directory.
    // Delete all records referring to this directory.
    int i = 0;
    File tempMediaPath = new File(baseStaleMediaPath + mediaPath.getName() + "_" + Integer.toString(i));
    while (tempMediaPath.exists()) {
        ++i;
        tempMediaPath = new File(baseStaleMediaPath + mediaPath.getName() + "_" + Integer.toString(i));
    }
    FileUtils.moveDirectory(mediaPath, tempMediaPath);
    return tempMediaPath;
}

From source file:org.opendatakit.common.android.provider.impl.FormsDiscoveryRunnable.java

/**
 * Scan the given formDir and update the Forms database. If it is the
 * formsFolder, then any 'framework' forms should be forbidden. If it is not
 * the// w  w w .  ja  va2 s  .co m
 * formsFolder, only 'framework' forms should be allowed
 *
 * @param mediaPath
 *          -- full formDir
 * @param isFormsFolder
 * @param baseStaleMediaPath
 *          -- path prefix to the stale forms/framework directory.
 */
private final void updateFormDir(File formDir, boolean isFormsFolder, String baseStaleMediaPath) {

    String formDirectoryPath = formDir.getAbsolutePath();
    Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath);

    boolean needUpdate = true;
    FormInfo fi = null;
    Uri uri = null;
    Cursor c = null;
    try {
        File formDef = new File(formDir, ODKFileUtils.FORMDEF_JSON_FILENAME);

        String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?";
        String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, formDir) };
        c = context.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null,
                selection, selectionArgs, null);

        if (c == null) {
            Log.w(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath
                    + " null cursor -- cannot update!");
            return;
        }

        if (c.getCount() > 1) {
            c.close();
            Log.w(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath
                    + " multiple records from cursor -- delete all and restore!");
            // we have multiple records for this one directory.
            // Rename the directory. Delete the records, and move the
            // directory back.
            File tempMediaPath = moveToStaleDirectory(formDir, baseStaleMediaPath);
            context.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                    selection, selectionArgs);
            FileUtils.moveDirectory(tempMediaPath, formDir);
            // we don't know which of the above records was correct, so
            // reparse this to get ground truth...
            fi = new FormInfo(context, appName, formDef);
        } else if (c.getCount() == 1) {
            c.moveToFirst();
            String id = c.getString(c.getColumnIndex(FormsColumns.FORM_ID));
            uri = Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), id);
            Long lastModificationDate = c.getLong(c.getColumnIndex(FormsColumns.DATE));
            Long formDefModified = ODKFileUtils.getMostRecentlyModifiedDate(formDir);
            if (lastModificationDate.compareTo(formDefModified) == 0) {
                Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath
                        + " formDef unchanged");
                fi = new FormInfo(appName, c, false);
                needUpdate = false;
            } else {
                Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " formDef revised");
                fi = new FormInfo(context, appName, formDef);
                needUpdate = true;
            }
        } else if (c.getCount() == 0) {
            // it should be new, try to parse it...
            fi = new FormInfo(context, appName, formDef);
        }

        // Enforce that a formId == FormsColumns.COMMON_BASE_FORM_ID can only be
        // in the Framework directory
        // and that no other formIds can be in that directory. If this is not the
        // case, ensure that
        // this record is moved to the stale directory.

        if (fi.formId.equals(FormsColumns.COMMON_BASE_FORM_ID)) {
            if (isFormsFolder) {
                // we have a 'framework' form in the forms directory.
                // Move it to the stale directory.
                // Delete all records referring to this directory.
                moveToStaleDirectory(formDir, baseStaleMediaPath);
                context.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                        selection, selectionArgs);
                return;
            }
        } else {
            if (!isFormsFolder) {
                // we have a non-'framework' form in the framework directory.
                // Move it to the stale directory.
                // Delete all records referring to this directory.
                moveToStaleDirectory(formDir, baseStaleMediaPath);
                context.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                        selection, selectionArgs);
                return;
            }
        }
    } catch (SQLiteException e) {
        e.printStackTrace();
        Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: "
                + e.toString());
        return;
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: "
                + e.toString());
        return;
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
        Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: "
                + e.toString());
        try {
            FileUtils.deleteDirectory(formDir);
            Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath
                    + " Removing -- unable to parse formDef file: " + e.toString());
        } catch (IOException e1) {
            e1.printStackTrace();
            Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath
                    + " Removing -- unable to delete form directory: " + formDir.getName() + " error: "
                    + e.toString());
        }
        return;
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    // Delete any entries matching this FORM_ID, but not the same directory and
    // which have a version that is equal to or older than this version.
    String selection;
    String[] selectionArgs;
    if (fi.formVersion == null) {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + FormsColumns.FORM_VERSION + " IS NULL";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId };
        selectionArgs = temp;
    } else {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + "( " + FormsColumns.FORM_VERSION + " IS NULL" + " OR " + FormsColumns.FORM_VERSION + " <=?"
                + " )";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId, fi.formVersion };
        selectionArgs = temp;
    }

    try {
        context.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName), selection,
                selectionArgs);
    } catch (SQLiteException e) {
        e.printStackTrace();
        Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: "
                + e.toString());
        return;
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: "
                + e.toString());
        return;
    }

    // See if we have any newer versions already present...
    if (fi.formVersion == null) {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + FormsColumns.FORM_VERSION + " IS NOT NULL";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId };
        selectionArgs = temp;
    } else {
        selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "!=? AND " + FormsColumns.FORM_ID + "=? AND "
                + FormsColumns.FORM_VERSION + " >?";
        String[] temp = { ODKFileUtils.asRelativePath(appName, formDir), fi.formId, fi.formVersion };
        selectionArgs = temp;
    }

    try {
        Uri uriApp = Uri.withAppendedPath(formsProviderContentUri, appName);
        c = context.getContentResolver().query(uriApp, null, selection, selectionArgs, null);

        if (c == null) {
            Log.w(t, "[" + instanceCounter + "] updateFormDir: " + uriApp.toString()
                    + " null cursor -- cannot update!");
            return;
        }

        if (c.moveToFirst()) {
            // the directory we are processing is stale -- move it to stale
            // directory
            moveToStaleDirectory(formDir, baseStaleMediaPath);
            return;
        }
    } catch (SQLiteException e) {
        e.printStackTrace();
        Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: "
                + e.toString());
        return;
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: "
                + e.toString());
        return;
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    if (!needUpdate) {
        // no change...
        return;
    }

    try {
        // Now insert or update the record...
        ContentValues v = new ContentValues();
        String[] values = fi.asRowValues(FormsColumns.formsDataColumnNames);
        for (int i = 0; i < values.length; ++i) {
            v.put(FormsColumns.formsDataColumnNames[i], values[i]);
        }

        if (uri != null) {
            int count = context.getContentResolver().update(uri, v, null, null);
            Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " " + count
                    + " records successfully updated");
        } else {
            context.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), v);
            Log.i(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath
                    + " one record successfully inserted");
        }

    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.e(t, "[" + instanceCounter + "] updateFormDir: " + formDirectoryPath + " exception: "
                + ex.toString());
        return;
    }
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

private void moveDirectory(String appName, DirType mediaType, File mediaDirectory) throws IOException {
    WebLogger log = WebLogger.getLogger(appName);

    if (mediaDirectory.exists() && mediaType != DirType.OTHER) {
        // it is a directory under our control
        // -- move it to the stale forms or framework path...
        // otherwise, it is not where we will look for it,
        // so we can ignore it (once the record is gone
        // from our FormsProvider, we will not accidentally
        // detect it).
        String rootName = mediaDirectory.getName();
        int rev = 2;
        String staleMediaPathBase;
        if (mediaType == DirType.FORMS) {
            staleMediaPathBase = ODKFileUtils.getStaleFormsFolder(appName) + File.separator;
        } else {/*  w w  w . j av  a2  s .c o  m*/
            staleMediaPathBase = ODKFileUtils.getStaleFrameworkFolder(appName) + File.separator;
        }

        String staleMediaPathName = staleMediaPathBase + rootName;
        File staleMediaPath = new File(staleMediaPathName);

        while (staleMediaPath.exists()) {
            try {
                if (staleMediaPath.exists()) {
                    FileUtils.deleteDirectory(staleMediaPath);
                    if (!staleMediaPath.exists()) {
                        // we successfully deleted an older directory -- reuse it...
                        break;
                    }
                }
                log.i(t, "Successful delete of stale directory: " + staleMediaPathName);
            } catch (IOException ex) {
                ex.printStackTrace();
                log.i(t, "Unable to delete stale directory: " + staleMediaPathName);
            }
            staleMediaPathName = staleMediaPathBase + rootName + "_" + rev;
            staleMediaPath = new File(staleMediaPathName);
            rev++;
        }
        FileUtils.moveDirectory(mediaDirectory, staleMediaPath);
    }
}

From source file:org.opendatakit.common.android.task.InitializationTask.java

/**
 * Scan the given formDir and update the Forms database. If it is the
 * formsFolder, then any 'framework' forms should be forbidden. If it is not
 * the formsFolder, only 'framework' forms should be allowed
 *
 * @param tableId/*from   w  ww. j  ava 2  s.  c  o m*/
 * @param formId
 * @param formDir
 * @param isFormsFolder
 * @param baseStaleMediaPath -- path prefix to the stale forms/framework directory.
 */
private final void updateFormDir(String tableId, String formId, File formDir, boolean isFormsFolder,
        String baseStaleMediaPath) {
    Uri formsProviderContentUri = Uri.parse("content://" + FormsProviderAPI.AUTHORITY);
    String formDirectoryPath = formDir.getAbsolutePath();
    WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath);

    String successMessage = appContext.getString(R.string.form_register_success, tableId, formId);
    String failureMessage = appContext.getString(R.string.form_register_failure, tableId, formId);

    Cursor c = null;
    try {
        String selection = FormsColumns.TABLE_ID + "=? AND " + FormsColumns.FORM_ID + "=?";
        String[] selectionArgs = { tableId, formId };
        c = appContext.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null,
                selection, selectionArgs, null);

        if (c == null) {
            WebLogger.getLogger(appName).w(t,
                    "updateFormDir: " + formDirectoryPath + " null cursor -- cannot update!");
            mPendingResult.add(failureMessage);
            return;
        }

        if (c.getCount() > 1) {
            c.close();
            WebLogger.getLogger(appName).w(t, "updateFormDir: " + formDirectoryPath
                    + " multiple records from cursor -- delete all and restore!");
            // we have multiple records for this one directory.
            // Rename the directory. Delete the records, and move the
            // directory back.
            File tempMediaPath = moveToStaleDirectory(formDir, baseStaleMediaPath);

            appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                    selection, selectionArgs);

            FileUtils.moveDirectory(tempMediaPath, formDir);

            ContentValues cv = new ContentValues();
            cv.put(FormsColumns.TABLE_ID, tableId);
            cv.put(FormsColumns.FORM_ID, formId);
            appContext.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), cv);
        } else if (c.getCount() == 1) {
            c.close();
            ContentValues cv = new ContentValues();
            cv.put(FormsColumns.TABLE_ID, tableId);
            cv.put(FormsColumns.FORM_ID, formId);
            appContext.getContentResolver().update(Uri.withAppendedPath(formsProviderContentUri, appName), cv,
                    null, null);
        } else if (c.getCount() == 0) {
            c.close();
            ContentValues cv = new ContentValues();
            cv.put(FormsColumns.TABLE_ID, tableId);
            cv.put(FormsColumns.FORM_ID, formId);
            appContext.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), cv);
        }
    } catch (IOException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        mPendingResult.add(failureMessage);
        return;
    } catch (IllegalArgumentException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        try {
            FileUtils.deleteDirectory(formDir);
            WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath
                    + " Removing -- unable to parse formDef file: " + e.toString());
        } catch (IOException e1) {
            WebLogger.getLogger(appName).printStackTrace(e1);
            WebLogger.getLogger(appName)
                    .i(t, "updateFormDir: " + formDirectoryPath
                            + " Removing -- unable to delete form directory: " + formDir.getName() + " error: "
                            + e.toString());
        }
        mPendingResult.add(failureMessage);
        return;
    } catch (Exception e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        mPendingResult.add(failureMessage);
        return;
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
    mPendingResult.add(successMessage);
}