Search in sources :

Example 1 with SettingsImportExportException

use of com.fsck.k9.preferences.SettingsImportExportException in project k-9 by k9mail.

the class SettingsImporter method importSettings.

/**
     * Reads an import {@link InputStream} and imports the global settings and/or account
     * configurations specified by the arguments.
     *
     * @param context
     *         A {@link Context} instance.
     * @param inputStream
     *         The {@code InputStream} to read the settings from.
     * @param globalSettings
     *         {@code true} if global settings should be imported from the file.
     * @param accountUuids
     *         A list of UUIDs of the accounts that should be imported.
     * @param overwrite
     *         {@code true} if existing accounts should be overwritten when an account with the
     *         same UUID is found in the settings file.<br>
     *         <strong>Note:</strong> This can have side-effects we currently don't handle, e.g.
     *         changing the account type from IMAP to POP3. So don't use this for now!
     *
     * @return An {@link ImportResults} instance containing information about errors and
     *         successfully imported accounts.
     *
     * @throws SettingsImportExportException
     *         In case of an error.
     */
public static ImportResults importSettings(Context context, InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overwrite) throws SettingsImportExportException {
    try {
        boolean globalSettingsImported = false;
        List<AccountDescriptionPair> importedAccounts = new ArrayList<>();
        List<AccountDescription> erroneousAccounts = new ArrayList<>();
        Imported imported = parseSettings(inputStream, globalSettings, accountUuids, false);
        Preferences preferences = Preferences.getPreferences(context);
        Storage storage = preferences.getStorage();
        if (globalSettings) {
            try {
                StorageEditor editor = storage.edit();
                if (imported.globalSettings != null) {
                    importGlobalSettings(storage, editor, imported.contentVersion, imported.globalSettings);
                } else {
                    Timber.w("Was asked to import global settings but none found.");
                }
                if (editor.commit()) {
                    Timber.v("Committed global settings to the preference storage.");
                    globalSettingsImported = true;
                } else {
                    Timber.v("Failed to commit global settings to the preference storage");
                }
            } catch (Exception e) {
                Timber.e(e, "Exception while importing global settings");
            }
        }
        if (accountUuids != null && accountUuids.size() > 0) {
            if (imported.accounts != null) {
                for (String accountUuid : accountUuids) {
                    if (imported.accounts.containsKey(accountUuid)) {
                        ImportedAccount account = imported.accounts.get(accountUuid);
                        try {
                            StorageEditor editor = storage.edit();
                            AccountDescriptionPair importResult = importAccount(context, editor, imported.contentVersion, account, overwrite);
                            if (editor.commit()) {
                                Timber.v("Committed settings for account \"%s\" to the settings database.", importResult.imported.name);
                                // account UUIDs
                                if (!importResult.overwritten) {
                                    editor = storage.edit();
                                    String newUuid = importResult.imported.uuid;
                                    String oldAccountUuids = storage.getString("accountUuids", "");
                                    String newAccountUuids = (oldAccountUuids.length() > 0) ? oldAccountUuids + "," + newUuid : newUuid;
                                    putString(editor, "accountUuids", newAccountUuids);
                                    if (!editor.commit()) {
                                        throw new SettingsImportExportException("Failed to set account UUID list");
                                    }
                                }
                                // Reload accounts
                                preferences.loadAccounts();
                                importedAccounts.add(importResult);
                            } else {
                                Timber.w("Error while committing settings for account \"%s\" to the settings " + "database.", importResult.original.name);
                                erroneousAccounts.add(importResult.original);
                            }
                        } catch (InvalidSettingValueException e) {
                            Timber.e(e, "Encountered invalid setting while importing account \"%s\"", account.name);
                            erroneousAccounts.add(new AccountDescription(account.name, account.uuid));
                        } catch (Exception e) {
                            Timber.e(e, "Exception while importing account \"%s\"", account.name);
                            erroneousAccounts.add(new AccountDescription(account.name, account.uuid));
                        }
                    } else {
                        Timber.w("Was asked to import account with UUID %s. But this account wasn't found.", accountUuid);
                    }
                }
                StorageEditor editor = storage.edit();
                String defaultAccountUuid = storage.getString("defaultAccountUuid", null);
                if (defaultAccountUuid == null) {
                    putString(editor, "defaultAccountUuid", accountUuids.get(0));
                }
                if (!editor.commit()) {
                    throw new SettingsImportExportException("Failed to set default account");
                }
            } else {
                Timber.w("Was asked to import at least one account but none found.");
            }
        }
        preferences.loadAccounts();
        K9.loadPrefs(preferences);
        K9.setServicesEnabled(context);
        return new ImportResults(globalSettingsImported, importedAccounts, erroneousAccounts);
    } catch (SettingsImportExportException e) {
        throw e;
    } catch (Exception e) {
        throw new SettingsImportExportException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) IOException(java.io.IOException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) SharedPreferences(android.content.SharedPreferences) Preferences(com.fsck.k9.Preferences)

Example 2 with SettingsImportExportException

use of com.fsck.k9.preferences.SettingsImportExportException in project k-9 by k9mail.

the class SettingsImporter method parseSettings.

@VisibleForTesting
static Imported parseSettings(InputStream inputStream, boolean globalSettings, List<String> accountUuids, boolean overview) throws SettingsImportExportException {
    if (!overview && accountUuids == null) {
        throw new IllegalArgumentException("Argument 'accountUuids' must not be null.");
    }
    try {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        //factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser();
        InputStreamReader reader = new InputStreamReader(inputStream);
        xpp.setInput(reader);
        Imported imported = null;
        int eventType = xpp.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                if (SettingsExporter.ROOT_ELEMENT.equals(xpp.getName())) {
                    imported = parseRoot(xpp, globalSettings, accountUuids, overview);
                } else {
                    Timber.w("Unexpected start tag: %s", xpp.getName());
                }
            }
            eventType = xpp.next();
        }
        if (imported == null || (overview && imported.globalSettings == null && imported.accounts == null)) {
            throw new SettingsImportExportException("Invalid import data");
        }
        return imported;
    } catch (Exception e) {
        throw new SettingsImportExportException(e);
    }
}
Also used : XmlPullParserFactory(org.xmlpull.v1.XmlPullParserFactory) InputStreamReader(java.io.InputStreamReader) XmlPullParser(org.xmlpull.v1.XmlPullParser) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) IOException(java.io.IOException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) VisibleForTesting(android.support.annotation.VisibleForTesting)

Example 3 with SettingsImportExportException

use of com.fsck.k9.preferences.SettingsImportExportException in project k-9 by k9mail.

the class SettingsExporter method exportToFile.

public static String exportToFile(Context context, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException {
    OutputStream os = null;
    try {
        File dir = new File(Environment.getExternalStorageDirectory() + File.separator + context.getPackageName());
        if (!dir.mkdirs()) {
            Timber.d("Unable to create directory: %s", dir.getAbsolutePath());
        }
        File file = FileHelper.createUniqueFile(dir, EXPORT_FILENAME);
        String filename = file.getAbsolutePath();
        os = new FileOutputStream(filename);
        exportPreferences(context, os, includeGlobals, accountUuids);
        // If all went well, we return the name of the file just written.
        return filename;
    } catch (Exception e) {
        throw new SettingsImportExportException(e);
    } finally {
        closeOrThrow(os);
    }
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) IOException(java.io.IOException)

Example 4 with SettingsImportExportException

use of com.fsck.k9.preferences.SettingsImportExportException in project k-9 by k9mail.

the class SettingsExporter method exportPreferences.

static void exportPreferences(Context context, OutputStream os, boolean includeGlobals, Set<String> accountUuids) throws SettingsImportExportException {
    try {
        XmlSerializer serializer = Xml.newSerializer();
        serializer.setOutput(os, "UTF-8");
        serializer.startDocument(null, Boolean.TRUE);
        // Output with indentation
        serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
        serializer.startTag(null, ROOT_ELEMENT);
        serializer.attribute(null, VERSION_ATTRIBUTE, Integer.toString(Settings.VERSION));
        serializer.attribute(null, FILE_FORMAT_ATTRIBUTE, Integer.toString(FILE_FORMAT_VERSION));
        Timber.i("Exporting preferences");
        Preferences preferences = Preferences.getPreferences(context);
        Storage storage = preferences.getStorage();
        Set<String> exportAccounts;
        if (accountUuids == null) {
            List<Account> accounts = preferences.getAccounts();
            exportAccounts = new HashSet<>();
            for (Account account : accounts) {
                exportAccounts.add(account.getUuid());
            }
        } else {
            exportAccounts = accountUuids;
        }
        Map<String, Object> prefs = new TreeMap<String, Object>(storage.getAll());
        if (includeGlobals) {
            serializer.startTag(null, GLOBAL_ELEMENT);
            writeSettings(serializer, prefs);
            serializer.endTag(null, GLOBAL_ELEMENT);
        }
        serializer.startTag(null, ACCOUNTS_ELEMENT);
        for (String accountUuid : exportAccounts) {
            Account account = preferences.getAccount(accountUuid);
            writeAccount(serializer, account, prefs);
        }
        serializer.endTag(null, ACCOUNTS_ELEMENT);
        serializer.endTag(null, ROOT_ELEMENT);
        serializer.endDocument();
        serializer.flush();
    } catch (Exception e) {
        throw new SettingsImportExportException(e.getLocalizedMessage(), e);
    }
}
Also used : Account(com.fsck.k9.Account) TreeMap(java.util.TreeMap) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) IOException(java.io.IOException) Preferences(com.fsck.k9.Preferences) XmlSerializer(org.xmlpull.v1.XmlSerializer)

Example 5 with SettingsImportExportException

use of com.fsck.k9.preferences.SettingsImportExportException in project k-9 by k9mail.

the class SettingsExporter method exportToUri.

public static void exportToUri(Context context, boolean includeGlobals, Set<String> accountUuids, Uri uri) throws SettingsImportExportException {
    OutputStream os = null;
    try {
        os = context.getContentResolver().openOutputStream(uri);
        exportPreferences(context, os, includeGlobals, accountUuids);
    } catch (Exception e) {
        throw new SettingsImportExportException(e);
    } finally {
        closeOrThrow(os);
    }
}
Also used : OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) InvalidSettingValueException(com.fsck.k9.preferences.Settings.InvalidSettingValueException) IOException(java.io.IOException)

Aggregations

InvalidSettingValueException (com.fsck.k9.preferences.Settings.InvalidSettingValueException)5 IOException (java.io.IOException)5 Preferences (com.fsck.k9.Preferences)2 FileOutputStream (java.io.FileOutputStream)2 OutputStream (java.io.OutputStream)2 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)2 SharedPreferences (android.content.SharedPreferences)1 VisibleForTesting (android.support.annotation.VisibleForTesting)1 Account (com.fsck.k9.Account)1 File (java.io.File)1 InputStreamReader (java.io.InputStreamReader)1 ArrayList (java.util.ArrayList)1 TreeMap (java.util.TreeMap)1 XmlPullParser (org.xmlpull.v1.XmlPullParser)1 XmlPullParserFactory (org.xmlpull.v1.XmlPullParserFactory)1 XmlSerializer (org.xmlpull.v1.XmlSerializer)1