Thu, 22 Jan 2015 13:21:57 +0100
Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 package org.mozilla.gecko.db;
7 import java.io.File;
8 import java.util.HashMap;
10 import org.mozilla.gecko.GeckoProfile;
12 import android.content.Context;
13 import android.database.sqlite.SQLiteOpenHelper;
14 import android.text.TextUtils;
16 /**
17 * Manages a set of per-profile database storage helpers.
18 */
19 public class PerProfileDatabases<T extends SQLiteOpenHelper> {
21 private final HashMap<String, T> mStorages = new HashMap<String, T>();
23 private final Context mContext;
24 private final String mDatabaseName;
25 private final DatabaseHelperFactory<T> mHelperFactory;
27 public interface DatabaseHelperFactory<T> {
28 public T makeDatabaseHelper(Context context, String databasePath);
29 }
31 public PerProfileDatabases(final Context context, final String databaseName, final DatabaseHelperFactory<T> helperFactory) {
32 mContext = context;
33 mDatabaseName = databaseName;
34 mHelperFactory = helperFactory;
35 }
37 public String getDatabasePathForProfile(String profile) {
38 final File profileDir = GeckoProfile.get(mContext, profile).getDir();
39 if (profileDir == null) {
40 return null;
41 }
43 return new File(profileDir, mDatabaseName).getAbsolutePath();
44 }
46 public T getDatabaseHelperForProfile(String profile) {
47 return getDatabaseHelperForProfile(profile, false);
48 }
50 public T getDatabaseHelperForProfile(String profile, boolean isTest) {
51 // Always fall back to default profile if none has been provided.
52 if (TextUtils.isEmpty(profile)) {
53 profile = GeckoProfile.get(mContext).getName();
54 }
56 synchronized (this) {
57 if (mStorages.containsKey(profile)) {
58 return mStorages.get(profile);
59 }
61 final String databasePath = isTest ? mDatabaseName : getDatabasePathForProfile(profile);
62 if (databasePath == null) {
63 throw new IllegalStateException("Database path is null for profile: " + profile);
64 }
66 final T helper = mHelperFactory.makeDatabaseHelper(mContext, databasePath);
67 DBUtils.ensureDatabaseIsNotLocked(helper, databasePath);
69 mStorages.put(profile, helper);
70 return helper;
71 }
72 }
73 }