michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.db; michael@0: michael@0: import java.io.File; michael@0: import java.util.HashMap; michael@0: michael@0: import org.mozilla.gecko.GeckoProfile; michael@0: michael@0: import android.content.Context; michael@0: import android.database.sqlite.SQLiteOpenHelper; michael@0: import android.text.TextUtils; michael@0: michael@0: /** michael@0: * Manages a set of per-profile database storage helpers. michael@0: */ michael@0: public class PerProfileDatabases { michael@0: michael@0: private final HashMap mStorages = new HashMap(); michael@0: michael@0: private final Context mContext; michael@0: private final String mDatabaseName; michael@0: private final DatabaseHelperFactory mHelperFactory; michael@0: michael@0: public interface DatabaseHelperFactory { michael@0: public T makeDatabaseHelper(Context context, String databasePath); michael@0: } michael@0: michael@0: public PerProfileDatabases(final Context context, final String databaseName, final DatabaseHelperFactory helperFactory) { michael@0: mContext = context; michael@0: mDatabaseName = databaseName; michael@0: mHelperFactory = helperFactory; michael@0: } michael@0: michael@0: public String getDatabasePathForProfile(String profile) { michael@0: final File profileDir = GeckoProfile.get(mContext, profile).getDir(); michael@0: if (profileDir == null) { michael@0: return null; michael@0: } michael@0: michael@0: return new File(profileDir, mDatabaseName).getAbsolutePath(); michael@0: } michael@0: michael@0: public T getDatabaseHelperForProfile(String profile) { michael@0: return getDatabaseHelperForProfile(profile, false); michael@0: } michael@0: michael@0: public T getDatabaseHelperForProfile(String profile, boolean isTest) { michael@0: // Always fall back to default profile if none has been provided. michael@0: if (TextUtils.isEmpty(profile)) { michael@0: profile = GeckoProfile.get(mContext).getName(); michael@0: } michael@0: michael@0: synchronized (this) { michael@0: if (mStorages.containsKey(profile)) { michael@0: return mStorages.get(profile); michael@0: } michael@0: michael@0: final String databasePath = isTest ? mDatabaseName : getDatabasePathForProfile(profile); michael@0: if (databasePath == null) { michael@0: throw new IllegalStateException("Database path is null for profile: " + profile); michael@0: } michael@0: michael@0: final T helper = mHelperFactory.makeDatabaseHelper(mContext, databasePath); michael@0: DBUtils.ensureDatabaseIsNotLocked(helper, databasePath); michael@0: michael@0: mStorages.put(profile, helper); michael@0: return helper; michael@0: } michael@0: } michael@0: }