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 @@
-
-
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
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
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
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 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+ * 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- * 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- * 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(); - } - - /** - * Returntrue
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; - } - } - - /** - * Returnstrue
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+ * 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(); + } + + /** + * Returntrue
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 Settrue
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+ * 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 SetDuring 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 @@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* 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();