mobile/android/base/db/PerProfileDatabases.java

changeset 0
6474c204b198
equal deleted inserted replaced
-1:000000000000 0:aa4087373996
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/. */
4
5 package org.mozilla.gecko.db;
6
7 import java.io.File;
8 import java.util.HashMap;
9
10 import org.mozilla.gecko.GeckoProfile;
11
12 import android.content.Context;
13 import android.database.sqlite.SQLiteOpenHelper;
14 import android.text.TextUtils;
15
16 /**
17 * Manages a set of per-profile database storage helpers.
18 */
19 public class PerProfileDatabases<T extends SQLiteOpenHelper> {
20
21 private final HashMap<String, T> mStorages = new HashMap<String, T>();
22
23 private final Context mContext;
24 private final String mDatabaseName;
25 private final DatabaseHelperFactory<T> mHelperFactory;
26
27 public interface DatabaseHelperFactory<T> {
28 public T makeDatabaseHelper(Context context, String databasePath);
29 }
30
31 public PerProfileDatabases(final Context context, final String databaseName, final DatabaseHelperFactory<T> helperFactory) {
32 mContext = context;
33 mDatabaseName = databaseName;
34 mHelperFactory = helperFactory;
35 }
36
37 public String getDatabasePathForProfile(String profile) {
38 final File profileDir = GeckoProfile.get(mContext, profile).getDir();
39 if (profileDir == null) {
40 return null;
41 }
42
43 return new File(profileDir, mDatabaseName).getAbsolutePath();
44 }
45
46 public T getDatabaseHelperForProfile(String profile) {
47 return getDatabaseHelperForProfile(profile, false);
48 }
49
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 }
55
56 synchronized (this) {
57 if (mStorages.containsKey(profile)) {
58 return mStorages.get(profile);
59 }
60
61 final String databasePath = isTest ? mDatabaseName : getDatabasePathForProfile(profile);
62 if (databasePath == null) {
63 throw new IllegalStateException("Database path is null for profile: " + profile);
64 }
65
66 final T helper = mHelperFactory.makeDatabaseHelper(mContext, databasePath);
67 DBUtils.ensureDatabaseIsNotLocked(helper, databasePath);
68
69 mStorages.put(profile, helper);
70 return helper;
71 }
72 }
73 }

mercurial