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.opendatakit.services.forms.provider.FormsProvider.java

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}// w w w.j  ava  2s  .c  om
 */
@Override
public synchronized int delete(@NonNull Uri uri, String where, String[] whereArgs) {
    possiblyWaitForContentProviderDebugger();

    List<String> segments = uri.getPathSegments();

    PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs);
    WebLoggerIf logger = WebLogger.getLogger(pf.appName);

    String[] projection = { FormsColumns._ID, FormsColumns.TABLE_ID, FormsColumns.FORM_ID };

    HashMap<String, FormSpec> directories = new HashMap<String, FormSpec>();

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    Cursor c = null;

    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    try {
        // Get the database and run the query
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName,
                dbHandleName);
        db.beginTransactionNonExclusive();
        c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, pf.whereId, pf.whereIdArgs, null, null,
                null, null);

        if (c == null) {
            throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records");
        }

        int idxId = c.getColumnIndex(FormsColumns._ID);
        int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID);
        int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID);

        if (c.moveToFirst()) {
            do {
                idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId);
                tableIdValue = CursorUtils.getIndexAsString(c, idxTableId);
                formIdValue = CursorUtils.getIndexAsString(c, idxFormId);
                FormSpec formSpec = new FormSpec();
                formSpec.tableId = tableIdValue;
                formSpec.formId = formIdValue;
                formSpec.success = false;
                directories.put(idValue.toString(), formSpec);
            } while (c.moveToNext());
        }
        c.close();
        c = null;

        // and now go through this list moving the directories 
        // into the pending-deletion location and deleting them.
        for (Entry<String, FormSpec> de : directories.entrySet()) {
            String id = de.getKey();
            FormSpec fs = de.getValue();

            File srcDir = new File(ODKFileUtils.getFormFolder(pf.appName, fs.tableId, fs.formId));
            File destDir = new File(ODKFileUtils.getPendingDeletionTablesFolder(pf.appName),
                    fs.tableId + "." + fs.formId + "." + System.currentTimeMillis());

            try {
                FileUtils.moveDirectory(srcDir, destDir);
                if (db.delete(DatabaseConstants.FORMS_TABLE_NAME, FormsColumns._ID + "=?",
                        new String[] { id }) > 0) {
                    fs.success = true;
                }
            } catch (IOException e) {
                logger.e(t, "Unable to move directory prior to deleting it: " + e.toString());
                logger.printStackTrace(e);
            }
        }

        // commit the transaction...
        db.setTransactionSuccessful();

    } catch (Exception e) {
        logger.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (db != null) {
            try {
                try {
                    if (c != null && !c.isClosed()) {
                        c.close();
                    }
                } finally {
                    if (db.inTransaction()) {
                        db.endTransaction();
                    }
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
                            .removeConnection(pf.appName, dbHandleName);
                }
            }
        }
    }

    // and now, go through all the files in the pending-deletion 
    // directory and try to release them.

    File destFolder = new File(ODKFileUtils.getPendingDeletionTablesFolder(pf.appName));

    File[] delDirs = destFolder.listFiles();
    for (File formIdDir : delDirs) {
        try {
            FileUtils.deleteDirectory(formIdDir);
        } catch (IOException e) {
            logger.e(t, "Unable to remove directory " + e.toString());
            logger.printStackTrace(e);
        }
    }

    int failureCount = 0;
    for (Entry<String, FormSpec> e : directories.entrySet()) {
        String id = e.getKey();
        FormSpec fs = e.getValue();
        if (fs.success) {
            Uri formUri = Uri
                    .withAppendedPath(
                            Uri.withAppendedPath(Uri.withAppendedPath(
                                    Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId),
                            fs.formId);
            getContext().getContentResolver().notifyChange(formUri, null);
            Uri idUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), id);
            getContext().getContentResolver().notifyChange(idUri, null);
        } else {
            ++failureCount;
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);

    int count = directories.size();
    if (failureCount != 0) {
        throw new SQLiteException(
                "Unable to delete all forms (" + (count - failureCount) + " of " + count + " deleted)");
    }
    return count;
}

From source file:org.opendatakit.survey.android.tasks.DownloadFormsTask.java

@Override
protected HashMap<String, String> doInBackground(FormDetails... values) {

    String auth = PropertiesSingleton.getProperty(appName, PreferencesActivity.KEY_AUTH);
    setAuth(auth);/* w  w  w  .  j  av a 2 s  .  c om*/

    int total = values.length;
    int count = 1;

    HashMap<String, String> result = new HashMap<String, String>();

    try {
        for (int i = 0; i < total; i++) {
            FormDetails fd = values[i];

            if (isCancelled()) {
                result.put(fd.formID, "cancelled");
                return result;
            }

            publishProgress(fd.formID, Integer.valueOf(count).toString(), Integer.valueOf(total).toString());

            String message = "";
            /*
             * Downloaded forms are placed in a staging directory
             * (STALE_FORMS_PATH). Once they are deemed complete, they are
             * atomically moved into the FORMS_PATH. For atomicity, the Form
             * definition file will be stored WITHIN the media folder.
             */

            /* download to here... under STALE_FORMS_PATH */
            File tempFormPath = null;
            /* download to here.. under STALE_FORMS_PATH */
            File tempMediaPath = null;
            /* existing with exactly the same formVersion is here... */
            File existingMediaPath = null;
            /* existing to be moved here... under STALE_FORMS_PATH */
            File staleMediaPath = null;
            /* after downloaded and unpacked, move it here... */
            // File formPath = null; // don't know tableId yet...
            /* after downloaded and unpacked, move it here... */
            // File mediaPath = null; // don't know tableId yet...
            try {
                /*
                 * path to the directory containing the newly downloaded or stale data
                 */
                String baseStaleMediaPath;
                boolean isFramework;
                if (fd.formID.equals(FormsColumns.COMMON_BASE_FORM_ID)) {
                    /*
                     * the Common Javascript Framework is stored in the Framework
                     * directories
                     */
                    baseStaleMediaPath = ODKFileUtils.getStaleFrameworkFolder(getAppName()) + File.separator;
                    isFramework = true;
                } else {
                    baseStaleMediaPath = ODKFileUtils.getStaleFormsFolder(getAppName()) + File.separator;
                    isFramework = false;
                }

                try {
                    // clean up friendly form name...
                    String rootName = fd.formID;
                    if (!rootName.matches("^\\p{L}\\p{M}*(\\p{L}\\p{M}*|\\p{Nd}|_)*$")) {
                        // error!
                        message += appContext.getString(R.string.invalid_form_id, fd.formID, fd.formName);
                        WebLogger.getLogger(appName).e(t,
                                "Invalid form_id: " + fd.formID + " for: " + fd.formName);
                    } else {

                        // figure out what to name this when we move it
                        // out of /odk/appname/tables/tableId/forms/formId...
                        int rev = 2;
                        {
                            // proposed name of form 'media' directory and form
                            // file...
                            String tempMediaPathName = baseStaleMediaPath + rootName;

                            tempMediaPath = new File(tempMediaPathName);
                            tempFormPath = new File(tempMediaPath, ODKFileUtils.FILENAME_XFORMS_XML);

                            while (tempMediaPath.exists()) {
                                try {
                                    if (tempMediaPath.exists()) {
                                        FileUtils.deleteDirectory(tempMediaPath);
                                    }
                                    WebLogger.getLogger(appName).i(t,
                                            "Successful delete of stale directory: " + tempMediaPathName);
                                } catch (IOException ex) {
                                    WebLogger.getLogger(appName).printStackTrace(ex);
                                    WebLogger.getLogger(appName).i(t,
                                            "Unable to delete stale directory: " + tempMediaPathName);
                                }
                                tempMediaPathName = baseStaleMediaPath + rootName + "_" + rev;
                                tempMediaPath = new File(tempMediaPathName);
                                tempFormPath = new File(tempMediaPath, ODKFileUtils.FILENAME_XFORMS_XML);
                                rev++;
                            }
                        }

                        // and find a name that any existing directory could be
                        // renamed to... (continuing rev counter)
                        String staleMediaPathName = baseStaleMediaPath + rootName + "_" + rev;
                        staleMediaPath = new File(staleMediaPathName);

                        while (staleMediaPath.exists()) {
                            try {
                                if (staleMediaPath.exists()) {
                                    FileUtils.deleteDirectory(staleMediaPath);
                                }
                                WebLogger.getLogger(appName).i(t,
                                        "Successful delete of stale directory: " + staleMediaPathName);
                            } catch (IOException ex) {
                                WebLogger.getLogger(appName).printStackTrace(ex);
                                WebLogger.getLogger(appName).i(t,
                                        "Unable to delete stale directory: " + staleMediaPathName);
                            }
                            staleMediaPathName = baseStaleMediaPath + rootName + "_" + rev;
                            staleMediaPath = new File(staleMediaPathName);
                            rev++;
                        }

                        // we have a candidate mediaPath and formPath.
                        // The existing tableId directory is where we
                        // will eventually be placing this data, with
                        // the tableId == the formId from the legacy
                        // pathway.
                        if (isFramework) {
                            existingMediaPath = new File(ODKFileUtils.getAssetsFolder(getAppName()));
                        } else {
                            existingMediaPath = new File(ODKFileUtils.getTablesFolder(getAppName(), fd.formID));
                        }
                        ODKFileUtils.createFolder(existingMediaPath.getAbsolutePath());

                        if (fd.manifestUrl == null) {
                            message += appContext.getString(R.string.no_manifest, fd.formID);
                            WebLogger.getLogger(appName).e(t, "No Manifest for: " + fd.formID);
                        } else {
                            // download the media files -- it is an error if there
                            // are none...
                            String error = downloadManifestAndMediaFiles(tempMediaPath, existingMediaPath, fd,
                                    count, total);
                            if (error != null) {
                                message += error;
                            } else {
                                error = explodeZips(fd, tempMediaPath, count, total);
                                if (error != null) {
                                    message += error;
                                } else if (tempFormPath.exists()) {
                                    message += appContext.getString(R.string.xforms_file_exists,
                                            ODKFileUtils.FILENAME_XFORMS_XML, fd.formID);
                                    WebLogger.getLogger(appName).e(t, ODKFileUtils.FILENAME_XFORMS_XML
                                            + " was present in exploded download of " + fd.formID);
                                } else {
                                    // OK so far -- download the form definition
                                    // file
                                    // note that this is the reverse order from ODK1
                                    downloadXform(fd, tempFormPath,
                                            new File(existingMediaPath, ODKFileUtils.FILENAME_XFORMS_XML));
                                }
                            }
                        }
                    }
                } catch (SocketTimeoutException se) {
                    WebLogger.getLogger(appName).printStackTrace(se);
                    message += se.getMessage();
                } catch (Exception e) {
                    WebLogger.getLogger(appName).printStackTrace(e);
                    if (e.getCause() != null) {
                        message += e.getCause().getMessage();
                    } else {
                        message += e.getMessage();
                    }
                }

                if (message.equals("")) {
                    // OK. Everything is downloaded, unzipped, and present in the
                    // tempMediaPath
                    // directory... assume everything is OK and just move it...

                    // TODO: with the restructuring of the directory structure, step (3)
                    // won't be necessary
                    // (0) ensure there is no instances folder coming from the server
                    // (affects recovery)
                    // (1) move the existingMediaPath to the staleMediaPath
                    // (2) move the tempMediaPath to the existingMediaPath
                    // (3) move the staleMediaPath/instances folder to the
                    // existingMediaPath/instances.
                    File existingInstances = new File(existingMediaPath, ODKFileUtils.INSTANCES_FOLDER_NAME);
                    File staleInstances = new File(staleMediaPath, ODKFileUtils.INSTANCES_FOLDER_NAME);
                    File tempInstances = new File(tempMediaPath, ODKFileUtils.INSTANCES_FOLDER_NAME);

                    try {
                        // (0) ensure there is no instances folder coming from the server
                        if (tempInstances.exists()) {
                            FileUtils.deleteDirectory(tempInstances);
                        }
                        // (1) move any current directory to the stale tree.
                        if (existingMediaPath.exists()) {
                            FileUtils.moveDirectory(existingMediaPath, staleMediaPath);
                        }
                        // (2) move the temp directory to the current location.
                        FileUtils.moveDirectory(tempMediaPath, existingMediaPath);
                        // (3) move any instances back to the current location.
                        if (staleInstances.exists()) {
                            FileUtils.moveDirectory(staleInstances, existingInstances);
                        }
                    } catch (IOException ex) {
                        WebLogger.getLogger(appName).printStackTrace(ex);
                        message += ex.toString();
                        if (staleMediaPath.exists()) {
                            // try to move this back, since we failed somehow...
                            try {
                                if (existingInstances.exists()) {
                                    FileUtils.moveDirectory(existingInstances, staleInstances);
                                }
                                if (existingMediaPath.exists()) {
                                    FileUtils.deleteDirectory(existingMediaPath);
                                }
                                FileUtils.moveDirectory(staleMediaPath, existingMediaPath);
                            } catch (IOException e) {
                                WebLogger.getLogger(appName).printStackTrace(e);
                            }
                        }
                    }
                }
            } finally {
                if (!message.equalsIgnoreCase("")) {
                    // failure...
                    // we should always delete the temp file / directory.
                    // it is always a new file / directory, so there is no harm
                    // doing this.
                    if (tempMediaPath.exists()) {
                        try {
                            FileUtils.deleteDirectory(tempMediaPath);
                        } catch (IOException e) {
                            WebLogger.getLogger(appName).printStackTrace(e);
                        }
                    }
                } else {
                    message = appContext.getString(R.string.success);
                }
            }
            count++;
            result.put(fd.formID, message);
        }
    } finally {
        Survey.getInstance().setRunInitializationTask(getAppName());
    }
    return result;
}

From source file:org.opendatakit.survey.android.tasks.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 mediaPath/* ww w .java 2  s  .  c o m*/
 *          -- full formDir
 * @param isFormsFolder
 * @param baseStaleMediaPath
 *          -- path prefix to the stale forms/framework directory.
 */
private final void updateFormDir(File formDir, boolean isFormsFolder, String baseStaleMediaPath) {
    Uri formsProviderContentUri = Uri.parse("content://" + FormsProviderAPI.AUTHORITY);
    String formDirectoryPath = formDir.getAbsolutePath();
    WebLogger.getLogger(appName).i(t, "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 = 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!");
            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);
            // we don't know which of the above records was correct, so
            // reparse this to get ground truth...
            fi = new FormInfo(appContext, appName, formDef);
        } else if (c.getCount() == 1) {
            c.moveToFirst();
            String id = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID));
            uri = Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), id);
            Long lastModificationDate = ODKDatabaseUtils.get().getIndexAsType(c, Long.class,
                    c.getColumnIndex(FormsColumns.DATE));
            Long formDefModified = ODKFileUtils.getMostRecentlyModifiedDate(formDir);
            if (lastModificationDate.compareTo(formDefModified) == 0) {
                WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath + " formDef unchanged");
                fi = new FormInfo(appName, c, false);
                needUpdate = false;
            } else {
                WebLogger.getLogger(appName).i(t, "updateFormDir: " + formDirectoryPath + " formDef revised");
                fi = new FormInfo(appContext, appName, formDef);
                needUpdate = true;
            }
        } else if (c.getCount() == 0) {
            // it should be new, try to parse it...
            fi = new FormInfo(appContext, 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);
                appContext.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);
                appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                        selection, selectionArgs);
                return;
            }
        }
    } catch (SQLiteException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (IOException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        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());
        }
        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 {
        appContext.getContentResolver().delete(Uri.withAppendedPath(formsProviderContentUri, appName),
                selection, selectionArgs);
    } catch (SQLiteException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (Exception e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "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 = appContext.getContentResolver().query(uriApp, null, selection, selectionArgs, null);

        if (c == null) {
            WebLogger.getLogger(appName).w(t,
                    "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) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + e.toString());
        return;
    } catch (IOException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t,
                "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 = appContext.getContentResolver().update(uri, v, null, null);
            WebLogger.getLogger(appName).i(t,
                    "updateFormDir: " + formDirectoryPath + " " + count + " records successfully updated");
        } else {
            appContext.getContentResolver().insert(Uri.withAppendedPath(formsProviderContentUri, appName), v);
            WebLogger.getLogger(appName).i(t,
                    "updateFormDir: " + formDirectoryPath + " one record successfully inserted");
        }

    } catch (SQLiteException ex) {
        WebLogger.getLogger(appName).printStackTrace(ex);
        WebLogger.getLogger(appName).e(t,
                "updateFormDir: " + formDirectoryPath + " exception: " + ex.toString());
        return;
    }
}

From source file:org.opendatakit.utilities.ODKFileUtils.java

public static void moveDirectory(File sourceFolder, File destinationFolder) throws IOException {
    ContextClassLoaderWrapper wrapper = new ContextClassLoaderWrapper();
    try {/*ww  w.j av a  2 s  . co m*/
        FileUtils.moveDirectory(sourceFolder, destinationFolder);
    } finally {
        wrapper.release();
    }
}

From source file:org.openmrs.module.owa.activator.OwaActivator.java

/**
 * @see ModuleActivator#contextRefreshed()
 *//*from w  w w .  j a  va 2 s . c  o  m*/
@Override
public void contextRefreshed() {
    /**
     * Used to move the files from omod webapp resources to owa folder when omod webapps contain
     * manifest.webapp
     */
    String owaAppFolderPath = Context.getAdministrationService()
            .getGlobalProperty(AppManager.KEY_APP_FOLDER_PATH);
    if (null == owaAppFolderPath) {
        owaAppFolderPath = OpenmrsUtil.getApplicationDataDirectory()
                + (OpenmrsUtil.getApplicationDataDirectory().endsWith(File.separator) ? "owa"
                        : File.separator + "owa");
        Context.getAdministrationService().setGlobalProperty(AppManager.KEY_APP_FOLDER_PATH, owaAppFolderPath);
    }
    String owaStarted = Context.getAdministrationService().getGlobalProperty("owa.started");
    String realPath = System.getProperty("user.dir");
    realPath = realPath.substring(0, realPath.length() - 3);
    StringBuffer tomcatPath = new StringBuffer(realPath);
    tomcatPath.append("webapps/openmrs");
    StringBuilder absPath = new StringBuilder(tomcatPath + "/WEB-INF");
    absPath.append("/view/module/");
    File dir = new File(absPath.toString().replace("/", File.separator));
    try {
        List<File> files = (List<File>) FileUtils.listFiles(dir, TrueFileFilter.INSTANCE,
                TrueFileFilter.INSTANCE);
        for (File file : files) {
            if (file.getCanonicalPath().contains("manifest.webapp") && owaStarted.equalsIgnoreCase("true")) {
                File source = file.getParentFile();
                File dest = new File(owaAppFolderPath + File.separator + source.getName());
                FileUtils.moveDirectory(source, dest);
                log.info("Moving file from: " + source + " to " + dest);
            }
        }
    } catch (IOException e) {
        log.error(e);
    }
    log.info("OWA Module refreshed");
}

From source file:org.opennms.upgrade.implementations.SnmpInterfaceRrdMigratorOnline.java

/**
 * Merge./*from   w  w  w .  ja v a 2s . c  om*/
 *
 * @param oldDir the old directory
 * @param newDir the new directory
 * @throws Exception the exception
 */
protected void merge(File oldDir, File newDir) throws Exception {
    log("Merging data from %s to %s\n", oldDir, newDir);
    if (newDir.exists()) {
        File[] rrdFiles = getFiles(oldDir, getRrdExtension());
        if (rrdFiles == null) {
            log("Warning: there are no %s files on %s\n", getRrdExtension(), oldDir);
        } else {
            for (File source : rrdFiles) {
                File dest = new File(newDir, source.getName());
                if (dest.exists()) {
                    if (isRrdToolEnabled()) {
                        mergeRrd(source, dest);
                    } else {
                        mergeJrb(source, dest);
                    }
                } else {
                    log("  Warning: %s doesn't exist\n", dest);
                }
            }
        }
        try {
            log("  removing old directory %s\n", oldDir.getName());
            FileUtils.deleteDirectory(oldDir);
        } catch (Exception e) {
            log("  Warning: can't delete old directory because %s", e.getMessage());
        }
    } else {
        try {
            log("  moving %s to %s\n", oldDir.getName(), newDir.getName());
            FileUtils.moveDirectory(oldDir, newDir);
        } catch (Exception e) {
            log("  Warning: can't rename directory because %s", e.getMessage());
        }
    }
}

From source file:org.pieShare.pieShareApp.service.configurationService.ApplicationConfigurationService.java

@Override
public void setDatabaseFolder(File folder) {
    File db = getDatabaseFolder();
    addProperty("databaseDir", folder.toPath().toString());
    IPieDatabaseManagerFactory fact = beanService.getBean(PieDatabaseManagerFactory.class);
    fact.closeDB();/*from   www  . j a v a  2 s .  c om*/
    try {
        for (File file : db.listFiles()) {
            if (file.isDirectory()) {
                FileUtils.moveDirectory(file, folder);
            } else {
                FileUtils.moveFileToDirectory(file, folder, false);
            }
        }
    } catch (IOException ex) {
        PieLogger.error(this.getClass(), "Error copy database to new location", ex);
    }

    fact.init();
}

From source file:org.pieshare.piespring.service.ApplicationConfigurationService.java

@Override
public void setDatabaseFolder(File folder) {
    File db = getDatabaseFolder();
    addProperty("databaseDir", folder.toPath().toString());
    //todo-sv: i thing this does not belong here!! if we move this then the class can go back to the pieShareApp package
    IPieDatabaseManagerFactory fact = beanService.getBean(DatabaseFactory.class);
    fact.closeDB();/*from  ww  w.j  a  v  a  2 s .  c o m*/
    try {
        for (File file : db.listFiles()) {
            if (file.isDirectory()) {
                FileUtils.moveDirectory(file, folder);
            } else {
                FileUtils.moveFileToDirectory(file, folder, false);
            }
        }
    } catch (IOException ex) {
        PieLogger.error(this.getClass(), "Error copy database to new location", ex);
    }

    fact.init();
}

From source file:org.pitest.PitMojoIT.java

@Test
public void shouldCorrectlyHandleOverrides() throws Exception {
    File testDir = prepareSiteTest("/pit-site-custom-config");
    File targetDir = buildFilePath(testDir, "target");
    File expectedSiteReportDir = buildFilePath(testDir, "target", "site", "foobar");

    FileUtils.moveDirectory(buildFilePath(targetDir, "pit-reports"),
            buildFilePath(targetDir, "new-report-location"));

    verifier.executeGoal("site");

    String projectReportsHtmlContents = FileUtils
            .readFileToString(buildFilePath(testDir, "target", "site", "project-reports.html"));
    assertTrue("did not find expected anchor tag to pit site report", projectReportsHtmlContents.contains(
            "<a href=\"foobar/index.html\" title=\"my-test-pit-report-name\">my-test-pit-report-name</a>"));
    assertTrue("expected site report directory [" + expectedSiteReportDir + "] does not exist but should exist",
            expectedSiteReportDir.exists());

    assertFalse(/*from   w  w  w. j  ava2  s . c om*/
            "expected default site report directory exists but should not exist since the report location parameter was overridden",
            buildFilePath(testDir, "target", "site", "pit-reports").exists());
}

From source file:org.polymap.service.fs.providers.fs.FsContentProvider.java

public void moveTo(IContentNode src, IPath dest, String newName) throws BadRequestException, IOException {
    FsFolder destFolder = (FsFolder) getSite().getFolder(dest);
    File destFile = new File(destFolder.getDir(), newName);

    // file//ww  w. j  a  v a2  s  . c  o  m
    if (src instanceof FsFile) {
        FsFile srcFile = (FsFile) src;
        FileUtils.moveFile(srcFile.getFile(), destFile);
        getSite().invalidateFolder(getSite().getFolder(srcFile.getParentPath()));
    }
    // directory
    else if (src instanceof FsFolder) {
        FsFolder srcFolder = (FsFolder) src;
        FileUtils.moveDirectory(srcFolder.getDir(), destFile);
        getSite().invalidateFolder(getSite().getFolder(srcFolder.getParentPath()));
    } else {
        throw new BadRequestException("Destination is not a valid folder to move to.");
    }

    getSite().invalidateFolder(destFolder);
}