Search in sources :

Example 1 with Cursor

use of net.sqlcipher.Cursor in project android-database-sqlcipher by sqlcipher.

the class SQLiteDatabase method getAttachedDbs.

/**
     * returns list of full pathnames of all attached databases
     * including the main database
     * TODO: move this to {@link DatabaseUtils}
     */
private static ArrayList<Pair<String, String>> getAttachedDbs(SQLiteDatabase dbObj) {
    if (!dbObj.isOpen()) {
        return null;
    }
    ArrayList<Pair<String, String>> attachedDbs = new ArrayList<Pair<String, String>>();
    Cursor c = dbObj.rawQuery("pragma database_list;", null);
    while (c.moveToNext()) {
        attachedDbs.add(new Pair<String, String>(c.getString(1), c.getString(2)));
    }
    c.close();
    return attachedDbs;
}
Also used : ArrayList(java.util.ArrayList) Cursor(net.sqlcipher.Cursor) Pair(android.util.Pair)

Example 2 with Cursor

use of net.sqlcipher.Cursor in project android-database-sqlcipher by sqlcipher.

the class SQLiteDatabase method rawQuery.

/**
     * Runs the provided SQL and returns a {@link Cursor} over the result set.
     *
     * @param sql the SQL query. The SQL string must not be ; terminated
     * @param args You may include ?s in where clause in the query,
     *     which will be replaced by the values from args. The
     *     values will be bound by their type.
     *
     * @return A {@link Cursor} object, which is positioned before the first entry. Note that
     * {@link Cursor}s are not synchronized, see the documentation for more details.
     *
     * @throws SQLiteException if there is an issue executing the sql or the SQL string is invalid
     * @throws IllegalStateException if the database is not open
     */
public Cursor rawQuery(String sql, Object[] args) {
    if (!isOpen()) {
        throw new IllegalStateException("database not open");
    }
    long timeStart = 0;
    if (Config.LOGV || mSlowQueryThreshold != -1) {
        timeStart = System.currentTimeMillis();
    }
    SQLiteDirectCursorDriver driver = new SQLiteDirectCursorDriver(this, sql, null);
    Cursor cursor = null;
    try {
        cursor = driver.query(mFactory, args);
    } finally {
        if (Config.LOGV || mSlowQueryThreshold != -1) {
            // Force query execution
            int count = -1;
            if (cursor != null) {
                count = cursor.getCount();
            }
            long duration = System.currentTimeMillis() - timeStart;
            if (Config.LOGV || duration >= mSlowQueryThreshold) {
                Log.v(TAG, "query (" + duration + " ms): " + driver.toString() + ", args are <redacted>, count is " + count);
            }
        }
    }
    return new CrossProcessCursorWrapper(cursor);
}
Also used : CrossProcessCursorWrapper(net.sqlcipher.CrossProcessCursorWrapper) Cursor(net.sqlcipher.Cursor)

Example 3 with Cursor

use of net.sqlcipher.Cursor in project android-database-sqlcipher by sqlcipher.

the class SQLiteDatabase method rawQueryWithFactory.

/**
     * Runs the provided SQL and returns a cursor over the result set.
     *
     * @param cursorFactory the cursor factory to use, or null for the default factory
     * @param sql the SQL query. The SQL string must not be ; terminated
     * @param selectionArgs You may include ?s in where clause in the query,
     *     which will be replaced by the values from selectionArgs. The
     *     values will be bound as Strings.
     * @param editTable the name of the first table, which is editable
     *
     * @return A {@link Cursor} object, which is positioned before the first entry. Note that
     * {@link Cursor}s are not synchronized, see the documentation for more details.
     *
     * @throws SQLiteException if there is an issue executing the sql or the SQL string is invalid
     * @throws IllegalStateException if the database is not open
     */
public Cursor rawQueryWithFactory(CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable) {
    if (!isOpen()) {
        throw new IllegalStateException("database not open");
    }
    long timeStart = 0;
    if (Config.LOGV || mSlowQueryThreshold != -1) {
        timeStart = System.currentTimeMillis();
    }
    SQLiteCursorDriver driver = new SQLiteDirectCursorDriver(this, sql, editTable);
    Cursor cursor = null;
    try {
        cursor = driver.query(cursorFactory != null ? cursorFactory : mFactory, selectionArgs);
    } finally {
        if (Config.LOGV || mSlowQueryThreshold != -1) {
            // Force query execution
            int count = -1;
            if (cursor != null) {
                count = cursor.getCount();
            }
            long duration = System.currentTimeMillis() - timeStart;
            if (Config.LOGV || duration >= mSlowQueryThreshold) {
                Log.v(TAG, "query (" + duration + " ms): " + driver.toString() + ", args are <redacted>, count is " + count);
            }
        }
    }
    return new CrossProcessCursorWrapper(cursor);
}
Also used : CrossProcessCursorWrapper(net.sqlcipher.CrossProcessCursorWrapper) Cursor(net.sqlcipher.Cursor)

Example 4 with Cursor

use of net.sqlcipher.Cursor in project storymaker by StoryMaker.

the class BaseHomeActivity method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // copy index file
    // TODO: REPLACE THIS WITH INDEX DOWNLOAD (IF LOGGED IN) <- NEED TO COPY FILE FOR BASELINE CONTENT
    StorymakerIndexManager.copyAvailableIndex(this, false);
    // initialize db
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    // version check (sqlite upgrade requires migration)
    int appMigrationVersion = preferences.getInt("APP_MIGRATION_VERSION", 0);
    Timber.d("MIGRATION CHECK: " + appMigrationVersion + " vs. " + Constants.APP_MIGRATION_VERSION);
    if (appMigrationVersion != Constants.APP_MIGRATION_VERSION) {
        Timber.d("MIGRATION REQUIRED, RE-ENCRYPTING DATABASE");
        final boolean[] dbStatus = { false };
        try {
            SQLiteDatabaseHook dbHook = new SQLiteDatabaseHook() {

                public void preKey(SQLiteDatabase database) {
                }

                public void postKey(SQLiteDatabase database) {
                    Cursor cursor = database.rawQuery("PRAGMA cipher_migrate", new String[] {});
                    String value = "";
                    if (cursor != null) {
                        cursor.moveToFirst();
                        value = cursor.getString(0);
                        cursor.close();
                    }
                    // this result is currently ignored, checking if db is null instead
                    dbStatus[0] = Integer.valueOf(value) == 0;
                }
            };
            File dbPath = getDatabasePath("sm.db");
            Timber.d("MIGRATING DATABASE AT " + dbPath.getPath());
            SQLiteDatabase sqldb = SQLiteDatabase.openOrCreateDatabase(dbPath, "foo", null, dbHook);
            if (sqldb != null) {
                Timber.d("MIGRATED DATABASE NOT NULL");
                sqldb.close();
                // update preferences if migration succeeded
                preferences.edit().putInt("APP_MIGRATION_VERSION", Constants.APP_MIGRATION_VERSION).commit();
            } else {
                Timber.e("MIGRATED DATABASE IS NULL");
            }
        } catch (Exception ex) {
            Timber.e("EXCEPTION WHILE MIGRATING DATABASE: " + ex.getMessage());
        }
    }
    int availableIndexVersion = preferences.getInt("AVAILABLE_INDEX_VERSION", 0);
    Timber.d("VERSION CHECK: " + availableIndexVersion + " vs. " + scal.io.liger.Constants.AVAILABLE_INDEX_VERSION);
    if (availableIndexVersion != scal.io.liger.Constants.AVAILABLE_INDEX_VERSION) {
        // load db from file
        HashMap<String, scal.io.liger.model.ExpansionIndexItem> availableItemsFromFile = scal.io.liger.IndexManager.loadAvailableIdIndex(this);
        if (availableItemsFromFile.size() == 0) {
            Timber.d("NOTHING LOADED FROM AVAILABLE FILE");
        } else {
            for (scal.io.liger.model.ExpansionIndexItem item : availableItemsFromFile.values()) {
                Timber.d("ADDING " + item.getExpansionId() + " TO DATABASE (AVAILABLE)");
                // replaces existing items, should trigger updates to installed items and table as needed
                availableIndexItemDao.addAvailableIndexItem(item, true);
                // ugly solution to deal with the fact that the popup menu assumes there will be threads for an item we tried to download/install
                ArrayList<Thread> noThreads = new ArrayList<Thread>();
                downloadThreads.put(item.getExpansionId(), noThreads);
            }
        }
        // the following migration stuff is currently piggy-backing on the index update stuff
        // if found, migrate installed index
        File installedFile = new File(StorageHelper.getActualStorageDirectory(this), "installed_index.json");
        if (installedFile.exists()) {
            HashMap<String, scal.io.liger.model.ExpansionIndexItem> installedItemsFromFile = scal.io.liger.IndexManager.loadInstalledIdIndex(this);
            if (installedItemsFromFile.size() == 0) {
                Timber.d("NOTHING LOADED FROM INSTALLED INDEX FILE");
            } else {
                for (scal.io.liger.model.ExpansionIndexItem item : installedItemsFromFile.values()) {
                    Timber.d("ADDING " + item.getExpansionId() + " TO DATABASE (INSTALLED)");
                    // replaces existing items, should trigger updates to installed items and table as needed
                    installedIndexItemDao.addInstalledIndexItem(item, true);
                }
            }
            installedFile.delete();
        } else {
            Timber.d("NO INSTALLED INDEX FILE");
        }
        // if found, migrate instance index
        File instanceFile = new File(StorageHelper.getActualStorageDirectory(this), "instance_index.json");
        if (instanceFile.exists()) {
            HashMap<String, scal.io.liger.model.InstanceIndexItem> instanceItemsFromFile = scal.io.liger.IndexManager.loadInstanceIndex(this);
            if (instanceItemsFromFile.size() == 0) {
                Timber.d("NOTHING LOADED FROM INSTANCE INDEX FILE");
            } else {
                for (scal.io.liger.model.InstanceIndexItem item : instanceItemsFromFile.values()) {
                    Timber.d("ADDING " + item.getInstanceFilePath() + " TO DATABASE (INSTANCE)");
                    // replaces existing items, should trigger updates to installed items and table as needed
                    instanceIndexItemDao.addInstanceIndexItem(item, true);
                }
            }
            instanceFile.delete();
        } else {
            Timber.d("NO INSTANCE INDEX FILE");
        }
        // update preferences
        preferences.edit().putInt("AVAILABLE_INDEX_VERSION", scal.io.liger.Constants.AVAILABLE_INDEX_VERSION).commit();
        if (getIntent() != null && getIntent().hasExtra("showlauncher")) {
            if (getIntent().getBooleanExtra("showlauncher", false)) {
                showLauncherIcon();
            }
        }
    }
    // dumb test
    // check values
    availableIndexItemDao.getAvailableIndexItems().take(1).subscribe(new Action1<List<AvailableIndexItem>>() {

        @Override
        public void call(List<AvailableIndexItem> expansionIndexItems) {
            for (ExpansionIndexItem item : expansionIndexItems) {
                Timber.d("AVAILABLE ITEM " + item.getExpansionId() + ", TITLE: " + item.getTitle());
            }
        }
    });
    installedIndexItemDao.getInstalledIndexItems().take(1).subscribe(new Action1<List<InstalledIndexItem>>() {

        @Override
        public void call(List<InstalledIndexItem> expansionIndexItems) {
            for (ExpansionIndexItem item : expansionIndexItems) {
                Timber.d("INSTALLED ITEM " + item.getExpansionId() + ", TITLE: " + item.getTitle());
            }
        }
    });
    // file cleanup
    File actualStorageDirectory = StorageHelper.getActualStorageDirectory(this);
    if (actualStorageDirectory != null) {
        JsonHelper.cleanup(actualStorageDirectory.getPath());
    } else {
    // this is an error, will deal with it below
    }
    // default
    loggedIn = false;
    if (actualStorageDirectory != null) {
        // NEW/TEMP
        // DOWNLOAD AVAILABE INDEX FOR CURRENT USER AND SAVE TO TARGET FILE
        // NEED TO ACCOUNT FOR POSSIBLE MISSING INDEX
        // force download at startup (maybe only force on a timetable?)
        IndexTask iTask = new IndexTask(this, true);
        iTask.execute();
    } else {
        //show storage error message
        new AlertDialog.Builder(this).setTitle(Utils.getAppName(this)).setIcon(android.R.drawable.ic_dialog_info).setMessage(R.string.err_storage_not_available).show();
    }
    // we want to grab required updates without restarting the app
    // integrate with index task
    // if (!DownloadHelper.checkAndDownload(this)) {
    //     Toast.makeText(this, "Downloading content and/or updating installed files", Toast.LENGTH_LONG).show(); // FIXME move to strings.xml
    // }
    // i don't think we ever want to do this
    // IndexManager.copyInstalledIndex(this);
    //setContentView(R.layout.activity_home);
    //mRecyclerView = (RecyclerView) findViewById(scal.io.liger.R.id.recyclerView);
    //mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    //mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
    //mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
    //    @Override
    //    public void onRefresh() {
    //        IndexTask iTask = new IndexTask(HomeActivity.this, true); // force download on manual refresh
    //        iTask.execute();
    //    }
    //});
    //mTabMenu = getMenu("home");
    // action bar stuff
    getActionBar().setDisplayHomeAsUpEnabled(true);
    checkForTor();
    checkForUpdates();
}
Also used : ArrayList(java.util.ArrayList) ExpansionIndexItem(scal.io.liger.model.sqlbrite.ExpansionIndexItem) InstalledIndexItem(scal.io.liger.model.sqlbrite.InstalledIndexItem) Cursor(net.sqlcipher.Cursor) InstanceIndexItem(scal.io.liger.model.sqlbrite.InstanceIndexItem) AvailableIndexItem(scal.io.liger.model.sqlbrite.AvailableIndexItem) List(java.util.List) ArrayList(java.util.ArrayList) SharedPreferences(android.content.SharedPreferences) IOException(java.io.IOException) SQLiteDatabase(net.sqlcipher.database.SQLiteDatabase) File(java.io.File) SQLiteDatabaseHook(net.sqlcipher.database.SQLiteDatabaseHook)

Example 5 with Cursor

use of net.sqlcipher.Cursor in project android-database-sqlcipher by sqlcipher.

the class SQLiteDatabase method keyDatabase.

private void keyDatabase(SQLiteDatabaseHook databaseHook, Runnable keyOperation) {
    if (databaseHook != null) {
        databaseHook.preKey(this);
    }
    if (keyOperation != null) {
        keyOperation.run();
    }
    if (databaseHook != null) {
        databaseHook.postKey(this);
    }
    if (SQLiteDebug.DEBUG_SQL_CACHE) {
        mTimeOpened = getTime();
    }
    try {
        Cursor cursor = rawQuery("select count(*) from sqlite_master;", new String[] {});
        if (cursor != null) {
            cursor.moveToFirst();
            int count = cursor.getInt(0);
            cursor.close();
        }
    } catch (RuntimeException e) {
        Log.e(TAG, e.getMessage(), e);
        throw e;
    }
}
Also used : Cursor(net.sqlcipher.Cursor)

Aggregations

Cursor (net.sqlcipher.Cursor)5 ArrayList (java.util.ArrayList)2 CrossProcessCursorWrapper (net.sqlcipher.CrossProcessCursorWrapper)2 SharedPreferences (android.content.SharedPreferences)1 Pair (android.util.Pair)1 File (java.io.File)1 IOException (java.io.IOException)1 List (java.util.List)1 SQLiteDatabase (net.sqlcipher.database.SQLiteDatabase)1 SQLiteDatabaseHook (net.sqlcipher.database.SQLiteDatabaseHook)1 AvailableIndexItem (scal.io.liger.model.sqlbrite.AvailableIndexItem)1 ExpansionIndexItem (scal.io.liger.model.sqlbrite.ExpansionIndexItem)1 InstalledIndexItem (scal.io.liger.model.sqlbrite.InstalledIndexItem)1 InstanceIndexItem (scal.io.liger.model.sqlbrite.InstanceIndexItem)1