Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT] add option to use with sqlcipher library (encrypted database) #81

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ These are self-explanatory so here is an example:
"databaseVersion": 1,
"enableForeignKeys": true,
"useAnnotations": true,
"useEncryptedDatabase": false
}
```

Expand Down
48 changes: 48 additions & 0 deletions sqliteopenhelpercallbacks.ftl
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<#if header??>
${header}
</#if>
package ${config.providerJavaPackage};

import android.content.Context;
<#if config.useEncryptedDatabase>
import net.sqlcipher.database.SQLiteDatabase;
<#else>
import android.database.sqlite.SQLiteDatabase;
</#if>
import android.util.Log;

import ${config.projectPackageId}.BuildConfig;

/**
* Implement your custom database creation or upgrade code here.
*
* This file will not be overwritten if you re-run the content provider generator.
*/
public class ${config.sqliteOpenHelperCallbacksClassName} {
private static final String TAG = ${config.sqliteOpenHelperCallbacksClassName}.class.getSimpleName();

public void onOpen(final Context context, final SQLiteDatabase db) {
if (BuildConfig.DEBUG) Log.d(TAG, "onOpen");
// Insert your db open code here.
}

public void onPreCreate(final Context context, final SQLiteDatabase db) {
if (BuildConfig.DEBUG) Log.d(TAG, "onPreCreate");
// Insert your db creation code here. This is called before your tables are created.
}

public void onPostCreate(final Context context, final SQLiteDatabase db) {
if (BuildConfig.DEBUG) Log.d(TAG, "onPostCreate");
// Insert your db creation code here. This is called after your tables are created.
}

public void onUpgrade(final Context context, final SQLiteDatabase db, final int oldVersion, final int newVersion) {
if (BuildConfig.DEBUG) Log.d(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);
// Insert your upgrading code here.
<#if config.optString("sqliteUpgradeHelperClassName")?has_content>
new ${config.sqliteUpgradeHelperClassName}().onUpgrade(db, oldVersion, newVersion);
</#if>
}


}
2 changes: 1 addition & 1 deletion src/main/java/org/jraf/androidcontentprovidergenerator/Constants.java
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@
package org.jraf.androidcontentprovidergenerator;

public class Constants {
public static final int SYNTAX_VERSION = 3;
public static final int SYNTAX_VERSION = 4;
public static final String TAG = "";
}
39 changes: 37 additions & 2 deletions src/main/java/org/jraf/androidcontentprovidergenerator/Main.java
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,16 @@ public static class Json {
public static final String PROJECT_PACKAGE_ID = "projectPackageId";
public static final String PROVIDER_JAVA_PACKAGE = "providerJavaPackage";
public static final String PROVIDER_CLASS_NAME = "providerClassName";
public static final String PROVIDER_CALLBACKS_CLASS_NAME = "providerCallbacksClassName";

public static final String SQLITE_OPEN_HELPER_CLASS_NAME = "sqliteOpenHelperClassName";
public static final String SQLITE_OPEN_HELPER_CALLBACKS_CLASS_NAME = "sqliteOpenHelperCallbacksClassName";
public static final String AUTHORITY = "authority";
public static final String DATABASE_FILE_NAME = "databaseFileName";
public static final String DATABASE_VERSION = "databaseVersion";
public static final String ENABLE_FOREIGN_KEY = "enableForeignKeys";
public static final String USE_ANNOTATIONS = "useAnnotations";
public static final String USE_ENCRYPTED_DATABASE = "useEncryptedDatabase";
}

private Configuration mFreemarkerConfig;
Expand Down Expand Up @@ -264,13 +267,17 @@ private void validateConfig() {
ensureString(Json.PROJECT_PACKAGE_ID);
ensureString(Json.PROVIDER_JAVA_PACKAGE);
ensureString(Json.PROVIDER_CLASS_NAME);
if(ensureBoolean(Json.USE_ENCRYPTED_DATABASE)){
ensureString(Json.PROVIDER_CALLBACKS_CLASS_NAME);
}
ensureString(Json.SQLITE_OPEN_HELPER_CLASS_NAME);
ensureString(Json.SQLITE_OPEN_HELPER_CALLBACKS_CLASS_NAME);
ensureString(Json.AUTHORITY);
ensureString(Json.DATABASE_FILE_NAME);
ensureInt(Json.DATABASE_VERSION);
ensureBoolean(Json.ENABLE_FOREIGN_KEY);
ensureBoolean(Json.USE_ANNOTATIONS);

}

private void ensureString(String field) {
Expand All @@ -281,9 +288,9 @@ private void ensureString(String field) {
}
}

private void ensureBoolean(String field) {
private boolean ensureBoolean(String field) {
try {
mConfig.getBoolean(field);
return mConfig.getBoolean(field);
} catch (JSONException e) {
throw new IllegalArgumentException("Could not find '" + field + "' field in _config.json, which is mandatory and must be a boolean.");
}
Expand Down Expand Up @@ -455,6 +462,32 @@ private void generateContentProvider(Arguments arguments) throws IOException, JS
template.process(root, out);
}


private void generateContentProviderCallbacks(Arguments arguments) throws IOException, JSONException, TemplateException {
JSONObject config = getConfig(arguments.inputDir);
if(config.optBoolean(Json.USE_ENCRYPTED_DATABASE,false)){
Template template = getFreeMarkerConfig().getTemplate("contentprovidercallbacks.ftl");
String providerJavaPackage = config.getString(Json.PROVIDER_JAVA_PACKAGE);
File providerDir = new File(arguments.outputDir, providerJavaPackage.replace('.', '/'));
providerDir.mkdirs();
File outputFile = new File(providerDir, config.getString(Json.PROVIDER_CALLBACKS_CLASS_NAME) + ".java");
if (outputFile.exists()) {
if (Config.LOGD) Log.d(TAG, "generateContentProviderCallbacks content provider callbacks class already exists: skip");
return;
}
Writer out = new OutputStreamWriter(new FileOutputStream(outputFile));

Map<String, Object> root = new HashMap<>();
root.put("config", config);
root.put("model", Model.get());
root.put("header", Model.get().getHeader());

template.process(root, out);
}
}



private void generateSqliteOpenHelper(Arguments arguments) throws IOException, JSONException, TemplateException {
Template template = getFreeMarkerConfig().getTemplate("sqliteopenhelper.ftl");
JSONObject config = getConfig(arguments.inputDir);
Expand Down Expand Up @@ -527,6 +560,8 @@ private void go(String[] args) throws IOException, JSONException, TemplateExcept
generateWrappers(arguments);
generateModels(arguments);
generateContentProvider(arguments);

generateContentProviderCallbacks(arguments);
generateSqliteOpenHelper(arguments);
generateSqliteOpenHelperCallbacks(arguments);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,13 @@ import android.content.ContentProviderResult;
import android.content.ContentValues;
import android.content.OperationApplicationException;
import android.database.Cursor;
<#if config.useEncryptedDatabase>
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;
<#else>
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
</#if>
import android.net.Uri;
import android.provider.BaseColumns;
<#if config.useAnnotations>
Expand All @@ -39,13 +44,17 @@ public abstract class BaseContentProvider extends ContentProvider {

protected abstract QueryParams getQueryParams(Uri uri, String selection, String[] projection);
protected abstract boolean hasDebug();
<#if config.useEncryptedDatabase>
protected abstract String getPassword();
</#if>

protected abstract SQLiteOpenHelper createSqLiteOpenHelper();

protected SQLiteOpenHelper mSqLiteOpenHelper;


@Override
public final boolean onCreate() {
public boolean onCreate() {
if (hasDebug()) {
// Enable logging of SQL statements as they are executed.
try {
Expand All @@ -70,7 +79,11 @@ public abstract class BaseContentProvider extends ContentProvider {
@Override
public Uri insert(Uri uri, ContentValues values) {
String table = uri.getLastPathSegment();
<#if config.useEncryptedDatabase>
long rowId = mSqLiteOpenHelper.getWritableDatabase(getPassword()).insertOrThrow(table, null, values);
<#else>
long rowId = mSqLiteOpenHelper.getWritableDatabase().insertOrThrow(table, null, values);
</#if>
if (rowId == -1) return null;
String notify;
if (((notify = uri.getQueryParameter(QUERY_NOTIFY)) == null || "true".equals(notify))) {
Expand All @@ -82,7 +95,11 @@ public abstract class BaseContentProvider extends ContentProvider {
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
String table = uri.getLastPathSegment();
<#if config.useEncryptedDatabase>
SQLiteDatabase db = mSqLiteOpenHelper.getWritableDatabase(getPassword());
<#else>
SQLiteDatabase db = mSqLiteOpenHelper.getWritableDatabase();
</#if>
int res = 0;
db.beginTransaction();
try {
Expand All @@ -108,7 +125,11 @@ public abstract class BaseContentProvider extends ContentProvider {
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
QueryParams queryParams = getQueryParams(uri, selection, null);
<#if config.useEncryptedDatabase>
int res = mSqLiteOpenHelper.getWritableDatabase(getPassword()).update(queryParams.table, values, queryParams.selection, selectionArgs);
<#else>
int res = mSqLiteOpenHelper.getWritableDatabase().update(queryParams.table, values, queryParams.selection, selectionArgs);
</#if>
String notify;
if (res != 0 && ((notify = uri.getQueryParameter(QUERY_NOTIFY)) == null || "true".equals(notify))) {
getContext().getContentResolver().notifyChange(uri, null);
Expand All @@ -119,7 +140,12 @@ public abstract class BaseContentProvider extends ContentProvider {
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
QueryParams queryParams = getQueryParams(uri, selection, null);
<#if config.useEncryptedDatabase>
int res = mSqLiteOpenHelper.getWritableDatabase(getPassword()).delete(queryParams.table, queryParams.selection, selectionArgs);
<#else>
int res = mSqLiteOpenHelper.getWritableDatabase().delete(queryParams.table, queryParams.selection, selectionArgs);
</#if>

String notify;
if (res != 0 && ((notify = uri.getQueryParameter(QUERY_NOTIFY)) == null || "true".equals(notify))) {
getContext().getContentResolver().notifyChange(uri, null);
Expand All @@ -134,8 +160,14 @@ public abstract class BaseContentProvider extends ContentProvider {
String limit = uri.getQueryParameter(QUERY_LIMIT);
QueryParams queryParams = getQueryParams(uri, selection, projection);
projection = ensureIdIsFullyQualified(projection, queryParams.table, queryParams.idColumn);
<#if config.useEncryptedDatabase>
Cursor res = mSqLiteOpenHelper.getReadableDatabase(getPassword()).query(queryParams.tablesWithJoins, projection, queryParams.selection, selectionArgs,
groupBy, having, sortOrder == null ? queryParams.orderBy : sortOrder, limit);
<#else>
Cursor res = mSqLiteOpenHelper.getReadableDatabase().query(queryParams.tablesWithJoins, projection, queryParams.selection, selectionArgs, groupBy,
having, sortOrder == null ? queryParams.orderBy : sortOrder, limit);
</#if>

res.setNotificationUri(getContext().getContentResolver(), uri);
return res;
}
Expand All @@ -159,7 +191,11 @@ public abstract class BaseContentProvider extends ContentProvider {
for (ContentProviderOperation operation : operations) {
urisToNotify.add(operation.getUri());
}
<#if config.useEncryptedDatabase>
SQLiteDatabase db = mSqLiteOpenHelper.getWritableDatabase(getPassword());
<#else>
SQLiteDatabase db = mSqLiteOpenHelper.getWritableDatabase();
</#if>
db.beginTransaction();
try {
int numOperations = operations.size();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import java.util.Arrays;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
<#if config.useEncryptedDatabase>
import net.sqlcipher.database.SQLiteOpenHelper;
<#else>
import android.database.sqlite.SQLiteDatabase;
</#if>
import android.net.Uri;
<#if config.useAnnotations>
import android.support.annotation.NonNull;
Expand All @@ -32,6 +36,11 @@ public class ${config.providerClassName} extends BaseContentProvider {
public static final String AUTHORITY = "${config.authority}";
public static final String CONTENT_URI_BASE = "content://" + AUTHORITY;

<#if config.useEncryptedDatabase>
private ${config.providerCallbacksClassName} mProviderCallbacks;
</#if>


<#assign i=0>
<#list model.entities as entity>
private static final int URI_TYPE_${entity.nameUpperCase} = ${i};
Expand All @@ -42,7 +51,7 @@ public class ${config.providerClassName} extends BaseContentProvider {
</#list>


private static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
protected static final UriMatcher URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);

static {
<#list model.entities as entity>
Expand All @@ -51,11 +60,30 @@ public class ${config.providerClassName} extends BaseContentProvider {
</#list>
}

protected ${config.sqliteOpenHelperClassName} m${config.sqliteOpenHelperClassName};
<#if config.useEncryptedDatabase>

@Override
public final boolean onCreate() {
super.onCreate();
mProviderCallbacks = new ${config.providerCallbacksClassName}();
return false;
}

@Override
protected String getPassword(){
return mProviderCallbacks.onPasswordRequested();
}
</#if>


@Override
protected SQLiteOpenHelper createSqLiteOpenHelper() {
return ${config.sqliteOpenHelperClassName}.getInstance(getContext());
}



@Override
protected boolean hasDebug() {
return DEBUG;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<#if header??>
${header}
</#if>
package ${config.providerJavaPackage};

import android.content.Context;
<#if config.useEncryptedDatabase>
import net.sqlcipher.database.SQLiteDatabase;
<#else>
import android.database.sqlite.SQLiteDatabase;
</#if>
import android.util.Log;

import ${config.projectPackageId}.BuildConfig;

/**
* Implement your custom database creation or upgrade code here.
*
* This file will not be overwritten if you re-run the content provider generator.
*/
public class ${config.providerCallbacksClassName} {
private static final String TAG = ${config.providerCallbacksClassName}.class.getSimpleName();

public String onPasswordRequested() {
if (BuildConfig.DEBUG) Log.d(TAG, "onPasswordRequested");
//TODO Insert your own password provider
return "password";

}
}
Loading