diff --git a/kripton-android-core/kripton-android-core.iml b/kripton-android-core/kripton-android-core.iml deleted file mode 100644 index 05db5c8fd..000000000 --- a/kripton-android-core/kripton-android-core.iml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/kripton-android-core/src/main/java/com/abubusoft/kripton/android/KriptonLibrary.java b/kripton-android-core/src/main/java/com/abubusoft/kripton/android/KriptonLibrary.java index 947b303bc..5d83ab10f 100644 --- a/kripton-android-core/src/main/java/com/abubusoft/kripton/android/KriptonLibrary.java +++ b/kripton-android-core/src/main/java/com/abubusoft/kripton/android/KriptonLibrary.java @@ -78,7 +78,7 @@ public static void init(Context contextValue) { * * @param contextValue * the context value - * @param executorService + * @param service * the executor service */ public static void init(Context contextValue, ExecutorService service) { diff --git a/kripton-android-library/src/test/java/sqlite/feature/kotlin/immutable/ArticleTable.java b/kripton-android-library/src/test/java/sqlite/feature/kotlin/immutable/ArticleTable.java index 053818378..6646c114f 100644 --- a/kripton-android-library/src/test/java/sqlite/feature/kotlin/immutable/ArticleTable.java +++ b/kripton-android-library/src/test/java/sqlite/feature/kotlin/immutable/ArticleTable.java @@ -158,11 +158,11 @@ public static Thumbnail parseThumbnail(byte[] input) { JsonParser jacksonParser=wrapper.jacksonParser; // START_OBJECT jacksonParser.nextToken(); - Thumbnail __thumbnail=null; + Thumbnail result=null; if (jacksonParser.currentToken()==JsonToken.START_OBJECT) { - __thumbnail=thumbnailBindMap.parseOnJackson(jacksonParser); + result=thumbnailBindMap.parseOnJackson(jacksonParser); } - return __thumbnail; + return result; } catch(Exception e) { e.printStackTrace(); throw(new KriptonRuntimeException(e.getMessage())); diff --git a/kripton-android-library/src/test/java/sqlite/feature/kotlin/immutable/ChannelTable.java b/kripton-android-library/src/test/java/sqlite/feature/kotlin/immutable/ChannelTable.java index 0a5e8a505..1627be331 100644 --- a/kripton-android-library/src/test/java/sqlite/feature/kotlin/immutable/ChannelTable.java +++ b/kripton-android-library/src/test/java/sqlite/feature/kotlin/immutable/ChannelTable.java @@ -158,11 +158,11 @@ public static Image parseImage(byte[] input) { JsonParser jacksonParser=wrapper.jacksonParser; // START_OBJECT jacksonParser.nextToken(); - Image __image=null; + Image result=null; if (jacksonParser.currentToken()==JsonToken.START_OBJECT) { - __image=imageBindMap.parseOnJackson(jacksonParser); + result=imageBindMap.parseOnJackson(jacksonParser); } - return __image; + return result; } catch(Exception e) { e.printStackTrace(); throw(new KriptonRuntimeException(e.getMessage())); diff --git a/kripton-android-library/src/test/java/sqlite/feature/many2many/case6/persistence/Person2PhoneDaoImpl.java b/kripton-android-library/src/test/java/sqlite/feature/many2many/case6/persistence/Person2PhoneDaoImpl.java index d5b592a18..a081ba530 100644 --- a/kripton-android-library/src/test/java/sqlite/feature/many2many/case6/persistence/Person2PhoneDaoImpl.java +++ b/kripton-android-library/src/test/java/sqlite/feature/many2many/case6/persistence/Person2PhoneDaoImpl.java @@ -521,7 +521,7 @@ public int deleteByPhoneNumberId(long phoneNumberId) { /** *

SQL insert

- *
INSERT INTO person_phone (buy_date, person_id, phone_number_id) VALUES (:buyDate, :personId, :phoneNumberId)
+ *
INSERT INTO person_phone (buy_date, person_id, phone_number_id) VALUES (:bean.buyDate, :bean.personId, :bean.phoneNumberId)
* *

bean.id is automatically updated because it is the primary key

* diff --git a/kripton-android-library/src/test/java/sqlite/feature/many2many/entity/PersonCityOk1DaoImpl.java b/kripton-android-library/src/test/java/sqlite/feature/many2many/entity/PersonCityOk1DaoImpl.java index 5ed183b0e..3efc2de77 100644 --- a/kripton-android-library/src/test/java/sqlite/feature/many2many/entity/PersonCityOk1DaoImpl.java +++ b/kripton-android-library/src/test/java/sqlite/feature/many2many/entity/PersonCityOk1DaoImpl.java @@ -498,7 +498,7 @@ public int deleteByCityId(long cityId) { /** *

SQL insert

- *
INSERT INTO person_city_ok1 (city_id, person_id) VALUES (:cityId, :personId)
+ *
INSERT INTO person_city_ok1 (city_id, person_id) VALUES (:bean.cityId, :bean.personId)
* *

bean.id is automatically updated because it is the primary key

* diff --git a/kripton-android-library/src/test/java/sqlite/feature/many2many/err3/PersonCityErr1DaoImpl.java b/kripton-android-library/src/test/java/sqlite/feature/many2many/err3/PersonCityErr1DaoImpl.java index 8f993437a..73f176880 100644 --- a/kripton-android-library/src/test/java/sqlite/feature/many2many/err3/PersonCityErr1DaoImpl.java +++ b/kripton-android-library/src/test/java/sqlite/feature/many2many/err3/PersonCityErr1DaoImpl.java @@ -426,7 +426,7 @@ public int deleteByCityId(long cityId) { /** *

SQL insert

- *
INSERT INTO person_city_err3 (city_id, person_id) VALUES (:cityId, :personId)
+ *
INSERT INTO person_city_err3 (city_id, person_id) VALUES (:bean.cityId, :bean.personId)
* *

bean.id is automatically updated because it is the primary key

* diff --git a/kripton-android-library/src/test/java/sqlite/git104/DocumentTable.java b/kripton-android-library/src/test/java/sqlite/git104/DocumentTable.java index 36e5aef1f..a98cd5b2e 100644 --- a/kripton-android-library/src/test/java/sqlite/git104/DocumentTable.java +++ b/kripton-android-library/src/test/java/sqlite/git104/DocumentTable.java @@ -130,11 +130,11 @@ public static DocumentInfo parseInfo(byte[] input) { JsonParser jacksonParser=wrapper.jacksonParser; // START_OBJECT jacksonParser.nextToken(); - DocumentInfo result=null; + DocumentInfo __info=null; if (jacksonParser.currentToken()==JsonToken.START_OBJECT) { - result=documentInfoBindMap.parseOnJackson(jacksonParser); + __info=documentInfoBindMap.parseOnJackson(jacksonParser); } - return result; + return __info; } catch(Exception e) { e.printStackTrace(); throw(new KriptonRuntimeException(e.getMessage())); diff --git a/kripton-arch-integration/kripton-arch-integration.iml b/kripton-arch-integration/kripton-arch-integration.iml deleted file mode 100644 index 9807b9bf7..000000000 --- a/kripton-arch-integration/kripton-arch-integration.iml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/kripton-arch-test/kripton-arch-test.iml b/kripton-arch-test/kripton-arch-test.iml deleted file mode 100644 index cdf1f5936..000000000 --- a/kripton-arch-test/kripton-arch-test.iml +++ /dev/null @@ -1,80 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/AbstractDataSource.java b/kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/AbstractDataSource.java index 3547ce984..fe8ca8bdf 100644 --- a/kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/AbstractDataSource.java +++ b/kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/AbstractDataSource.java @@ -50,859 +50,845 @@ */ public abstract class AbstractDataSource implements AutoCloseable { - /** - * Interface for database operations. - * - * @param - * the element type - */ - public interface AbstractExecutable { - - /** - * Execute transation. Method need to return - * {@link TransactionResult#COMMIT} to commit results or - * {@link TransactionResult#ROLLBACK} to rollback. If exception is - * thrown, a rollback will be done. - * - * @param daoFactory - * the dao factory - * @return the transaction result - */ - TransactionResult onExecute(E daoFactory); - } - - /** - * The listener interface for receiving onError events. The class that is - * interested in processing a onError event implements this interface, and - * the object created with that class is registered with a component using - * the component's addOnErrorListener method. When the onError - * event occurs, that object's appropriate method is invoked. - * - */ - public interface OnErrorListener { - /** - * Manages error situations. + /** + * Interface for database operations. * - * @param e - * exception + * @param the element type */ - void onError(Throwable e); - } + public interface AbstractExecutable { + + /** + * Execute transation. Method need to return + * {@link TransactionResult#COMMIT} to commit results or + * {@link TransactionResult#ROLLBACK} to rollback. If exception is + * thrown, a rollback will be done. + * + * @param daoFactory the dao factory + * @return the transaction result + */ + TransactionResult onExecute(E daoFactory); + } - /** - * The Enum TypeStatus. - */ - public enum TypeStatus { + /** + * The listener interface for receiving onError events. The class that is + * interested in processing a onError event implements this interface, and + * the object created with that class is registered with a component using + * the component's addOnErrorListener method. When the onError + * event occurs, that object's appropriate method is invoked. + */ + public interface OnErrorListener { + /** + * Manages error situations. + * + * @param e exception + */ + void onError(Throwable e); + } - /** The closed. */ - CLOSED, - /** The read and write opened. */ - READ_AND_WRITE_OPENED, - /** The read only opened. */ - READ_ONLY_OPENED - } + /** + * The Enum TypeStatus. + */ + public enum TypeStatus { + + /** + * The closed. + */ + CLOSED, + /** + * The read and write opened. + */ + READ_AND_WRITE_OPENED, + /** + * The read only opened. + */ + READ_ONLY_OPENED + } - /** The context. */ - protected SQLContextImpl context; + /** + * The context. + */ + protected SQLContextImpl context; - /** database instance. */ - SupportSQLiteDatabase database; + /** + * database instance. + */ + SupportSQLiteDatabase database; - /** - *

- * True if dataSource is just created - *

- * . - */ - protected boolean justCreated = false; + /** + *

+ * True if dataSource is just created + *

+ * . + */ + protected boolean justCreated = false; - /** The lock access. */ - private final ReentrantReadWriteLock lockAccess = new ReentrantReadWriteLock(); + /** + * The lock access. + */ + private final ReentrantReadWriteLock lockAccess = new ReentrantReadWriteLock(); - /** The lock db. */ - private final ReentrantLock lockDb = new ReentrantLock(); + /** + * The lock db. + */ + private final ReentrantLock lockDb = new ReentrantLock(); - /** The lock read access. */ - private final Lock lockReadAccess = lockAccess.readLock(); + /** + * The lock read access. + */ + private final Lock lockReadAccess = lockAccess.readLock(); - /** The lock read write access. */ - private final Lock lockReadWriteAccess = lockAccess.writeLock(); + /** + * The lock read write access. + */ + private final Lock lockReadWriteAccess = lockAccess.writeLock(); - /** The log enabled. */ - protected boolean logEnabled; + /** + * The log enabled. + */ + protected boolean logEnabled; - /** - *

- * file name used to save database, - *

- * . - */ - protected final String name; + /** + *

+ * file name used to save database, + *

+ * . + */ + protected final String name; - /** The on error listener. */ - protected OnErrorListener onErrorListener = (Throwable e) -> { - throw (new KriptonRuntimeException(e)); - }; + /** + * The on error listener. + */ + protected OnErrorListener onErrorListener = (Throwable e) -> { + throw (new KriptonRuntimeException(e)); + }; - /** The open counter. */ - private final AtomicInteger openCounter = new AtomicInteger(); + /** + * The open counter. + */ + private final AtomicInteger openCounter = new AtomicInteger(); - /** The options. */ - protected DataSourceOptions options; + /** + * The options. + */ + protected DataSourceOptions options; - /** The sqlite helper. */ - protected SupportSQLiteOpenHelper sqliteHelper; + /** + * The sqlite helper. + */ + protected SupportSQLiteOpenHelper sqliteHelper; - /** The status. Do not replace with Initial, it does not work on Android. */ - protected ThreadLocal status = new ThreadLocal() { + /** + * The status. Do not replace with Initial, it does not work on Android. + */ + protected ThreadLocal status = new ThreadLocal() { + + @Override + protected TypeStatus initialValue() { + return TypeStatus.CLOSED; + } + + }; + /** + *

+ * database version + *

+ * . + */ + protected int version; + + /** + * if true, database was update during this application run. + */ + protected boolean versionChanged; + + /** + * Instantiates a new abstract data source. + * + * @param name the name + * @param version the version + * @param options the options + */ + protected AbstractDataSource(String name, int version, DataSourceOptions options) { + DataSourceOptions optionsValue = (options != null) ? options : DataSourceOptions.builder().build(); + + if (optionsValue.inMemory) { + this.name = null; + } else if (StringUtils.hasText(optionsValue.name)) { + this.name = optionsValue.name; + } else { + this.name = name; + } + this.version = version; + + // create new SQLContext + this.context = new SQLContextImpl(this); + + this.options = optionsValue; + this.logEnabled = optionsValue.logEnabled; + + if (this.logEnabled) { + Logger.debug("%s is created with %s", getClass().getName(), optionsValue.toString()); + } + } + + protected void beginLock() { + lockDb.lock(); + } + + /** + * Builds the task list. + * + * @param previousVersion the previous version + * @param currentVersion the current version + * @return the list + */ + protected List buildTaskList(int previousVersion, int currentVersion) { + List result = new ArrayList<>(); + + for (Pair item : this.options.updateTasks) { + if (item.value0 - 1 == previousVersion) { + result.add(item.value1); + previousVersion = item.value0; + } + + if (previousVersion == currentVersion) + break; + } + + if (previousVersion != currentVersion) { + Logger.warn(String.format("Can not find version update task from version %s to version %s", previousVersion, + currentVersion)); + } + + return result; + + } + + /** + * used to clear prepared statements. + */ + public abstract void clearCompiledStatements(); + + /** + * Context. + * + * @return the SQL context + */ + public SQLContext getContext() { + return context; + } + + /* + * (non-Javadoc) + * + * @see android.database.sqlite.SQLiteOpenHelper#close() + */ @Override - protected TypeStatus initialValue() { - return TypeStatus.CLOSED; - } - - }; - /** - *

- * database version - *

- * . - */ - protected int version; - - /** if true, database was update during this application run. */ - protected boolean versionChanged; - - /** - * Instantiates a new abstract data source. - * - * @param name - * the name - * @param version - * the version - * @param options - * the options - */ - protected AbstractDataSource(String name, int version, DataSourceOptions options) { - DataSourceOptions optionsValue = (options != null) ? options : DataSourceOptions.builder().build(); - - if (optionsValue.inMemory) { - this.name=null; - } else if (StringUtils.hasText(optionsValue.name)) { - this.name=optionsValue.name; - } else { - this.name=name; - } - - this.version = version; - - // create new SQLContext - this.context = new SQLContextImpl(this); - - this.options = optionsValue; - this.logEnabled = optionsValue.logEnabled; - - if (this.logEnabled) { - Logger.debug("%s is created with %s", getClass().getName(), optionsValue.toString()); - } - } - - protected void beginLock() { - lockDb.lock(); - } - - /** - * Builds the task list. - * - * @param previousVersion - * the previous version - * @param currentVersion - * the current version - * @return the list - */ - protected List buildTaskList(int previousVersion, int currentVersion) { - List result = new ArrayList<>(); - - for (Pair item : this.options.updateTasks) { - if (item.value0 - 1 == previousVersion) { - result.add(item.value1); - previousVersion = item.value0; - } - - if (previousVersion == currentVersion) - break; - } - - if (previousVersion != currentVersion) { - Logger.warn(String.format("Can not find version update task from version %s to version %s", previousVersion, - currentVersion)); - } - - return result; - - } - - /** - * used to clear prepared statements. - */ - public abstract void clearCompiledStatements(); - - /** - * Context. - * - * @return the SQL context - */ - public SQLContext getContext() { - return context; - } - - /* - * (non-Javadoc) - * - * @see android.database.sqlite.SQLiteOpenHelper#close() - */ - @Override - public void close() { - beginLock(); - try { - if (openCounter.decrementAndGet() <= 0) { - - if (!this.options.inMemory) { - // Closing database - if (database != null) { - clearCompiledStatements(); - sqliteHelper.close(); - } - database = null; + public void close() { + beginLock(); + try { + if (openCounter.decrementAndGet() <= 0) { + + if (!this.options.inMemory) { + // Closing database + if (database != null) { + clearCompiledStatements(); + sqliteHelper.close(); + } + database = null; + } + if (logEnabled) + Logger.info("database CLOSED (%s) (connections: %s)", status.get(), openCounter.intValue()); + } else { + if (logEnabled) + Logger.info("database RELEASED (%s) (connections: %s)", status.get(), openCounter.intValue()); + } + } catch (Exception e) { + e.printStackTrace(); + throw (e); + } finally { + manageStatus(); + endLock(); + } + + } + + protected void closeThreadSafeMode(Pair status) { + if (status.value0) { + close(); + } else { + beginLock(); + // we unlock lockReadWriteAccess, so we can include this code in + manageStatus(); + endLock(); + } + } + + /** + * Content values. + * + * @param compiledStatement the compiled statement + * @return the kripton content values + */ + protected KriptonContentValues contentValues(SupportSQLiteStatement compiledStatement) { + return context.contentValues(compiledStatement); + } + + /** + * Content values for content provider. + * + * @param values the values + * @return the kripton content values + */ + protected KriptonContentValues contentValuesForContentProvider(ContentValues values) { + return context.contentValuesForContentProvider(values); + } + + /** + * Content values for update. + * + * @param compiledStatement the compiled statement + * @return the kripton content values + */ + protected KriptonContentValues contentValuesForUpdate(SupportSQLiteStatement compiledStatement) { + return context.contentValuesForUpdate(compiledStatement); + } + + /** + * Creates the helper. + */ + protected void createHelper() { + if (KriptonLibrary.getContext() == null) + throw new KriptonRuntimeException( + "Kripton library is not properly initialized. Please use KriptonLibrary.init(context) somewhere at application startup"); + + if (this.logEnabled) { + if (options.inMemory) { + Logger.info("In-memory database"); + } else { + File dbFile = KriptonLibrary.getContext().getDatabasePath(name); + Logger.info("Database file %s", dbFile.getAbsolutePath()); + } + } + + Builder config = SupportSQLiteOpenHelper.Configuration.builder(KriptonLibrary.getContext()).name(name) + .callback(new SupportSQLiteOpenHelper.Callback(version) { + + @Override + public void onConfigure(@NonNull SupportSQLiteDatabase db) { + AbstractDataSource.this.onConfigure(db); + } + + @Override + public void onCorruption(@NonNull SupportSQLiteDatabase db) { + AbstractDataSource.this.onCorruption(db); + } + + @Override + public void onCreate(@NonNull SupportSQLiteDatabase db) { + sqliteHelper.setWriteAheadLoggingEnabled(true); + AbstractDataSource.this.onCreate(db); + } + + @Override + public void onDowngrade(@NonNull SupportSQLiteDatabase db, int oldVersion, int newVersion) { + AbstractDataSource.this.onDowngrade(db, oldVersion, newVersion); + } + + @Override + public void onOpen(@NonNull SupportSQLiteDatabase db) { + sqliteHelper.setWriteAheadLoggingEnabled(true); + AbstractDataSource.this.onOpen(db); + } + + @Override + public void onUpgrade(@NonNull SupportSQLiteDatabase db, int oldVersion, int newVersion) { + AbstractDataSource.this.onUpgrade(db, oldVersion, newVersion); + } + }); + + sqliteHelper = options.openHelperFactory.create(config.build()); + + if (this.logEnabled) { + Logger.debug("Database helper factory class is %s", options.openHelperFactory.getClass().getName()); + Logger.debug("Database helper class is %s", sqliteHelper.getClass().getName()); + } + } + + private void deleteDatabaseFile(String fileName) { + if (fileName.equalsIgnoreCase(":memory:") || fileName.trim().length() == 0) { + return; + } + if (this.logEnabled) { + Logger.fatal("deleting the database file: " + fileName); } - if (logEnabled) - Logger.info("database CLOSED (%s) (connections: %s)", status.get(), openCounter.intValue()); - } else { - if (logEnabled) - Logger.info("database RELEASED (%s) (connections: %s)", status.get(), openCounter.intValue()); - } - } catch (Exception e) { - e.printStackTrace(); - throw (e); - } finally { - manageStatus(); - endLock(); - } - - } - - protected void closeThreadSafeMode(Pair status) { - if (status.value0 == true) { - close(); - } else { - beginLock(); - // we unlock lockReadWriteAccess, so we can include this code in - // lockDb - manageStatus(); - endLock(); - - // unlocked inside - // lockDb.unlock(); - } - } - - /** - * Content values. - * - * @param compiledStatement - * the compiled statement - * @return the kripton content values - */ - protected KriptonContentValues contentValues(SupportSQLiteStatement compiledStatement) { - return context.contentValues(compiledStatement); - } - - /** - * Content values for content provider. - * - * @param values - * the values - * @return the kripton content values - */ - protected KriptonContentValues contentValuesForContentProvider(ContentValues values) { - return context.contentValuesForContentProvider(values); - } - - /** - * Content values for update. - * - * @param compiledStatement - * the compiled statement - * @return the kripton content values - */ - protected KriptonContentValues contentValuesForUpdate(SupportSQLiteStatement compiledStatement) { - return context.contentValuesForUpdate(compiledStatement); - } - - /** - * Creates the helper. - */ - protected void createHelper() { - if (KriptonLibrary.getContext() == null) - throw new KriptonRuntimeException( - "Kripton library is not properly initialized. Please use KriptonLibrary.init(context) somewhere at application startup"); - - if (this.logEnabled) { - if (options.inMemory) { - Logger.info("In-memory database"); - } else { - File dbFile = KriptonLibrary.getContext().getDatabasePath(name); - Logger.info("Database file %s", dbFile.getAbsolutePath()); - } - } - - Builder config = SupportSQLiteOpenHelper.Configuration.builder(KriptonLibrary.getContext()).name(name) - .callback(new SupportSQLiteOpenHelper.Callback(version) { - - @Override - public void onConfigure(@NonNull SupportSQLiteDatabase db) { - AbstractDataSource.this.onConfigure(db); - } - - @Override - public void onCorruption(@NonNull SupportSQLiteDatabase db) { - AbstractDataSource.this.onCorruption(db); - } - - @Override - public void onCreate(@NonNull SupportSQLiteDatabase db) { - sqliteHelper.setWriteAheadLoggingEnabled(true); - AbstractDataSource.this.onCreate(db); - } - - @Override - public void onDowngrade(@NonNull SupportSQLiteDatabase db, int oldVersion, int newVersion) { - AbstractDataSource.this.onDowngrade(db, oldVersion, newVersion); - } - - @Override - public void onOpen(@NonNull SupportSQLiteDatabase db) { - sqliteHelper.setWriteAheadLoggingEnabled(true); - AbstractDataSource.this.onOpen(db); - } - - @Override - public void onUpgrade(@NonNull SupportSQLiteDatabase db, int oldVersion, int newVersion) { - AbstractDataSource.this.onUpgrade(db, oldVersion, newVersion); - } - }); - - sqliteHelper = options.openHelperFactory.create(config.build()); - - if (this.logEnabled) { - Logger.debug("Database helper factory class is %s", options.openHelperFactory.getClass().getName()); - Logger.debug("Database helper class is %s", sqliteHelper.getClass().getName()); - } - } - - private void deleteDatabaseFile(String fileName) { - if (fileName.equalsIgnoreCase(":memory:") || fileName.trim().length() == 0) { - return; - } - if (this.logEnabled) { - Logger.fatal("deleting the database file: " + fileName); - } - try { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { - SQLiteDatabase.deleteDatabase(new File(fileName)); - } else { try { - final boolean deleted = new File(fileName).delete(); - if (!deleted) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { + SQLiteDatabase.deleteDatabase(new File(fileName)); + } else { + try { + final boolean deleted = new File(fileName).delete(); + if (!deleted && this.logEnabled) { + Logger.fatal("Could not delete the database file " + fileName); + } + } catch (Exception error) { + if (this.logEnabled) { + Logger.fatal("error while deleting corrupted database file " + error.getMessage()); + } + } + } + } catch (Exception e) { if (this.logEnabled) { - Logger.fatal("Could not delete the database file " + fileName); + /* print warning and ignore exception */ + Logger.warn("delete failed: ", e); } - } - } catch (Exception error) { - if (this.logEnabled) { - Logger.fatal("error while deleting corrupted database file " + error.getMessage()); - } } - } - } catch (Exception e) { - if (this.logEnabled) { - /* print warning and ignore exception */ - Logger.warn("delete failed: ", e); - } - } - } - - protected void endLock() { - lockDb.unlock(); - } - - /** - * Force close. - */ - void forceClose() { - openCounter.set(0); - } - - /** - *

- * Return database object or runtimeexception if no database is opened. - *

- * - * @return the SQ lite database - */ - public SupportSQLiteDatabase getDatabase() { - if (database == null) - throw (new KriptonRuntimeException( - "No database connection is opened before use " + this.getClass().getCanonicalName())); - return database; - } - - public String getName() { - return name; - } - - // /** - // * Sets the version. - // * - // * @param version - // * the new version - // */ - // public void setVersion(int version) { - // this.version = version; - // } - - /** - * Get error listener, in transations. - * - * @return the on error listener - */ - public OnErrorListener getOnErrorListener() { - return onErrorListener; - } - - /** - * Gets the version. - * - * @return the version - */ - public int getVersion() { - return version; - } - - /** - *

- * True if dataSource is just created - *

- * . - * - * @return true, if is just created - */ - public boolean isJustCreated() { - return justCreated; - } - - /** - * Checks if is log enabled. - * - * @return true, if is log enabled - */ - public boolean isLogEnabled() { - return context.isLogEnabled(); - } - - /** - *

- * return true if database is already opened. - *

- * - * @return true if database is opened, otherwise false - */ - public boolean isOpen() { - return database != null && database.isOpen() && database.isDbLockedByCurrentThread(); - } - - /** - * Return true if any operation is running on datasource, - * false if database is currently closed. - * - * @return - */ - public boolean isAnyPendingOperation() { - return openCounter.get() > 0; - } - - /** - *

- * return true if database is already opened in write mode. - *

- * - * @return true if database is opened, otherwise false - */ - public boolean isOpenInWriteMode() { - // return database != null && database.isOpen() && - // !database.isReadOnly() && database.isDbLockedByCurrentThread(); - return database != null && database.isOpen() && !database.isReadOnly() && database.isDbLockedByCurrentThread(); - } - - /** - * Checks if is upgraded version. - * - * @return the upgradedVersion - */ - public boolean isUpgradedVersion() { - return versionChanged; - } - - /** - * - */ - private void manageStatus() { - switch (status.get()) { - case READ_AND_WRITE_OPENED: - if (database == null) - status.set(TypeStatus.CLOSED); - lockReadWriteAccess.unlock(); - // lockDb.unlock(); - break; - case READ_ONLY_OPENED: + } + + protected void endLock() { + lockDb.unlock(); + } + + /** + * Force close. + */ + void forceClose() { + openCounter.set(0); + } + + /** + *

+ * Return database object or runtimeexception if no database is opened. + *

+ * + * @return the SQ lite database + */ + public SupportSQLiteDatabase getDatabase() { if (database == null) - status.set(TypeStatus.CLOSED); - lockReadAccess.unlock(); - // lockDb.unlock(); - break; - case CLOSED: - // do nothing - // lockDb.unlock(); - break; - } - } - - /** - * Returns true if the database need foreign keys - * - * @return - * - */ - public abstract boolean hasForeignKeys(); - - /** - * On configure. - * - * @param database - * the database - */ - protected void onConfigure(SupportSQLiteDatabase database) { - // configure database - // database.setForeignKeyConstraintsEnabled(true); - if (options.databaseLifecycleHandler != null) { - options.databaseLifecycleHandler.onConfigure(database); - } - } - // protected abstract void onConfigure(SupportSQLiteDatabase database); - - /** - * The method invoked when database corruption is detected. Default - * implementation will delete the database file. - * - * @param db - * the {@link SupportSQLiteDatabase} object representing the - * database on which corruption is detected. - */ - protected void onCorruption(@NonNull SupportSQLiteDatabase db) { - // the following implementation is taken from {@link - // DefaultDatabaseErrorHandler}. - if (this.logEnabled) { - Logger.fatal("Corruption reported by sqlite on database: " + db.getPath()); - } - try { - if (options.databaseLifecycleHandler != null) { - options.databaseLifecycleHandler.onCorruption(db); - } - } catch (Throwable e) { - e.printStackTrace(); - } - - // is the corruption detected even before database could be 'opened'? - if (!db.isOpen()) { - // database files are not even openable. delete this database file. - // NOTE if the database has attached databases, then any of them - // could be corrupt. - // and not deleting all of them could cause corrupted database file - // to remain and - // make the application crash on database open operation. To avoid - // this problem, - // the application should provide its own {@link - // DatabaseErrorHandler} impl class - // to delete ALL files of the database (including the attached - // databases). - deleteDatabaseFile(db.getPath()); - return; - } - List> attachedDbs = null; - try { - // Close the database, which will cause subsequent operations to - // fail. - // before that, get the attached database list first. - try { - attachedDbs = db.getAttachedDbs(); - } catch (SQLiteException e) { - /* ignore */ - } - try { - db.close(); - } catch (IOException e) { - /* ignore */ - } - } finally { - // Delete all files of this corrupt database and/or attached - // databases - if (attachedDbs != null) { - for (android.util.Pair p : attachedDbs) { - deleteDatabaseFile(p.second); + throw (new KriptonRuntimeException( + "No database connection is opened before use " + this.getClass().getCanonicalName())); + return database; + } + + public String getName() { + return name; + } + + /** + * Get error listener, in transations. + * + * @return the on error listener + */ + public OnErrorListener getOnErrorListener() { + return onErrorListener; + } + + /** + * Gets the version. + * + * @return the version + */ + public int getVersion() { + return version; + } + + /** + *

+ * True if dataSource is just created + *

+ * . + * + * @return true, if is just created + */ + public boolean isJustCreated() { + return justCreated; + } + + /** + * Checks if is log enabled. + * + * @return true, if is log enabled + */ + public boolean isLogEnabled() { + return context.isLogEnabled(); + } + + /** + *

+ * return true if database is already opened. + *

+ * + * @return true if database is opened, otherwise false + */ + public boolean isOpen() { + return database != null && database.isOpen() && database.isDbLockedByCurrentThread(); + } + + /** + * Return true if any operation is running on datasource, + * false if database is currently closed. + * + * @return + */ + public boolean isAnyPendingOperation() { + return openCounter.get() > 0; + } + + /** + *

+ * return true if database is already opened in write mode. + *

+ * + * @return true if database is opened, otherwise false + */ + public boolean isOpenInWriteMode() { + return database != null && database.isOpen() && !database.isReadOnly() && database.isDbLockedByCurrentThread(); + } + + /** + * Checks if is upgraded version. + * + * @return the upgradedVersion + */ + public boolean isUpgradedVersion() { + return versionChanged; + } + + /** + * + */ + private void manageStatus() { + switch (status.get()) { + case READ_AND_WRITE_OPENED: + if (database == null) + status.set(TypeStatus.CLOSED); + lockReadWriteAccess.unlock(); + break; + case READ_ONLY_OPENED: + if (database == null) + status.set(TypeStatus.CLOSED); + lockReadAccess.unlock(); + break; + case CLOSED: + // do nothing + break; } - } else { - // attachedDbs = null is possible when the database is so - // corrupt that even - // "PRAGMA database_list;" also fails. delete the main database - // file - deleteDatabaseFile(db.getPath()); - } - } - } - - /** - * On create. - * - * @param database - * the database - */ - protected abstract void onCreate(SupportSQLiteDatabase database); - - /** - * On downgrade. - * - * @param db - * the db - * @param oldVersion - * the old version - * @param newVersion - * the new version - */ - protected void onDowngrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { - if (options.databaseLifecycleHandler != null) { - options.databaseLifecycleHandler.onUpdate(db, oldVersion, newVersion, false); - versionChanged = true; - } - } - - protected void onOpen(SupportSQLiteDatabase db) { - if (AbstractDataSource.this.options.databaseLifecycleHandler != null) { - AbstractDataSource.this.options.databaseLifecycleHandler.onOpen(db); - versionChanged = true; - } - } - - /** - * On session closed. - * - * @return the sets the - */ - protected Set onSessionClosed() { - return this.context.onSessionClosed(); - - } - - /** - * On session opened. - */ - protected void onSessionOpened() { - this.context.onSessionOpened(); - } - - /** - * On upgrade. - * - * @param db - * the db - * @param oldVersion - * the old version - * @param newVersion - * the new version - */ - protected void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { - if (AbstractDataSource.this.options.databaseLifecycleHandler != null) { - AbstractDataSource.this.options.databaseLifecycleHandler.onUpdate(db, oldVersion, newVersion, true); - versionChanged = true; - } - } - - /** - * Open a database, if it is needed in - * - * @param writeMode - * @return - */ - protected Pair openDatabaseThreadSafeMode(boolean writeMode) { - Pair result = new Pair(); - - try { - // lock entire operation set - beginLock(); - boolean needToOpened = writeMode ? !this.isOpenInWriteMode() : !this.isOpen(); - result.value0 = needToOpened; - // in this part we can not lock lockReadWriteAccess, otherwise it - // may be a - // blocking race - // we lock lockReadWriteAccess after we release - if (needToOpened) { - if (writeMode) { - result.value1 = openWritableDatabase(false); - } else { - result.value1 = openReadOnlyDatabase(false); + } + + /** + * Returns true if the database need foreign keys + * + * @return + */ + public abstract boolean hasForeignKeys(); + + /** + * On configure. + * + * @param database the database + */ + protected void onConfigure(SupportSQLiteDatabase database) { + // configure database + if (options.databaseLifecycleHandler != null) { + options.databaseLifecycleHandler.onConfigure(database); + } + } + + /** + * The method invoked when database corruption is detected. Default + * implementation will delete the database file. + * + * @param db the {@link SupportSQLiteDatabase} object representing the + * database on which corruption is detected. + */ + protected void onCorruption(@NonNull SupportSQLiteDatabase db) { + // the following implementation is taken from {@link + // DefaultDatabaseErrorHandler}. + if (this.logEnabled) { + Logger.fatal("Corruption reported by sqlite on database: " + db.getPath()); + } + try { + if (options.databaseLifecycleHandler != null) { + options.databaseLifecycleHandler.onCorruption(db); + } + } catch (Throwable e) { + e.printStackTrace(); } - } else { - result.value1 = this.getDatabase(); - } - } finally { - // unlock entire operation set - endLock(); + // is the corruption detected even before database could be 'opened'? + if (!db.isOpen()) { + // database files are not even openable. delete this database file. + // NOTE if the database has attached databases, then any of them + // could be corrupt. + // and not deleting all of them could cause corrupted database file + // to remain and + // make the application crash on database open operation. To avoid + // this problem, + // the application should provide its own {@link + // DatabaseErrorHandler} impl class + // to delete ALL files of the database (including the attached + // databases). + deleteDatabaseFile(db.getPath()); + return; + } + List> attachedDbs = null; + try { + // Close the database, which will cause subsequent operations to + // fail. + // before that, get the attached database list first. + try { + attachedDbs = db.getAttachedDbs(); + } catch (SQLiteException e) { + /* ignore */ + } + try { + db.close(); + } catch (IOException e) { + /* ignore */ + } + } finally { + // Delete all files of this corrupt database and/or attached + // databases + if (attachedDbs != null) { + for (android.util.Pair p : attachedDbs) { + deleteDatabaseFile(p.second); + } + } else { + // attachedDbs = null is possible when the database is so + // corrupt that even + // "PRAGMA database_list;" also fails. delete the main database + // file + deleteDatabaseFile(db.getPath()); + } + } + } - if (writeMode) { - lockReadWriteAccess.lock(); - } else { - lockReadAccess.lock(); - } + /** + * On create. + * + * @param database the database + */ + protected abstract void onCreate(SupportSQLiteDatabase database); + + /** + * On downgrade. + * + * @param db the db + * @param oldVersion the old version + * @param newVersion the new version + */ + protected void onDowngrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { + if (options.databaseLifecycleHandler != null) { + options.databaseLifecycleHandler.onUpdate(db, oldVersion, newVersion, false); + versionChanged = true; + } + } + + protected void onOpen(SupportSQLiteDatabase db) { + if (AbstractDataSource.this.options.databaseLifecycleHandler != null) { + AbstractDataSource.this.options.databaseLifecycleHandler.onOpen(db); + versionChanged = true; + } + } + + /** + * On session closed. + * + * @return the sets the + */ + protected Set onSessionClosed() { + return this.context.onSessionClosed(); + + } + + /** + * On session opened. + */ + protected void onSessionOpened() { + this.context.onSessionOpened(); + } + + /** + * On upgrade. + * + * @param db the db + * @param oldVersion the old version + * @param newVersion the new version + */ + protected void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) { + if (AbstractDataSource.this.options.databaseLifecycleHandler != null) { + AbstractDataSource.this.options.databaseLifecycleHandler.onUpdate(db, oldVersion, newVersion, true); + versionChanged = true; + } + } + + /** + * Open a database, if it is needed in + * + * @param writeMode + * @return + */ + protected Pair openDatabaseThreadSafeMode(boolean writeMode) { + Pair result = new Pair<>(); + + try { + // lock entire operation set + beginLock(); + boolean needToOpened = writeMode ? !this.isOpenInWriteMode() : !this.isOpen(); + result.value0 = needToOpened; + // in this part we can not lock lockReadWriteAccess, otherwise it + // may be a + // blocking race + // we lock lockReadWriteAccess after we release + if (needToOpened) { + if (writeMode) { + result.value1 = openWritableDatabase(false); + } else { + result.value1 = openReadOnlyDatabase(false); + } + } else { + result.value1 = this.getDatabase(); + } + + } finally { + // unlock entire operation set + endLock(); + + if (writeMode) { + lockReadWriteAccess.lock(); + } else { + lockReadAccess.lock(); + } + + } + + return result; } - return result; + public SupportSQLiteDatabase openReadOnlyDatabase() { + return openReadOnlyDatabase(true); + } - } + /** + *

+ * Open a read only database. + *

+ * + * @return read only database + */ + protected SupportSQLiteDatabase openReadOnlyDatabase(boolean lock) { + if (lock) { + // if I lock this in dbLock.. the last one remains locked too + lockReadAccess.lock(); - public SupportSQLiteDatabase openReadOnlyDatabase() { - return openReadOnlyDatabase(true); - } + beginLock(); + } - /** - *

- * Open a read only database. - *

- * - * @return read only database - */ - protected SupportSQLiteDatabase openReadOnlyDatabase(boolean lock) { - if (lock) { - // if I lock this in dbLock.. the last one remains locked too - lockReadAccess.lock(); + try { + if (sqliteHelper == null) + createHelper(); + + status.set(TypeStatus.READ_ONLY_OPENED); + + if (openCounter.incrementAndGet() == 1) { + // open new read database + if (database == null) { + sqliteHelper.setWriteAheadLoggingEnabled(true); + database = sqliteHelper.getReadableDatabase(); + database.setForeignKeyConstraintsEnabled(hasForeignKeys()); + } + if (logEnabled) + Logger.info("database OPEN %s (connections: %s)", status.get(), (openCounter.intValue() - 1)); + } else { + if (logEnabled) + Logger.info("database REUSE %s (connections: %s)", status.get(), (openCounter.intValue() - 1)); + } + } catch (Throwable e) { + if (logEnabled) { + Logger.fatal("database error during open operation: %s", e.getMessage()); + e.printStackTrace(); + } + throw (e); + } finally { + if (lock) + endLock(); + + } - beginLock(); + return database; } - try { - if (sqliteHelper == null) - createHelper(); + /** + *

+ * open a writable database. + *

+ * + * @return writable database + */ + public SupportSQLiteDatabase openWritableDatabase() { + return openWritableDatabase(true); + } - status.set(TypeStatus.READ_ONLY_OPENED); + protected SupportSQLiteDatabase openWritableDatabase(boolean lock) { + if (lock) { + lockReadWriteAccess.lock(); - if (openCounter.incrementAndGet() == 1) { - // open new read database - if (database == null) { - sqliteHelper.setWriteAheadLoggingEnabled(true); - database = sqliteHelper.getReadableDatabase(); - database.setForeignKeyConstraintsEnabled(hasForeignKeys()); + // if I lock this in dbLock.. the last one remains locked too + beginLock(); } - if (logEnabled) - Logger.info("database OPEN %s (connections: %s)", status.get(), (openCounter.intValue() - 1)); - } else { - if (logEnabled) - Logger.info("database REUSE %s (connections: %s)", status.get(), (openCounter.intValue() - 1)); - } - } catch (Throwable e) { - if (logEnabled) { - Logger.fatal("database error during open operation: %s", e.getMessage()); - e.printStackTrace(); - } - throw (e); - } finally { - if (lock) - endLock(); - - } - - return database; - } - - /** - *

- * open a writable database. - *

- * - * @return writable database - */ - public SupportSQLiteDatabase openWritableDatabase() { - return openWritableDatabase(true); - } - - protected SupportSQLiteDatabase openWritableDatabase(boolean lock) { - if (lock) { - lockReadWriteAccess.lock(); - - // if I lock this in dbLock.. the last one remains locked too - beginLock(); - } - - try { - if (sqliteHelper == null) - createHelper(); - - status.set(TypeStatus.READ_AND_WRITE_OPENED); - - if (openCounter.incrementAndGet() == 1) { - // open new write database - if (database == null) { - sqliteHelper.setWriteAheadLoggingEnabled(true); - database = sqliteHelper.getWritableDatabase(); - database.setForeignKeyConstraintsEnabled(hasForeignKeys()); + + try { + if (sqliteHelper == null) + createHelper(); + + status.set(TypeStatus.READ_AND_WRITE_OPENED); + + if (openCounter.incrementAndGet() == 1) { + // open new write database + if (database == null) { + sqliteHelper.setWriteAheadLoggingEnabled(true); + database = sqliteHelper.getWritableDatabase(); + database.setForeignKeyConstraintsEnabled(hasForeignKeys()); + } + if (logEnabled) + Logger.info("database OPEN %s (connections: %s)", status.get(), (openCounter.intValue() - 1)); + } else { + if (logEnabled) + Logger.info("database REUSE %s (connections: %s)", status.get(), (openCounter.intValue() - 1)); + } + } catch (Throwable e) { + if (logEnabled) { + Logger.fatal("database error during open operation: %s", e.getMessage()); + e.printStackTrace(); + } + throw (e); + } finally { + if (lock) + endLock(); } - if (logEnabled) - Logger.info("database OPEN %s (connections: %s)", status.get(), (openCounter.intValue() - 1)); - } else { - if (logEnabled) - Logger.info("database REUSE %s (connections: %s)", status.get(), (openCounter.intValue() - 1)); - } - } catch (Throwable e) { - if (logEnabled) { - Logger.fatal("database error during open operation: %s", e.getMessage()); - e.printStackTrace(); - } - throw (e); - } finally { - if (lock) - endLock(); - } - - return database; - } - - /** - * Set error listener for transactions. - * - * @param onErrorListener - * the new on error listener - */ - public void setOnErrorListener(OnErrorListener onErrorListener) { - this.onErrorListener = onErrorListener; - } - - /** - * Sql builder. - * - * @return the string builder - */ - protected StringBuilder sqlBuilder() { - return context.sqlBuilder(); - } + + return database; + } + + /** + * Set error listener for transactions. + * + * @param onErrorListener the new on error listener + */ + public void setOnErrorListener(OnErrorListener onErrorListener) { + this.onErrorListener = onErrorListener; + } + + /** + * Sql builder. + * + * @return the string builder + */ + protected StringBuilder sqlBuilder() { + return context.sqlBuilder(); + } } diff --git a/kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/AbstractSQLContext.java b/kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/AbstractSQLContext.java index 71da36433..d4a95242d 100644 --- a/kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/AbstractSQLContext.java +++ b/kripton-orm/src/main/java/com/abubusoft/kripton/android/sqlite/AbstractSQLContext.java @@ -41,7 +41,7 @@ protected AbstractSQLContext(boolean session) { @Override protected Set initialValue() { - return new HashSet(); + return new HashSet<>(); } }; diff --git a/kripton-parent/kripton-parent.iml b/kripton-parent/kripton-parent.iml deleted file mode 100644 index 8cc7ef722..000000000 --- a/kripton-parent/kripton-parent.iml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/kripton-parent/pom.xml b/kripton-parent/pom.xml index 104ff6ff5..0102543c8 100644 --- a/kripton-parent/pom.xml +++ b/kripton-parent/pom.xml @@ -45,6 +45,8 @@ 2.9.0 2.2.19 + 0.8.6 + 4.12 3.4.2 @@ -218,7 +220,7 @@ org.jacoco jacoco-maven-plugin - 0.8.6 + ${jacoco-maven-plugin.version} diff --git a/kripton-processor/.README.md.html b/kripton-processor/.README.md.html deleted file mode 100644 index ecf81431c..000000000 --- a/kripton-processor/.README.md.html +++ /dev/null @@ -1,646 +0,0 @@ - - - - -C:\Users\xcesco\git\kripton\KriptonProcessor\.README.md.html - - - - - - - - - - -

Note about test

-

During development, you can need to view test's output. To enable test's output, you need to enable it with the creation of environment variable kripton.debug and set it to true.

-

In eclipse enviroment, you can use a simple plugin to manage environment variables Eclipse-Environment-Variables.

- - diff --git a/kripton-processor/pom.xml b/kripton-processor/pom.xml index 06a9d3412..123cd81a9 100644 --- a/kripton-processor/pom.xml +++ b/kripton-processor/pom.xml @@ -217,20 +217,6 @@
- - - - - - - - - - - - - - org.codehaus.mojo templating-maven-plugin diff --git a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/AbstractBindTransform.java b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/AbstractBindTransform.java index 9fc1d213d..2751fbe77 100644 --- a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/AbstractBindTransform.java +++ b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/AbstractBindTransform.java @@ -26,7 +26,7 @@ */ public abstract class AbstractBindTransform implements BindTransform { - /** The default value. */ + /** The default value. It can be modified, so do not change */ protected String DEFAULT_VALUE = "null"; /** The Constant PRE_TYPE_ADAPTER_TO_JAVA. */ diff --git a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/AbstractCollectionBindTransform.java b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/AbstractCollectionBindTransform.java index cbac26097..7965dceb4 100644 --- a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/AbstractCollectionBindTransform.java +++ b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/bind/transform/AbstractCollectionBindTransform.java @@ -55,6 +55,13 @@ */ public abstract class AbstractCollectionBindTransform extends AbstractBindTransform { + public static final String COLLECTION_ADD_ITEM = "collection.add(item)"; + public static final String COLLECTION_NEW = "$T<$T> collection=new $T<>()"; + public static final String ITEM_ASSIGN = "item=$L"; + public static final String ITEM_DEFINE = "$T item"; + public static final String INT_N_SIZE = "int n=$L.size()"; + public static final String FOR_INT_I_N = "for (int i=0; i collection=new $T<>()", ArrayList.class, elementTypeName.box(), + methodBuilder.addStatement(COLLECTION_NEW, ArrayList.class, elementTypeName.box(), ArrayList.class); } else { // it's for sure a parametrized type ParameterizedTypeName collectionTypeName = (ParameterizedTypeName) property.getPropertyType().getTypeName(); - methodBuilder.addStatement("$T<$T> collection=new $T<>()", defineCollectionClass(collectionTypeName), + methodBuilder.addStatement(COLLECTION_NEW, defineCollectionClass(collectionTypeName), elementTypeName.box(), defineCollectionClass(collectionTypeName)); } @@ -206,32 +211,14 @@ public void generateParseOnJacksonInternal(BindTypeContext context, Builder meth } else { methodBuilder.beginControlFlow("if ($L.currentToken()==$T.VALUE_NULL)", parserName, JsonToken.class); } - methodBuilder.addStatement("item=$L", DEFAULT_VALUE); + methodBuilder.addStatement(ITEM_ASSIGN, DEFAULT_VALUE); methodBuilder.nextControlFlow("else"); if (onString) { transform.generateParseOnJacksonAsString(context, methodBuilder, parserName, null, "item", elementProperty); } else { transform.generateParseOnJackson(context, methodBuilder, parserName, null, "item", elementProperty); } - methodBuilder.endControlFlow(); - methodBuilder.addStatement("collection.add(item)"); - methodBuilder.endControlFlow(); - - if (collectionType == CollectionType.ARRAY) { - if (TypeUtility.isTypePrimitive(elementTypeName)) { - methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.as$TTypeArray(collection)"), - CollectionUtils.class, elementTypeName.box()); - } else if (TypeUtility.isTypeWrappedPrimitive(elementTypeName)) { - methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.as$TArray(collection)"), - CollectionUtils.class, elementTypeName); - } else { - methodBuilder.addStatement( - setter(beanClass, beanName, property, "$T.asArray(collection, new $T[collection.size()])"), - CollectionUtils.class, elementTypeName); - } - } else { - methodBuilder.addStatement(setter(beanClass, beanName, property, "collection")); - } + define(methodBuilder, beanClass, beanName, property, elementTypeName); if (onString) { // ELSE: check if empty string (== empty collection but not null) @@ -240,13 +227,13 @@ public void generateParseOnJacksonInternal(BindTypeContext context, Builder meth JsonToken.class, StringUtils.class, parserName); // create collection if (collectionType == CollectionType.ARRAY) { - methodBuilder.addStatement("$T<$T> collection=new $T<>()", ArrayList.class, elementTypeName.box(), + methodBuilder.addStatement(COLLECTION_NEW, ArrayList.class, elementTypeName.box(), ArrayList.class); } else { // it's for sure a parametrized type ParameterizedTypeName collectionTypeName = (ParameterizedTypeName) property.getPropertyType() .getTypeName(); - methodBuilder.addStatement("$T<$T> collection=new $T<>()", defineCollectionClass(collectionTypeName), + methodBuilder.addStatement(COLLECTION_NEW, defineCollectionClass(collectionTypeName), elementTypeName.box(), defineCollectionClass(collectionTypeName)); } // set collection @@ -272,6 +259,28 @@ public void generateParseOnJacksonInternal(BindTypeContext context, Builder meth // @formatter:on } + private void define(Builder methodBuilder, TypeName beanClass, String beanName, BindProperty property, TypeName elementTypeName) { + methodBuilder.endControlFlow(); + methodBuilder.addStatement(COLLECTION_ADD_ITEM); + methodBuilder.endControlFlow(); + + if (collectionType == CollectionType.ARRAY) { + if (TypeUtility.isTypePrimitive(elementTypeName)) { + methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.as$TTypeArray(collection)"), + CollectionUtils.class, elementTypeName.box()); + } else if (TypeUtility.isTypeWrappedPrimitive(elementTypeName)) { + methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.as$TArray(collection)"), + CollectionUtils.class, elementTypeName); + } else { + methodBuilder.addStatement( + setter(beanClass, beanName, property, "$T.asArray(collection, new $T[collection.size()])"), + CollectionUtils.class, elementTypeName); + } + } else { + methodBuilder.addStatement(setter(beanClass, beanName, property, "collection")); + } + } + /** * Convert. * @@ -321,7 +330,7 @@ public void generateParseOnXml(BindTypeContext context, MethodSpec.Builder metho break; } - methodBuilder.addStatement("$T item", elementTypeName.box()); + methodBuilder.addStatement(ITEM_DEFINE, elementTypeName.box()); BindTransform transform = BindTransformer.lookup(elementTypeName); BindProperty elementProperty = BindProperty.builder(elementTypeName, property).inCollection(true).build(); @@ -333,17 +342,17 @@ public void generateParseOnXml(BindTypeContext context, MethodSpec.Builder metho } else { // no wrap element methodBuilder.addCode("// add first element\n"); - methodBuilder.addStatement("item=$L", DEFAULT_VALUE); + methodBuilder.addStatement(ITEM_ASSIGN, DEFAULT_VALUE); methodBuilder.beginControlFlow("if ($T.isEmptyTag($L))", XmlAttributeUtils.class, parserName); methodBuilder.addCode("// if there's a an empty collection it marked with attribute emptyCollection\n"); methodBuilder.beginControlFlow("if ($T.getAttributeAsBoolean($L, $S, false)==false)", XmlAttributeUtils.class, parserName, XmlAttributeUtils.EMPTY_COLLECTION_ATTRIBUTE_NAME); - methodBuilder.addStatement("collection.add(item)"); + methodBuilder.addStatement(COLLECTION_ADD_ITEM); methodBuilder.endControlFlow(); methodBuilder.addStatement("$L.nextTag()", parserName); methodBuilder.nextControlFlow("else"); transform.generateParseOnXml(context, methodBuilder, parserName, null, "item", elementProperty); - methodBuilder.addStatement("collection.add(item)"); + methodBuilder.addStatement(COLLECTION_ADD_ITEM); methodBuilder.endControlFlow(); methodBuilder.beginControlFlow("while ($L.nextTag() != $T.END_TAG && $L.getName().toString().equals($S))", @@ -352,31 +361,11 @@ public void generateParseOnXml(BindTypeContext context, MethodSpec.Builder metho // for all methodBuilder.beginControlFlow("if ($T.isEmptyTag($L))", XmlAttributeUtils.class, parserName); - methodBuilder.addStatement("item=$L", DEFAULT_VALUE); + methodBuilder.addStatement(ITEM_ASSIGN, DEFAULT_VALUE); methodBuilder.addStatement("$L.nextTag()", parserName); methodBuilder.nextControlFlow("else"); transform.generateParseOnXml(context, methodBuilder, parserName, null, "item", elementProperty); - methodBuilder.endControlFlow(); - methodBuilder.addStatement("collection.add(item)"); - - methodBuilder.endControlFlow(); - - //getter(beanName, beanClass, property); - if (collectionType == CollectionType.ARRAY) { - if (TypeUtility.isTypePrimitive(elementTypeName)) { - methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.as$TTypeArray(collection)"), - CollectionUtils.class, elementTypeName.box()); - } else if (TypeUtility.isTypeWrappedPrimitive(elementTypeName)) { - methodBuilder.addStatement(setter(beanClass, beanName, property, "$T.as$TArray(collection)"), - CollectionUtils.class, elementTypeName); - } else { - methodBuilder.addStatement( - setter(beanClass, beanName, property, "$T.asArray(collection, new $T[collection.size()])"), - CollectionUtils.class, elementTypeName); - } - } else { - methodBuilder.addStatement(setter(beanClass, beanName, property, "collection")); - } + define(methodBuilder, beanClass, beanName, property, elementTypeName); if (!property.xmlInfo.isWrappedCollection()) { methodBuilder.addStatement("read=false"); @@ -446,13 +435,13 @@ void generateSerializeOnJacksonInternal(BindTypeContext context, MethodSpec.Buil } if (collectionType == CollectionType.LIST) { - methodBuilder.addStatement("int n=$L.size()", getter(beanName, beanClass, property)); - methodBuilder.addStatement("$T item", elementTypeName); + methodBuilder.addStatement(INT_N_SIZE, getter(beanName, beanClass, property)); + methodBuilder.addStatement(ITEM_DEFINE, elementTypeName); } else if (collectionType == CollectionType.ARRAY) { methodBuilder.addStatement("int n=$L.length", getter(beanName, beanClass, property)); - methodBuilder.addStatement("$T item", elementTypeName); + methodBuilder.addStatement(ITEM_DEFINE, elementTypeName); } else if (onString) { - methodBuilder.addStatement("int n=$L.size()", getter(beanName, beanClass, property)); + methodBuilder.addStatement(INT_N_SIZE, getter(beanName, beanClass, property)); } BindTransform transform = BindTransformer.lookup(elementTypeName); @@ -472,10 +461,10 @@ void generateSerializeOnJacksonInternal(BindTypeContext context, MethodSpec.Buil if (collectionType == CollectionType.SET) { methodBuilder.beginControlFlow("for ($T item: $L)", elementTypeName, getter(beanName, beanClass, property)); } else if (collectionType == CollectionType.LIST) { - methodBuilder.beginControlFlow("for (int i=0; i formatter = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL); + Converter converter = CaseFormat.LOWER_CAMEL.converterTo(CaseFormat.UPPER_CAMEL); + buildWriterInternal(methodBuilder, editorName, beanClass, beanName, property, converter); + + } + + static void buildWriterInternal(Builder methodBuilder, String editorName, TypeName beanClass, String beanName, PrefsProperty property, Converter converter) { methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property)); - methodBuilder.addStatement("String temp=serialize$L($L)", formatter.convert(property.getName()), + methodBuilder.addStatement("String temp=serialize$L($L)", converter.convert(property.getName()), getter(beanName, beanClass, property)); methodBuilder.addStatement("$L.putString($S,temp)", editorName, property.getPreferenceKey()); methodBuilder.nextControlFlow(" else "); methodBuilder.addStatement("$L.remove($S)", editorName, property.getPreferenceKey()); methodBuilder.endControlFlow(); - } } diff --git a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/AbstractPrefsTransform.java b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/AbstractPrefsTransform.java index 714e3a132..2ef2f7e17 100644 --- a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/AbstractPrefsTransform.java +++ b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/AbstractPrefsTransform.java @@ -31,7 +31,7 @@ public abstract class AbstractPrefsTransform implements PrefsTransform { * * @param typeAdapterAware the type adapter aware */ - public AbstractPrefsTransform(boolean typeAdapterAware) { + protected AbstractPrefsTransform(boolean typeAdapterAware) { this.typeAdapterAware=typeAdapterAware; } diff --git a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/SetPrefsTransformation.java b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/SetPrefsTransformation.java index b8703afd7..0ebd572ac 100644 --- a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/SetPrefsTransformation.java +++ b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/SetPrefsTransformation.java @@ -169,14 +169,8 @@ public void generateWriteProperty(Builder methodBuilder, String editorName, Type boolean isStringSet = isStringSet(property); if (!isStringSet) { - methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property)); - methodBuilder.addStatement("String temp=serialize$L($L)", formatter.convert(property.getName()), - getter(beanName, beanClass, property)); - methodBuilder.addStatement("$L.putString($S,temp)", editorName, property.getPreferenceKey()); - methodBuilder.nextControlFlow(" else "); - methodBuilder.addStatement("$L.remove($S)", editorName, property.getPreferenceKey()); - methodBuilder.endControlFlow(); - } else { + AbstractGeneratedPrefsTransform.buildWriterInternal(methodBuilder, editorName, beanClass, beanName, property, formatter); + } else { methodBuilder.addStatement("$L.putStringSet($S," + tempPre + "$L" + tempPost + ")", editorName, property.getPreferenceKey(), getter(beanName, beanClass, property)); } diff --git a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/lang/AbstractPrimitivePrefsTransform.java b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/lang/AbstractPrimitivePrefsTransform.java index 9dfff3631..2366354ae 100644 --- a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/lang/AbstractPrimitivePrefsTransform.java +++ b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/lang/AbstractPrimitivePrefsTransform.java @@ -39,7 +39,7 @@ abstract class AbstractPrimitivePrefsTransform extends AbstractPrefsTransform { * @param nullable * the nullable */ - public AbstractPrimitivePrefsTransform(boolean nullable) { + protected AbstractPrimitivePrefsTransform(boolean nullable) { super(true); this.nullable = nullable; } @@ -52,7 +52,7 @@ public AbstractPrimitivePrefsTransform(boolean nullable) { * @param typeAware * the type aware */ - public AbstractPrimitivePrefsTransform(boolean nullable, boolean typeAware) { + protected AbstractPrimitivePrefsTransform(boolean nullable, boolean typeAware) { super(typeAware); this.nullable = nullable; } diff --git a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/math/AbstractNumberPrefsTransform.java b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/math/AbstractNumberPrefsTransform.java index 0ba6fa8dc..b51201ceb 100644 --- a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/math/AbstractNumberPrefsTransform.java +++ b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/math/AbstractNumberPrefsTransform.java @@ -44,7 +44,7 @@ abstract class AbstractNumberPrefsTransform extends AbstractPrefsTransform { /** * Instantiates a new abstract number prefs transform. */ - public AbstractNumberPrefsTransform() + protected AbstractNumberPrefsTransform() { super(false); defaultValue="0"; diff --git a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractBuilder.java b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractBuilder.java index a9f48473b..13529e838 100644 --- a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractBuilder.java +++ b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractBuilder.java @@ -45,7 +45,7 @@ public abstract class AbstractBuilder { * @param filer the filer * @param model the model */ - public AbstractBuilder(Elements elementUtils, Filer filer, SQLiteDatabaseSchema model) { + protected AbstractBuilder(Elements elementUtils, Filer filer, SQLiteDatabaseSchema model) { this.model=model; this.elementUtils = elementUtils; this.filer = filer; diff --git a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractSelectCodeGenerator.java b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractSelectCodeGenerator.java index 31ed4be19..4e0fff54d 100644 --- a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractSelectCodeGenerator.java +++ b/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/AbstractSelectCodeGenerator.java @@ -68,6 +68,7 @@ public abstract class AbstractSelectCodeGenerator implements SelectCodeGenerator /** The Constant LIVE_DATA_PREFIX. */ public static final String LIVE_DATA_PREFIX = "ForLiveData"; + public static final String PAGINATED_RESULT = "paginatedResult"; /** * The Enum JavadocPartType. @@ -245,7 +246,7 @@ public void generateLiveData(TypeSpec.Builder classBuilder, SQLiteModelMethod me methodBuilder.addJavadoc("

Live data

\n"); methodBuilder.addJavadoc("

This method open a connection internally.

\n\n"); - generateCommonPart(method, classBuilder, methodBuilder, fieldList, GenerationType.NO_CONTENT, method.liveDataReturnClass, true, false, "paginatedResult"); + generateCommonPart(method, classBuilder, methodBuilder, fieldList, GenerationType.NO_CONTENT, method.liveDataReturnClass, true, false, PAGINATED_RESULT); boolean pagedLiveData = method.isPagedLiveData(); @@ -280,7 +281,7 @@ public void generateLiveData(TypeSpec.Builder classBuilder, SQLiteModelMethod me .build(); // return - TypeSpec.Builder liveDataBuilderBuilder = TypeSpec.anonymousClassBuilder("paginatedResult").addSuperinterface(ParameterizedTypeName.get(handlerClass, method.getReturnClass())) + TypeSpec.Builder liveDataBuilderBuilder = TypeSpec.anonymousClassBuilder(PAGINATED_RESULT).addSuperinterface(ParameterizedTypeName.get(handlerClass, method.getReturnClass())) .addMethod(MethodSpec.methodBuilder("compute").addAnnotation(Override.class).addModifiers(Modifier.PROTECTED).returns(method.getReturnClass()) .addStatement("return $T.getInstance().executeBatch($L)", dataSourceClazz, batchBuilder).build()); TypeSpec liveDataBuilder = liveDataBuilderBuilder.build(); @@ -322,7 +323,7 @@ public void generateLiveData(TypeSpec.Builder classBuilder, SQLiteModelMethod me * the map fields */ public void generateCommonPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set fieldList, boolean generateSqlField) { - generateCommonPart(method, classBuilder, methodBuilder, fieldList, GenerationType.ALL, null, generateSqlField, false, "paginatedResult"); + generateCommonPart(method, classBuilder, methodBuilder, fieldList, GenerationType.ALL, null, generateSqlField, false, PAGINATED_RESULT); } /** @@ -345,8 +346,6 @@ public void generateCommonPart(SQLiteModelMethod method, TypeSpec.Builder classB SQLiteDaoDefinition daoDefinition = method.getParent(); SQLiteEntity entity = method.getEntity(); - // if true, field must be associate to ben attributes - // TypeName returnType = method.getReturnClass(); TypeName returnTypeName = forcedReturnType; if (returnTypeName == null) { returnTypeName = method.getReturnClass(); @@ -355,13 +354,13 @@ public void generateCommonPart(SQLiteModelMethod method, TypeSpec.Builder classB ModelAnnotation annotation = method.getAnnotation(BindSqlSelect.class); // parameters - List paramNames = new ArrayList(); - List paramGetters = new ArrayList(); - List paramTypeNames = new ArrayList(); + List paramNames = new ArrayList<>(); + List paramGetters = new ArrayList<>(); + List paramTypeNames = new ArrayList<>(); List usedBeanPropertyNames = new ArrayList<>(); // used method parameters - Set usedMethodParameters = new HashSet(); + Set usedMethodParameters = new HashSet<>(); final One whereJQL = new One<>(""); final One havingJQL = new One<>(""); @@ -399,41 +398,9 @@ public String onGroup(String statement) { SqlAnalyzer analyzer = new SqlAnalyzer(); - // String whereSQL = - // annotation.getAttribute(AnnotationAttributeType.WHERE); - analyzer.execute(BaseProcessor.elementUtils, method, whereJQL.value0); - paramGetters.addAll(analyzer.getParamGetters()); - paramNames.addAll(analyzer.getParamNames()); - paramTypeNames.addAll(analyzer.getParamTypeNames()); - usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames()); - usedMethodParameters.addAll(analyzer.getUsedMethodParameters()); - // String havingSQL = - // annotation.getAttribute(AnnotationAttributeType.HAVING); - analyzer.execute(BaseProcessor.elementUtils, method, havingJQL.value0); - paramGetters.addAll(analyzer.getParamGetters()); - paramNames.addAll(analyzer.getParamNames()); - paramTypeNames.addAll(analyzer.getParamTypeNames()); - usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames()); - usedMethodParameters.addAll(analyzer.getUsedMethodParameters()); - - // String groupBySQL = - // annotation.getAttribute(AnnotationAttributeType.GROUP_BY); - analyzer.execute(BaseProcessor.elementUtils, method, groupJQL.value0); - paramGetters.addAll(analyzer.getParamGetters()); - paramNames.addAll(analyzer.getParamNames()); - paramTypeNames.addAll(analyzer.getParamTypeNames()); - usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames()); - usedMethodParameters.addAll(analyzer.getUsedMethodParameters()); - - // String orderBySQL = - // annotation.getAttribute(AnnotationAttributeType.ORDER_BY); - analyzer.execute(BaseProcessor.elementUtils, method, orderJQL.value0); - paramGetters.addAll(analyzer.getParamGetters()); - paramNames.addAll(analyzer.getParamNames()); - paramTypeNames.addAll(analyzer.getParamTypeNames()); - usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames()); - usedMethodParameters.addAll(analyzer.getUsedMethodParameters()); + buildSelectInner(method, paramNames, paramGetters, paramTypeNames, usedBeanPropertyNames, usedMethodParameters, whereJQL, havingJQL, analyzer); + buildSelectInner(method, paramNames, paramGetters, paramTypeNames, usedBeanPropertyNames, usedMethodParameters, groupJQL, orderJQL, analyzer); // add as used parameter dynamic components too if (method.hasDynamicWhereConditions()) { @@ -498,9 +465,6 @@ public String onGroup(String statement) { classBuilder.addField(FieldSpec.builder(String.class, sqlName, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL).initializer("$S", sql) .addJavadoc("SQL definition for method $L\n", method.getName()).build()); } else if (generateSqlField) { - // sqlName = - // CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, - // method.buildSQLName()); String sql = SqlSelectBuilder.convertJQL2SQL(method, true); // add static sql definition @@ -522,7 +486,7 @@ public String onGroup(String statement) { { String separator = ""; TypeName paramTypeName; - // String paramName; + boolean nullable; int i = 0; boolean rawParameters; @@ -531,10 +495,10 @@ public String onGroup(String statement) { beanName = method.findEntityProperty(); for (String methodParam : paramGetters) { - rawParameters = paramNames.get(i).indexOf(".") == -1; + rawParameters = !paramNames.get(i).contains("."); if (method.jql.spreadParams.contains(method.findParameterAliasByName(methodParam))) { - // paramTypeName = paramTypeNames.get(i); + String sizeMethod = ""; String elementMethod = ""; TypeName paramCollTypeName = paramTypeNames.get(i); @@ -574,24 +538,20 @@ public String onGroup(String statement) { // eventually we take associated property SQLProperty property = usedBeanPropertyNames.get(i) == null ? null : entity.get(usedBeanPropertyNames.get(i)); - if (nullable && !(property != null) && !method.hasAdapterForParam(methodParam)) { + if (nullable && property == null && !method.hasAdapterForParam(methodParam)) { methodBuilder.addCode("($L==null?\"\":", methodParam); } // check for string conversion TypeUtility.beginStringConversion(methodBuilder, paramTypeName); - // if (property != null) { - // SQLTransformer.javaProperty2WhereCondition(methodBuilder, - // method, item, paramTypeName, property); - // } else { SQLTransformer.javaProperty2WhereCondition(methodBuilder, method, beanName, paramTypeName, property); - // } + // check for string conversion TypeUtility.endStringConversion(methodBuilder, paramTypeName); - if (nullable && !(property != null) && !method.hasAdapterForParam(methodParam)) { + if (nullable && (property == null) && !method.hasAdapterForParam(methodParam)) { methodBuilder.addCode(")"); } } @@ -662,6 +622,22 @@ public String onGroup(String statement) { } + private static void buildSelectInner(SQLiteModelMethod method, List paramNames, List paramGetters, List paramTypeNames, List usedBeanPropertyNames, Set usedMethodParameters, One whereJQL, One havingJQL, SqlAnalyzer analyzer) { + analyzer.execute(BaseProcessor.elementUtils, method, whereJQL.value0); + paramGetters.addAll(analyzer.getParamGetters()); + paramNames.addAll(analyzer.getParamNames()); + paramTypeNames.addAll(analyzer.getParamTypeNames()); + usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames()); + usedMethodParameters.addAll(analyzer.getUsedMethodParameters()); + + analyzer.execute(BaseProcessor.elementUtils, method, havingJQL.value0); + paramGetters.addAll(analyzer.getParamGetters()); + paramNames.addAll(analyzer.getParamNames()); + paramTypeNames.addAll(analyzer.getParamTypeNames()); + usedBeanPropertyNames.addAll(analyzer.getUsedBeanPropertyNames()); + usedMethodParameters.addAll(analyzer.getUsedMethodParameters()); + } + private void generateRawWhereArg(SQLiteModelMethod method, MethodSpec.Builder methodBuilder, TypeName paramTypeName, boolean nullable, String item) { generateRawWhereArg(method, methodBuilder, paramTypeName, nullable, item, item); } diff --git a/kripton-processor/src/test/java/bind/AbstractBindTypeProcessorTest.java b/kripton-processor/src/test/java/bind/AbstractBindTypeProcessorTest.java index c78c9ee09..fe8f23aeb 100644 --- a/kripton-processor/src/test/java/bind/AbstractBindTypeProcessorTest.java +++ b/kripton-processor/src/test/java/bind/AbstractBindTypeProcessorTest.java @@ -41,7 +41,7 @@ /** * The Class AbstractBindTypeProcessorTest. */ -public class AbstractBindTypeProcessorTest extends BaseProcessorTest { +public abstract class AbstractBindTypeProcessorTest extends BaseProcessorTest { /** * Setup. @@ -162,7 +162,7 @@ public int serializeAndParse(Object bean, BinderType type) throws Exception { String output2 = KriptonBinder.bind(type).serialize(bean2); System.out.println(output2); - Assert.assertTrue(type.toString(), output1.length() == output2.length()); + Assert.assertEquals(type.toString(),output1.length(), output2.length()); ReflectionAssert.assertReflectionEquals(bean, bean2, ReflectionComparatorMode.LENIENT_ORDER); @@ -188,7 +188,7 @@ public int serializeAndParseCollection(Collection list, Class clazz, B System.out.println(value1); System.out.println(value2); // - Assert.assertTrue(value1.length() == value2.length()); + Assert.assertEquals(type.toString(),value1.length(), value2.length()); ReflectionAssert.assertReflectionEquals(type.toString(), list, list2, ReflectionComparatorMode.LENIENT_ORDER); // return value1.length(); @@ -218,7 +218,7 @@ public int serializeAndParseCollectionBinary(Collection list, Class cl System.out.println(value1); System.out.println(value2); - Assert.assertTrue(value1.length() == value2.length()); + Assert.assertEquals(type.toString(),value1.length(), value2.length()); ReflectionAssert.assertReflectionEquals(type.toString(), list, list2, ReflectionComparatorMode.LENIENT_ORDER); // return bar.getCount(); @@ -245,9 +245,7 @@ public int serializeAndParseBinary(Object bean, BinderType type) throws Exceptio String value2 = toString(bar2.getByteBuffer()); System.out.println(value2); - Assert.assertTrue(value1.length() == value2.length()); - // ReflectionAssert.assertReflectionEquals(type.toString(), bean, - // bean2); + Assert.assertEquals(type.toString(),value1.length(), value2.length()); return bar.getCount(); } diff --git a/kripton-processor/src/test/java/sqlite/AbstractBindSQLiteProcessorTest.java b/kripton-processor/src/test/java/sqlite/AbstractBindSQLiteProcessorTest.java index 9e68c6685..d624e0aec 100644 --- a/kripton-processor/src/test/java/sqlite/AbstractBindSQLiteProcessorTest.java +++ b/kripton-processor/src/test/java/sqlite/AbstractBindSQLiteProcessorTest.java @@ -25,7 +25,7 @@ /** * The Class AbstractBindSQLiteProcessorTest. */ -public class AbstractBindSQLiteProcessorTest extends BaseProcessorTest { +public abstract class AbstractBindSQLiteProcessorTest extends BaseProcessorTest { /** * Setup. diff --git a/kripton-retrofit-converter/src/test/java/com/abubusoft/kripton/retrofit2/AbstractBaseTest.java b/kripton-retrofit-converter/src/test/java/com/abubusoft/kripton/retrofit2/AbstractBaseTest.java index abd7c5ec1..7ecdfa48c 100644 --- a/kripton-retrofit-converter/src/test/java/com/abubusoft/kripton/retrofit2/AbstractBaseTest.java +++ b/kripton-retrofit-converter/src/test/java/com/abubusoft/kripton/retrofit2/AbstractBaseTest.java @@ -1,12 +1,12 @@ /******************************************************************************* * Copyright 2016-2019 Francesco Benincasa (info@abubusoft.com) - * + * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the @@ -38,265 +38,269 @@ /** * The Class AbstractBaseTest. */ -public class AbstractBaseTest { - - /** The Constant KRIPTON_DEBUG_MODE. */ - private static final String KRIPTON_DEBUG_MODE = "kripton.debug"; - - /** The expected ex. */ - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - /** - * Check. - * - * @param bean the bean - * @param checks the checks - * @throws Exception the exception - */ - protected void check(Object bean, BinderType... checks) throws Exception { - int max = 0; - int[] values = new int[BinderType.values().length]; - - boolean all = false; - List checkList = Arrays.asList(checks); - if (checks.length == 0) - all = true; - - int i = 0; - for (BinderType checkType : BinderType.values()) { - if (all || checkList.contains(checkType)) { - if (checkType == BinderType.CBOR) { - values[i] = serializeAndParseBinary(bean, checkType); - } else { - values[i] = serializeAndParse(bean, checkType); - } - max = Math.max(max, values[i]); - i++; - } - } - - i = 0; - for (BinderType checkType : BinderType.values()) { - if (all || checkList.contains(checkType)) { - System.out.print(String.format("%s: %s bytes (%.0f%%) ", checkType.toString(), values[i], values[i] * 100.0 / max)); - i++; - } - } - - System.out.println(); - } - - /** - * Check collection. - * - * @param the element type - * @param collection the collection - * @param beanClazz the bean clazz - * @param checks the checks - * @throws Exception the exception - */ - protected void checkCollection(Collection collection, Class beanClazz, BinderType... checks) throws Exception { - int max = 0; - int[] values = new int[BinderType.values().length]; - - boolean all = false; - List checkList = Arrays.asList(checks); - if (checks.length == 0) - all = true; - - int i = 0; - for (BinderType checkType : BinderType.values()) { - if (all || checkList.contains(checkType)) { - if (checkType == BinderType.CBOR) { - values[i] = serializeAndParseCollectionBinary(collection, beanClazz, checkType); - } else { - values[i] = serializeAndParseCollection(collection, beanClazz, checkType); - } - max = Math.max(max, values[i]); - i++; - } - } - - i = 0; - for (BinderType checkType : BinderType.values()) { - if (all || checkList.contains(checkType)) { - System.out.print(String.format("%s: %s bytes (%.0f%%) ", checkType.toString(), values[i], values[i] * 100.0 / max)); - i++; - } - } - - System.out.println(); - } - - /** - * Expected exception. - * - * @param the element type - * @param clazzException the clazz exception - * @throws InstantiationException the instantiation exception - * @throws IllegalAccessException the illegal access exception - */ - public void expectedException(Class clazzException) throws InstantiationException, IllegalAccessException { - expectedEx.expect(AssertionError.class); - expectedEx.expectMessage(clazzException.getSimpleName()); - } - - /** - * Serialize and parse. - * - * @param bean the bean - * @param type the type - * @return the int - * @throws Exception the exception - */ - public int serializeAndParse(Object bean, BinderType type) throws Exception { - String output1 = KriptonBinder.bind(type).serialize(bean); - System.out.println("[[" + output1 + "]]"); - - Object bean2 = KriptonBinder.bind(type).parse(output1, bean.getClass()); - - String output2 = KriptonBinder.bind(type).serialize(bean2); - if (output1.equals(output2)) { - System.out.println("[[-- same --]]"); - } else { - System.out.println("[[" + output2 + "]]"); - } - - Assert.assertTrue(type.toString(), output1.length() == output2.length()); - - ReflectionAssert.assertReflectionEquals(bean, bean2, ReflectionComparatorMode.LENIENT_ORDER); - - return output2.length(); - } - - /** - * Serialize and parse binary. - * - * @param bean the bean - * @param type the type - * @return the int - * @throws Exception the exception - */ - public int serializeAndParseBinary(Object bean, BinderType type) throws Exception { - KriptonByteArrayOutputStream bar = new KriptonByteArrayOutputStream(); - KriptonBinder.bind(type).serialize(bean, bar); - String value1 = toString(bar.getByteBufferCopy()); - - System.out.println("[[" + value1 + "]]"); - - Object bean2 = KriptonBinder.bind(type).parse(new ByteArrayInputStream(bar.getByteBuffer()), bean.getClass()); - - KriptonByteArrayOutputStream bar2 = new KriptonByteArrayOutputStream(); - KriptonBinder.bind(type).serialize(bean2, bar2); - String value2 = toString(bar2.getByteBufferCopy()); - - if (value1.equals(value2)) { - System.out.println("[[-- same --]]"); - } else { - System.out.println("[[" + value2 + "]]"); - } - - Assert.assertTrue(value1.length() == value2.length()); - - return bar.getCount(); - } - - /** - * Serialize and parse collection. - * - * @param the element type - * @param list the list - * @param clazz the clazz - * @param type the type - * @return the int - * @throws Exception the exception - */ - public int serializeAndParseCollection(Collection list, Class clazz, BinderType type) throws Exception { - String value1 = KriptonBinder.bind(type).serializeCollection(list, clazz); - - System.out.println("[[" + value1 + "]]"); - - Collection list2 = KriptonBinder.bind(type).parseCollection(value1, new ArrayList(), clazz); - - String value2 = KriptonBinder.bind(type).serializeCollection(list2, clazz); - - if (value1.equals(value2)) { - System.out.println("[[-- same --]]"); - } else { - System.out.println("[[" + value2 + "]]"); - } - // - Assert.assertTrue(value1.length() == value2.length()); - ReflectionAssert.assertReflectionEquals(type.toString(), list, list2, ReflectionComparatorMode.LENIENT_ORDER); - // - return value1.length(); - } - - /** - * Serialize and parse collection binary. - * - * @param the element type - * @param list the list - * @param clazz the clazz - * @param type the type - * @return the int - * @throws Exception the exception - */ - public int serializeAndParseCollectionBinary(Collection list, Class clazz, BinderType type) throws Exception { - KriptonByteArrayOutputStream bar = new KriptonByteArrayOutputStream(); - KriptonBinder.bind(type).serializeCollection(list, clazz, bar); - String value1 = toString(bar.getByteBuffer()); - - System.out.println("[[" + value1 + "]]"); - - Collection list2 = KriptonBinder.bind(type).parseCollection(bar.getByteBufferCopy(), new ArrayList(), clazz); - - KriptonByteArrayOutputStream bar2 = new KriptonByteArrayOutputStream(); - KriptonBinder.bind(type).serializeCollection(list2, clazz, bar2); - String value2 = toString(bar2.getByteBuffer()); - - if (value1.equals(value2)) { - System.out.println("[[-- same --]]"); - } else { - System.out.println("[[" + value2 + "]]"); - } - - Assert.assertTrue(value1.length() == value2.length()); - ReflectionAssert.assertReflectionEquals(type.toString(), list, list2, ReflectionComparatorMode.LENIENT_ORDER); - // - return bar.getCount(); - } - - /** - * Setup. - */ - @Before - public void setup() { - final String value = System.getProperty(KRIPTON_DEBUG_MODE); - if ("false".equals(value)) { - // we are in test, but we don't see log on System.out - System.setOut(new PrintStream(new NullOutputStream())); - System.setErr(new PrintStream(new NullOutputStream())); - } - - // when we run junit test, AnnotationProcessor is always in TEST_MODE - System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] (%2$s) %5$s %6$s%n"); - - // KriptonBinder.registryBinder(new KriptonCborContext()); - } - - /** - * To string. - * - * @param input the input - * @return the string - */ - String toString(byte[] input) { - StringBuilder buffer = new StringBuilder(); - for (int j = 0; j < input.length; j++) { - buffer.append(String.format("%02X", input[j])); - } - return buffer.toString(); - } +public abstract class AbstractBaseTest { + + /** + * The Constant KRIPTON_DEBUG_MODE. + */ + private static final String KRIPTON_DEBUG_MODE = "kripton.debug"; + + /** + * The expected ex. + */ + @Rule + public ExpectedException expectedEx = ExpectedException.none(); + + /** + * Check. + * + * @param bean the bean + * @param checks the checks + * @throws Exception the exception + */ + protected void check(Object bean, BinderType... checks) throws Exception { + int max = 0; + int[] values = new int[BinderType.values().length]; + + boolean all = false; + List checkList = Arrays.asList(checks); + if (checks.length == 0) + all = true; + + int i = 0; + for (BinderType checkType : BinderType.values()) { + if (all || checkList.contains(checkType)) { + if (checkType == BinderType.CBOR) { + values[i] = serializeAndParseBinary(bean, checkType); + } else { + values[i] = serializeAndParse(bean, checkType); + } + max = Math.max(max, values[i]); + i++; + } + } + + i = 0; + for (BinderType checkType : BinderType.values()) { + if (all || checkList.contains(checkType)) { + System.out.print(String.format("%s: %s bytes (%.0f%%) ", checkType.toString(), values[i], values[i] * 100.0 / max)); + i++; + } + } + + System.out.println(); + } + + /** + * Check collection. + * + * @param the element type + * @param collection the collection + * @param beanClazz the bean clazz + * @param checks the checks + * @throws Exception the exception + */ + protected void checkCollection(Collection collection, Class beanClazz, BinderType... checks) throws Exception { + int max = 0; + int[] values = new int[BinderType.values().length]; + + boolean all = false; + List checkList = Arrays.asList(checks); + if (checks.length == 0) + all = true; + + int i = 0; + for (BinderType checkType : BinderType.values()) { + if (all || checkList.contains(checkType)) { + if (checkType == BinderType.CBOR) { + values[i] = serializeAndParseCollectionBinary(collection, beanClazz, checkType); + } else { + values[i] = serializeAndParseCollection(collection, beanClazz, checkType); + } + max = Math.max(max, values[i]); + i++; + } + } + + i = 0; + for (BinderType checkType : BinderType.values()) { + if (all || checkList.contains(checkType)) { + System.out.print(String.format("%s: %s bytes (%.0f%%) ", checkType.toString(), values[i], values[i] * 100.0 / max)); + i++; + } + } + + System.out.println(); + } + + /** + * Expected exception. + * + * @param the element type + * @param clazzException the clazz exception + * @throws InstantiationException the instantiation exception + * @throws IllegalAccessException the illegal access exception + */ + public void expectedException(Class clazzException) throws InstantiationException, IllegalAccessException { + expectedEx.expect(AssertionError.class); + expectedEx.expectMessage(clazzException.getSimpleName()); + } + + /** + * Serialize and parse. + * + * @param bean the bean + * @param type the type + * @return the int + * @throws Exception the exception + */ + public int serializeAndParse(Object bean, BinderType type) throws Exception { + String output1 = KriptonBinder.bind(type).serialize(bean); + System.out.println("[[" + output1 + "]]"); + + Object bean2 = KriptonBinder.bind(type).parse(output1, bean.getClass()); + + String output2 = KriptonBinder.bind(type).serialize(bean2); + if (output1.equals(output2)) { + System.out.println("[[-- same --]]"); + } else { + System.out.println("[[" + output2 + "]]"); + } + + Assert.assertEquals(type.toString(), output1.length(), output2.length()); + + ReflectionAssert.assertReflectionEquals(bean, bean2, ReflectionComparatorMode.LENIENT_ORDER); + + return output2.length(); + } + + /** + * Serialize and parse binary. + * + * @param bean the bean + * @param type the type + * @return the int + * @throws Exception the exception + */ + public int serializeAndParseBinary(Object bean, BinderType type) throws Exception { + KriptonByteArrayOutputStream bar = new KriptonByteArrayOutputStream(); + KriptonBinder.bind(type).serialize(bean, bar); + String value1 = toString(bar.getByteBufferCopy()); + + System.out.println("[[" + value1 + "]]"); + + Object bean2 = KriptonBinder.bind(type).parse(new ByteArrayInputStream(bar.getByteBuffer()), bean.getClass()); + + KriptonByteArrayOutputStream bar2 = new KriptonByteArrayOutputStream(); + KriptonBinder.bind(type).serialize(bean2, bar2); + String value2 = toString(bar2.getByteBufferCopy()); + + if (value1.equals(value2)) { + System.out.println("[[-- same --]]"); + } else { + System.out.println("[[" + value2 + "]]"); + } + + Assert.assertEquals(value1.length(), value2.length()); + + return bar.getCount(); + } + + /** + * Serialize and parse collection. + * + * @param the element type + * @param list the list + * @param clazz the clazz + * @param type the type + * @return the int + * @throws Exception the exception + */ + public int serializeAndParseCollection(Collection list, Class clazz, BinderType type) throws Exception { + String value1 = KriptonBinder.bind(type).serializeCollection(list, clazz); + + System.out.println("[[" + value1 + "]]"); + + Collection list2 = KriptonBinder.bind(type).parseCollection(value1, new ArrayList(), clazz); + + String value2 = KriptonBinder.bind(type).serializeCollection(list2, clazz); + + if (value1.equals(value2)) { + System.out.println("[[-- same --]]"); + } else { + System.out.println("[[" + value2 + "]]"); + } + // + Assert.assertEquals(value1.length(), value2.length()); + ReflectionAssert.assertReflectionEquals(type.toString(), list, list2, ReflectionComparatorMode.LENIENT_ORDER); + // + return value1.length(); + } + + /** + * Serialize and parse collection binary. + * + * @param the element type + * @param list the list + * @param clazz the clazz + * @param type the type + * @return the int + * @throws Exception the exception + */ + public int serializeAndParseCollectionBinary(Collection list, Class clazz, BinderType type) throws Exception { + KriptonByteArrayOutputStream bar = new KriptonByteArrayOutputStream(); + KriptonBinder.bind(type).serializeCollection(list, clazz, bar); + String value1 = toString(bar.getByteBuffer()); + + System.out.println("[[" + value1 + "]]"); + + Collection list2 = KriptonBinder.bind(type).parseCollection(bar.getByteBufferCopy(), new ArrayList(), clazz); + + KriptonByteArrayOutputStream bar2 = new KriptonByteArrayOutputStream(); + KriptonBinder.bind(type).serializeCollection(list2, clazz, bar2); + String value2 = toString(bar2.getByteBuffer()); + + if (value1.equals(value2)) { + System.out.println("[[-- same --]]"); + } else { + System.out.println("[[" + value2 + "]]"); + } + + Assert.assertEquals(value1.length(), value2.length()); + ReflectionAssert.assertReflectionEquals(type.toString(), list, list2, ReflectionComparatorMode.LENIENT_ORDER); + // + return bar.getCount(); + } + + /** + * Setup. + */ + @Before + public void setup() { + final String value = System.getProperty(KRIPTON_DEBUG_MODE); + if ("false".equals(value)) { + // we are in test, but we don't see log on System.out + System.setOut(new PrintStream(new NullOutputStream())); + System.setErr(new PrintStream(new NullOutputStream())); + } + + // when we run junit test, AnnotationProcessor is always in TEST_MODE + System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tH:%1$tM:%1$tS.%1$tL %4$-7s [%3$s] (%2$s) %5$s %6$s%n"); + + // KriptonBinder.registryBinder(new KriptonCborContext()); + } + + /** + * To string. + * + * @param input the input + * @return the string + */ + String toString(byte[] input) { + StringBuilder buffer = new StringBuilder(); + for (int j = 0; j < input.length; j++) { + buffer.append(String.format("%02X", input[j])); + } + return buffer.toString(); + } } diff --git a/kripton-shared-preferences/kripton-shared-preferences.iml b/kripton-shared-preferences/kripton-shared-preferences.iml deleted file mode 100644 index dbf25cacc..000000000 --- a/kripton-shared-preferences/kripton-shared-preferences.iml +++ /dev/null @@ -1,79 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/kripton-shared-preferences/src/main/java/com/abubusoft/kripton/android/annotation/BindPreference.java b/kripton-shared-preferences/src/main/java/com/abubusoft/kripton/android/annotation/BindPreference.java index 21e14a04f..72e2483ed 100644 --- a/kripton-shared-preferences/src/main/java/com/abubusoft/kripton/android/annotation/BindPreference.java +++ b/kripton-shared-preferences/src/main/java/com/abubusoft/kripton/android/annotation/BindPreference.java @@ -41,7 +41,7 @@ * * protected String[] stringArray; * - * public List stringList; + * public List<String> stringList; * * public String[] getStringArray() { * return stringArray; @@ -73,7 +73,7 @@ * *
  * BindAppPreferences sp = BindAppPreferences.getInstance();
- * sp.getDescriptionAsLiveData().observeForever(new Observer() {
+ * sp.getDescriptionAsLiveData().observeForever(new Observer<String>() {
  * 
  * 	@Override
  * 	public void onChanged(String t) {
diff --git a/kripton-shared-preferences/src/main/java/com/abubusoft/kripton/android/annotation/BindPreferenceAdapter.java b/kripton-shared-preferences/src/main/java/com/abubusoft/kripton/android/annotation/BindPreferenceAdapter.java
index 29bafeeb9..10a57a1ac 100644
--- a/kripton-shared-preferences/src/main/java/com/abubusoft/kripton/android/annotation/BindPreferenceAdapter.java
+++ b/kripton-shared-preferences/src/main/java/com/abubusoft/kripton/android/annotation/BindPreferenceAdapter.java
@@ -44,7 +44,7 @@
  * public class App1Preferences {
  * 
  * 	@BindPreference
- * 	public HashSet valueSet;
+ * 	public HashSet<String> valueSet;
  * 
  * 	@BindPreferenceAdapter(adapter = IntTypeAdapter.class)
  * 	@BindPreference
@@ -56,7 +56,7 @@
  * 

* *
-public class IntTypeAdapter implements PreferenceTypeAdapter {
+public class IntTypeAdapter implements PreferenceTypeAdapte<> M getMapper(Class cls) {
       String mapperClassName = cls.getName() + KriptonBinder.MAPPER_CLASS_SUFFIX;
       try {
         Class mapperClass = (Class) Class.forName(mapperClassName);
-        mapper = (M) mapperClass.newInstance();
+        mapper = (M) mapperClass.getDeclaredConstructor().newInstance();
         // mapper.
         OBJECT_MAPPERS.put(cls, mapper);
         
@@ -78,7 +79,7 @@ static > M getMapper(Class cls) {
       } catch (ClassNotFoundException e) {
         e.printStackTrace();
         throw new KriptonRuntimeException(String.format("Class '%s' does not exist. Does '%s' have @BindType annotation?", mapperClassName, beanClassName));
-      } catch (InstantiationException | IllegalAccessException e) {
+      } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
         e.printStackTrace();
       }
     }
@@ -118,15 +119,14 @@ public boolean canPersist(Class cls) {
       String beanClassName = cls.getName();
       String mapperClassName = cls.getName() + KriptonBinder.MAPPER_CLASS_SUFFIX;
       try {
-        Class mapperClass = (Class) Class.forName(mapperClassName);
-        mapper = mapperClass.newInstance();
-        // mapper.
+        Class mapperClass = Class.forName(mapperClassName);
+        mapperClass.getDeclaredConstructor().newInstance();
 
         return true;
       } catch (ClassNotFoundException e) {
         e.printStackTrace();
         throw new KriptonRuntimeException(String.format("Class '%s' does not exist. Does '%s' have @BindType annotation?", mapperClassName, beanClassName));
-      } catch (InstantiationException | IllegalAccessException e) {
+      } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
         e.printStackTrace();
       }
     }
diff --git a/kripton/src/main/java/com/abubusoft/kripton/AbstractJacksonContext.java b/kripton/src/main/java/com/abubusoft/kripton/AbstractJacksonContext.java
index fe1a27df5..4fe1a0e39 100644
--- a/kripton/src/main/java/com/abubusoft/kripton/AbstractJacksonContext.java
+++ b/kripton/src/main/java/com/abubusoft/kripton/AbstractJacksonContext.java
@@ -37,12 +37,12 @@
 public abstract class AbstractJacksonContext extends AbstractContext {
 
 	/** inner factory. */
-	public JsonFactory innerFactory;
+	protected JsonFactory innerFactory;
 
 	/**
 	 * constructor.
 	 */
-	public AbstractJacksonContext() {
+	protected AbstractJacksonContext() {
 		innerFactory = createInnerFactory();
 	}
 
diff --git a/kripton/src/main/java/com/abubusoft/kripton/AbstractMapper.java b/kripton/src/main/java/com/abubusoft/kripton/AbstractMapper.java
index e5bce2e09..29d4ac6d8 100644
--- a/kripton/src/main/java/com/abubusoft/kripton/AbstractMapper.java
+++ b/kripton/src/main/java/com/abubusoft/kripton/AbstractMapper.java
@@ -1,12 +1,12 @@
 /*******************************************************************************
  * Copyright 2016-2019 Francesco Benincasa (info@abubusoft.com)
- * 
+ *
  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  * use this file except in compliance with the License.  You may obtain a copy
  * of the License at
- * 
+ *
  *   http://www.apache.org/licenses/LICENSE-2.0
- * 
+ *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
@@ -35,149 +35,141 @@
 /**
  * The Class AbstractMapper.
  *
- * @author Francesco Benincasa (info@abubusoft.com)
  * @param  the element type
+ * @author Francesco Benincasa (info@abubusoft.com)
  */
 public abstract class AbstractMapper implements BinderMapper {
 
-	/* (non-Javadoc)
-	 * @see com.abubusoft.kripton.BinderMapper#parse(com.abubusoft.kripton.BinderContext, com.abubusoft.kripton.persistence.ParserWrapper)
-	 */
-	@Override
-	public E parse(BinderContext context, ParserWrapper parserWrapper) throws Exception {
-		E instance = null;
-
-		switch (context.getSupportedFormat()) {
-		case XML:
-			instance = parseOnXml(((XmlWrapperParser) parserWrapper).xmlParser, EventType.START_DOCUMENT);
-			break;
-		default:
-			if (context.getSupportedFormat().onlyText)
-				instance = parseOnJacksonAsString(((JacksonWrapperParser) parserWrapper).jacksonParser);
-			else
-				instance = parseOnJackson(((JacksonWrapperParser) parserWrapper).jacksonParser);
-
-			break;
-		}
-
-		return instance;
-	}
-
-	/* (non-Javadoc)
-	 * @see com.abubusoft.kripton.BinderMapper#parseCollection(com.abubusoft.kripton.BinderContext, com.abubusoft.kripton.persistence.ParserWrapper, java.util.Collection)
-	 */
-	@Override
-	public > L parseCollection(BinderContext context, ParserWrapper parserWrapper, L collection)  throws Exception {
-		switch (context.getSupportedFormat()) {
-		case XML: {
-			throw (new KriptonRuntimeException(context.getSupportedFormat() + " context does not support direct collection persistance"));
-		}
-		default: {
-			JacksonWrapperParser wrapperParser = (JacksonWrapperParser) parserWrapper;
-			JsonParser parser = wrapperParser.jacksonParser;
-
-			try {
-				collection.clear();
-
-				if (parser.nextToken() != JsonToken.START_ARRAY) {
-					throw (new KriptonRuntimeException("Invalid input format"));
-				}
-				if (context.getSupportedFormat().onlyText) {
-					while (parser.nextToken() != JsonToken.END_ARRAY) {
-						collection.add(parseOnJacksonAsString(parser));
-					}
-				} else {
-					while (parser.nextToken() != JsonToken.END_ARRAY) {
-						collection.add(parseOnJackson(parser));
-					}
-				}
-				return collection;
-			} catch (IOException e) {
-				e.printStackTrace();
-				throw (new KriptonRuntimeException(e));
-			}
-		}
-		}
-	}
-
-	/**
-	 * Serialize an object using the contxt and the serializerWrapper.
-	 *
-	 * @param context the context
-	 * @param object the object
-	 * @param serializerWrapper the serializer wrapper
-	 * @param writeStartAndEnd the write start and end
-	 * @throws Exception the exception
-	 */
-	protected void serialize(BinderContext context, E object, SerializerWrapper serializerWrapper, boolean writeStartAndEnd) throws Exception {
-
-		switch (context.getSupportedFormat()) {
-		case XML:
-			try {
-				XmlWrapperSerializer wrapper = ((XmlWrapperSerializer) serializerWrapper);
-				XMLSerializer xmlSerializer=wrapper.xmlSerializer;
-
-				if (writeStartAndEnd) {
-					xmlSerializer.writeStartDocument();
-				}
-				serializeOnXml(object, xmlSerializer, EventType.START_DOCUMENT);
-
-				if (writeStartAndEnd) {
-					xmlSerializer.writeEndDocument();
-				}
-			} catch (Exception e) {
-				e.printStackTrace();
-				throw (new KriptonRuntimeException(e));
-			}
-			break;
-		default:
-			if (context.getSupportedFormat().onlyText)
-				serializeOnJacksonAsString(object, ((JacksonWrapperSerializer) serializerWrapper).jacksonGenerator);
-			else
-				serializeOnJackson(object, ((JacksonWrapperSerializer) serializerWrapper).jacksonGenerator);
-			break;
-		}
-	}
-
-	/* (non-Javadoc)
-	 * @see com.abubusoft.kripton.BinderMapper#serialize(com.abubusoft.kripton.BinderContext, com.abubusoft.kripton.persistence.SerializerWrapper, java.lang.Object)
-	 */
-	@Override
-	public void serialize(BinderContext context, SerializerWrapper serializerWrapper, E object) throws Exception {
-		serialize(context, object, serializerWrapper, true);
-	}
-
-	/* (non-Javadoc)
-	 * @see com.abubusoft.kripton.BinderMapper#serializeCollection(com.abubusoft.kripton.BinderContext, com.abubusoft.kripton.persistence.SerializerWrapper, java.util.Collection)
-	 */
-	@Override
-	public void serializeCollection(BinderContext context, SerializerWrapper serializerWrapper, Collection collection) throws Exception {
-		switch (context.getSupportedFormat()) {
-		case XML: {
-			throw (new KriptonRuntimeException(context.getSupportedFormat() + " context does not support direct collection persistance"));
-		}
-		default: {
-			JacksonWrapperSerializer wrapper = (JacksonWrapperSerializer) serializerWrapper;
-			JsonGenerator jacksonGenerator=wrapper.jacksonGenerator;
-
-			try {
-				jacksonGenerator.writeStartArray();
-				if (context.getSupportedFormat().onlyText)
-					for (E object : collection) {
-						serializeOnJacksonAsString(object, jacksonGenerator);
-					}
-				else
-					for (E object : collection) {
-						serializeOnJackson(object, jacksonGenerator);
-					}
-				jacksonGenerator.writeEndArray();
-			} catch (IOException e) {
-				e.printStackTrace();
-				throw (new KriptonRuntimeException(e));
-			}
-		}
-			break;
-		}
-	}
-	
+    /* (non-Javadoc)
+     * @see com.abubusoft.kripton.BinderMapper#parse(com.abubusoft.kripton.BinderContext, com.abubusoft.kripton.persistence.ParserWrapper)
+     */
+    @Override
+    public E parse(BinderContext context, ParserWrapper parserWrapper) throws Exception {
+        E instance;
+
+        if (BinderType.XML == context.getSupportedFormat()) {
+            instance = parseOnXml(((XmlWrapperParser) parserWrapper).xmlParser, EventType.START_DOCUMENT);
+        } else {
+            if (context.getSupportedFormat().onlyText)
+                instance = parseOnJacksonAsString(((JacksonWrapperParser) parserWrapper).jacksonParser);
+            else
+                instance = parseOnJackson(((JacksonWrapperParser) parserWrapper).jacksonParser);
+        }
+
+        return instance;
+    }
+
+    /* (non-Javadoc)
+     * @see com.abubusoft.kripton.BinderMapper#parseCollection(com.abubusoft.kripton.BinderContext, com.abubusoft.kripton.persistence.ParserWrapper, java.util.Collection)
+     */
+    @Override
+    public > L parseCollection(BinderContext context, ParserWrapper parserWrapper, L collection) throws Exception {
+        switch (context.getSupportedFormat()) {
+            case XML: {
+                throw (new KriptonRuntimeException(context.getSupportedFormat() + " context does not support direct collection persistance"));
+            }
+            default: {
+                JacksonWrapperParser wrapperParser = (JacksonWrapperParser) parserWrapper;
+                JsonParser parser = wrapperParser.jacksonParser;
+
+                try {
+                    collection.clear();
+
+                    if (parser.nextToken() != JsonToken.START_ARRAY) {
+                        throw (new KriptonRuntimeException("Invalid input format"));
+                    }
+                    if (context.getSupportedFormat().onlyText) {
+                        while (parser.nextToken() != JsonToken.END_ARRAY) {
+                            collection.add(parseOnJacksonAsString(parser));
+                        }
+                    } else {
+                        while (parser.nextToken() != JsonToken.END_ARRAY) {
+                            collection.add(parseOnJackson(parser));
+                        }
+                    }
+                    return collection;
+                } catch (IOException e) {
+                    e.printStackTrace();
+                    throw (new KriptonRuntimeException(e));
+                }
+            }
+        }
+    }
+
+    /**
+     * Serialize an object using the contxt and the serializerWrapper.
+     *
+     * @param context           the context
+     * @param object            the object
+     * @param serializerWrapper the serializer wrapper
+     * @param writeStartAndEnd  the write start and end
+     * @throws Exception the exception
+     */
+    protected void serialize(BinderContext context, E object, SerializerWrapper serializerWrapper, boolean writeStartAndEnd) throws Exception {
+
+        switch (context.getSupportedFormat()) {
+            case XML:
+                try {
+                    XmlWrapperSerializer wrapper = ((XmlWrapperSerializer) serializerWrapper);
+                    XMLSerializer xmlSerializer = wrapper.xmlSerializer;
+
+                    if (writeStartAndEnd) {
+                        xmlSerializer.writeStartDocument();
+                    }
+                    serializeOnXml(object, xmlSerializer, EventType.START_DOCUMENT);
+
+                    if (writeStartAndEnd) {
+                        xmlSerializer.writeEndDocument();
+                    }
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    throw (new KriptonRuntimeException(e));
+                }
+                break;
+            default:
+                if (context.getSupportedFormat().onlyText)
+                    serializeOnJacksonAsString(object, ((JacksonWrapperSerializer) serializerWrapper).jacksonGenerator);
+                else
+                    serializeOnJackson(object, ((JacksonWrapperSerializer) serializerWrapper).jacksonGenerator);
+                break;
+        }
+    }
+
+    /* (non-Javadoc)
+     * @see com.abubusoft.kripton.BinderMapper#serialize(com.abubusoft.kripton.BinderContext, com.abubusoft.kripton.persistence.SerializerWrapper, java.lang.Object)
+     */
+    @Override
+    public void serialize(BinderContext context, SerializerWrapper serializerWrapper, E object) throws Exception {
+        serialize(context, object, serializerWrapper, true);
+    }
+
+    /* (non-Javadoc)
+     * @see com.abubusoft.kripton.BinderMapper#serializeCollection(com.abubusoft.kripton.BinderContext, com.abubusoft.kripton.persistence.SerializerWrapper, java.util.Collection)
+     */
+    @Override
+    public void serializeCollection(BinderContext context, SerializerWrapper serializerWrapper, Collection collection) throws Exception {
+        if (BinderType.XML == context.getSupportedFormat()) {
+            throw (new KriptonRuntimeException(context.getSupportedFormat() + " context does not support direct collection persistance"));
+        }
+
+        JacksonWrapperSerializer wrapper = (JacksonWrapperSerializer) serializerWrapper;
+        JsonGenerator jacksonGenerator = wrapper.jacksonGenerator;
+
+        try {
+            jacksonGenerator.writeStartArray();
+            if (context.getSupportedFormat().onlyText)
+                for (E object : collection) {
+                    serializeOnJacksonAsString(object, jacksonGenerator);
+                }
+            else
+                for (E object : collection) {
+                    serializeOnJackson(object, jacksonGenerator);
+                }
+            jacksonGenerator.writeEndArray();
+        } catch (IOException e) {
+            e.printStackTrace();
+            throw (new KriptonRuntimeException(e));
+        }
+    }
+
 }
diff --git a/kripton/src/test/java/bind/AbstractBaseTest.java b/kripton/src/test/java/bind/AbstractBaseTest.java
index d0a6c471e..917609cda 100644
--- a/kripton/src/test/java/bind/AbstractBaseTest.java
+++ b/kripton/src/test/java/bind/AbstractBaseTest.java
@@ -44,7 +44,7 @@
  *
  * @author Francesco Benincasa (info@abubusoft.com)
  */
-public class AbstractBaseTest {
+public abstract class AbstractBaseTest {
 	
 	/** The Constant KRIPTON_DEBUG_MODE. */
 	private static final String KRIPTON_DEBUG_MODE = "kripton.debug";
@@ -169,7 +169,8 @@ public int serializeAndParse(Object bean, BinderType type) throws Exception {
 			System.out.println("[[" + output2 + "]]");
 		}
 
-		Assert.assertTrue(type.toString(), output1.length() == output2.length());
+
+		Assert.assertEquals(type.toString(), output1.length(), output2.length());
 
 		ReflectionAssert.assertReflectionEquals(bean, bean2, ReflectionComparatorMode.LENIENT_ORDER);
 
@@ -203,7 +204,7 @@ public int serializeAndParseBinary(Object bean, BinderType type) throws Exceptio
 			System.out.println("[[" + value2 + "]]");
 		}
 
-		Assert.assertTrue(value1.length() == value2.length());
+		Assert.assertEquals(type.toString(),value1.length(), value2.length());
 
 		return bar.getCount();
 	}
@@ -233,7 +234,7 @@ public  int serializeAndParseCollection(Collection list, Class clazz, B
 			System.out.println("[[" + value2 + "]]");
 		}
 		//
-		Assert.assertTrue(value1.length() == value2.length());
+		Assert.assertEquals(type.toString(),value1.length(), value2.length());
 		ReflectionAssert.assertReflectionEquals(type.toString(), list, list2, ReflectionComparatorMode.LENIENT_ORDER);
 		//
 		return value1.length();
@@ -268,7 +269,7 @@ public  int serializeAndParseCollectionBinary(Collection list, Class cl
 			System.out.println("[[" + value2 + "]]");
 		}
 
-		Assert.assertTrue(value1.length() == value2.length());
+		Assert.assertEquals(type.toString(),value1.length(), value2.length());
 		ReflectionAssert.assertReflectionEquals(type.toString(), list, list2, ReflectionComparatorMode.LENIENT_ORDER);
 		//
 		return bar.getCount();