import java.util.Properties;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
+import org.apache.commons.lang3.ArrayUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.mxchange.jcore.application.Application;
import org.mxchange.jcore.client.Client;
import org.mxchange.jcore.contact.Contact;
+import org.mxchange.jcore.database.backend.DatabaseBackend;
import org.mxchange.jcore.database.frontend.DatabaseFrontend;
+import org.mxchange.jcore.database.storage.Storable;
import org.mxchange.jcore.manager.Manageable;
/**
* @author Roland Haeder
*/
public class BaseFrameworkSystem implements FrameworkInterface {
+
/**
* Bundle instance
*/
*/
private Application application;
+ /**
+ * Instance for database backend
+ */
+ private DatabaseBackend backend;
/**
* Client instance
/**
* DatabaseFrontend instance
*/
- private DatabaseFrontend wrapper;
+ private DatabaseFrontend frontend;
+ /**
+ * Session id assigned with this basket, or any other unique identifier
+ */
+ private String sessionId;
/**
* Initialize object
LOG = LogManager.getLogger(this);
}
+ /**
+ * No instances can be created of this class
+ */
+ protected BaseFrameworkSystem () {
+ // Set own instance
+ this.setSelfInstance();
+ }
+
/**
* Getter for this application
*
return selfInstance;
}
- /**
- * No instances can be created of this class
- */
- protected BaseFrameworkSystem () {
- // Init properties file
- this.initProperties();
-
- // Set own instance
- this.setSelfInstance();
- }
-
/**
* Application instance
*
return this.getBundle().getString(key);
}
- /**
- * Some "getter for a value from given column name. This name will be
- * translated into a method name and then this method is called.
- *
- * @param columnName Column name
- * @return Value from field
- * @throws IllegalArgumentException Some implementations may throw this.
- */
- @Override
- public Object getValueFromColumn (final String columnName) throws IllegalArgumentException {
- throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0}", columnName)); //NOI18N
- }
-
/**
* Some "getter" for target class instance from given name.
*
* @param targetClass Class name to look for
* @return Class instance
*/
- @SuppressWarnings ("unchecked")
+ @SuppressWarnings("unchecked")
private Class<? extends FrameworkInterface> getClassFromTarget (final FrameworkInterface instance, final String targetClass) {
// Trace message
this.getLogger().debug(MessageFormat.format("instance={0},targetClass={1}", instance, targetClass)); //NOI18N
* @param methodName Method name
* @return A Method instance
*/
- private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) {
+ private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException {
// Trace messahe
this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
- // Get target class instance
- Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
- // Init field instance
+ // Init method instance
Method method = null;
- // Use reflection to get all attributes
+ // Try it from target class
try {
+ // Get target class instance
+ Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
+
+ // Init field instance
+ method = c.getDeclaredMethod(methodName, new Class<?>[0]);
+ } catch (final NoSuchMethodException e) {
+ // Didn't found it
+ this.getLogger().warn(e);
+
+ // So try it from super class
+ Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, "BaseFrameworkSystem"); //NOI18N
+
+ // Init field instance
method = c.getDeclaredMethod(methodName, new Class<?>[0]);
- } catch (final SecurityException ex) {
- // Security problem
- this.abortProgramWithException(ex);
- } catch (final NoSuchMethodException ex) {
- // Method not found
- this.abortProgramWithException(ex);
+ }
+
+ // Assert on field
+ assert (method instanceof Method) : "method is not a Method instance"; //NOI18N
+
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("method={0} - EXIT!", method)); //NOI18N
+
+ // Return it
+ return method;
+ }
+
+ /**
+ * Some "getter" for a Method instance from given method name
+ *
+ * @param instance Actual instance to call
+ * @param targetClass Target class name
+ * @param methodName Method name
+ * @param type Type reflection to check type from
+ * @return A Method instance
+ */
+ private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName, final Class<?> type) throws NoSuchMethodException {
+ // Trace messahe
+ this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1},type={2}", targetClass, methodName, type)); //NOI18N
+
+ // Init method instance
+ Method method = null;
+
+ // Try it from target class
+ try {
+ // Get target class instance
+ Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
+
+ // Init field instance
+ method = c.getDeclaredMethod(methodName, type);
+ } catch (final NoSuchMethodException e) {
+ // Didn't found it
+ this.getLogger().warn(e);
+
+ // So try it from super class
+ Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, "BaseFrameworkSystem"); //NOI18N
+
+ // Init field instance
+ method = c.getDeclaredMethod(methodName, type);
}
// Assert on field
/**
* Aborts program with given exception
*
- * @param throwable Any type of Throwable
+ * @param throwable Any type of Throwable
*/
protected final void abortProgramWithException (final Throwable throwable) {
// Log exception ...
- this.getLogger().catching(throwable);
+ this.logException(throwable);
// .. and exit
System.exit(1);
-
}
/**
return BaseFrameworkSystem.bundle;
}
+ /**
+ * Setter for bundle instance
+ *
+ * @param bundle the bundle to set
+ */
+ protected static void setBundle (final ResourceBundle bundle) {
+ BaseFrameworkSystem.bundle = bundle;
+ }
+
/**
* Client instance
*
this.client = client;
}
+ /**
+ * Name of used database table, handled over to backend
+ *
+ * @return the tableName
+ */
+ public final String getTableName () {
+ return this.tableName;
+ }
+
/**
* Checks if given boolean field is available and set to same value
*
* @param columnName Column name to check
* @param bool Boolean value
* @return Whether all conditions are met
+ * @throws NoSuchMethodException May be thrown by some implementations
+ * @throws java.lang.IllegalAccessException If the method cannot be accessed
+ * @throws java.lang.reflect.InvocationTargetException Any other problems?
*/
@Override
- public boolean isValueEqual (final String columnName, final boolean bool) {
+ public boolean isFieldValueEqual (final String columnName, final boolean bool) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
// Not implemented
throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
}
this.getLogger().catching(exception);
}
- /**
- * Prepares all properties, the file is written if it is not found
- */
- private void initProperties () {
- // Trace message
- this.getLogger().trace("CALLED!"); //NOI18N
-
- // Debug message
- this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
-
- // Are some properties loaded?
- if (!BaseFrameworkSystem.properties.isEmpty()) {
- // Some are already loaded, abort here
- return;
- }
-
- try {
- // Try to read it
- BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
-
- // Debug message
- this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
- } catch (final FileNotFoundException ex) {
- // Debug message
- this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
-
- /*
- * The file is not found which is normal for first run, so
- * initialize default values.
- */
- this.initPropertiesWithDefault();
-
- // Write file
- this.writePropertiesFile();
- } catch (final IOException ex) {
- // Something else didn't work
- this.abortProgramWithException(ex);
- }
-
- // Trace message
- this.getLogger().trace("EXIT!"); //NOI18N
- }
-
/**
* Initializes properties with default values
*/
// Init default values:
// Default database backend
- BaseFrameworkSystem.properties.put("org.mxchange.database.backendType", "base64csv"); //NOI18N
+ BaseFrameworkSystem.properties.put("org.mxchange.database.backend.class", "org.mxchange.jcore.database.backend.base64.Base64CsvDatabaseBackend"); //NOI18N
+ BaseFrameworkSystem.properties.put("org.mxchange.database.backend.storagepath", "data/"); //NOI18N
+ BaseFrameworkSystem.properties.put("org.mxchange.database.datasource.name", ""); //NOI18N
// For MySQL backend
BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
/**
* Writes the properties file to disk
*/
- private void writePropertiesFile () {
+ private void writePropertiesFile () throws IOException {
// Trace message
this.getLogger().trace("CALLED!"); //NOI18N
- try {
- // Write it
- BaseFrameworkSystem.properties.store(new PrintWriter(FrameworkInterface.PROPERTIES_CONFIG_FILE), "This file is automatically generated. You may wish to alter it."); //NOI18N
- } catch (final IOException ex) {
- this.abortProgramWithException(ex);
- }
+ // Write it
+ BaseFrameworkSystem.properties.store(new PrintWriter(FrameworkInterface.PROPERTIES_CONFIG_FILE), "This file is automatically generated. You may wish to alter it."); //NOI18N
// Trace message
this.getLogger().trace("EXIT!"); //NOI18N
* @param columnName Column name to convert
* @return Attribute name
*/
- protected String convertColumnNameToAttribute (final String columnName) {
+ protected String convertColumnNameToFieldName (final String columnName) {
// Trace message
this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
- // First all lower case
- String lower = columnName.toLowerCase();
-
- // Then split on "_"
- StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
+ // Split on "_"
+ StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
// Resulting string
StringBuilder builder = new StringBuilder(tokenizer.countTokens());
*/
protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
// Trace message
- this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
+ this.getLogger().trace(MessageFormat.format("columnName={0},isBool={1} - CALLED!", columnName, isBool)); //NOI18N
// Then split on "_"
StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
return builder.toString();
}
+ /**
+ * Converts a column name like "foo_bar" to a method name like "getFooBar"
+ * for non-booleans and to "isFooBar" for boolean fields.
+ *
+ * @param columnName Column name to convert
+ * @return Attribute name
+ */
+ protected String convertColumnNameToSetterMethod (final String columnName) {
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
+
+ // Then split on "_"
+ StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
+
+ // Resulting string
+ StringBuilder builder = new StringBuilder(tokenizer.countTokens());
+
+ // Append "set"
+ builder.append("set"); //NOI18N
+
+ // Walk through all
+ while (tokenizer.hasMoreTokens()) {
+ // Get token
+ String token = tokenizer.nextToken();
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("token={0} - BEFORE", token)); //NOI18N
+
+ // Make it upper-case
+ char c = token.charAt(0);
+ token = String.valueOf(c).toUpperCase() + token.substring(1);
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("token={0} - AFTER", token)); //NOI18N
+
+ // Add token
+ builder.append(token);
+ }
+
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
+
+ // Return result
+ return builder.toString();
+ }
+
/**
* Some "getter" for an array from given string and tokenizer
*
* @param str String to tokenize and get array from
* @param delimiter Delimiter
- * @param size Size of array
* @return Array from tokenized string
- * @todo Get rid of size parameter
+ * TODO Get rid of size parameter
*/
- protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
+ protected String[] getArrayFromString (final String str, final String delimiter) {
// Trace message
- this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
-
+ this.getLogger().trace(MessageFormat.format("str={0},delimiter={1} - CALLED!", str, delimiter)); //NOI18N
+
// Get tokenizer
StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
-
+
// Init array and index
- String[] tokens = new String[size];
+ String[] tokens = new String[tokenizer.countTokens()];
int index = 0;
-
+
// Run through all tokens
while (tokenizer.hasMoreTokens()) {
// Get current token and add it
tokens[index] = tokenizer.nextToken();
-
+
// Debug message
this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
-
+
// Increment index
index++;
}
-
+
// Trace message
this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
* @param targetClass Target class to look in
* @param methodName Method name to look for
* @return Boolean value from field
+ * @throws java.lang.NoSuchMethodException If the method was not found
+ * @throws java.lang.IllegalAccessException If the method cannot be accessed
+ * @throws java.lang.reflect.InvocationTargetException Some other problems?
*/
- protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) {
+ protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Trace messahe
this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
Method method = this.getMethodFromName(instance, targetClass, methodName);
// Get value from field
- Boolean value = false;
+ Boolean value = (Boolean) method.invoke(instance);
- try {
- value = (Boolean) method.invoke(instance);
- } catch (final IllegalArgumentException ex) {
- // Other problem
- this.abortProgramWithException(ex);
- } catch (final IllegalAccessException ex) {
- // Other problem
- this.abortProgramWithException(ex);
- } catch (final InvocationTargetException ex) {
- // Other problem
- this.abortProgramWithException(ex);
- }
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
// Return value
return value;
}
+ /**
+ * Sets boolean field value with given method name by invoking it
+ *
+ * @param instance The instance to call
+ * @param targetClass Target class to look in
+ * @param methodName Method name to look for
+ * @param columnName Column name
+ * @param value Boolean value from field
+ * @throws java.lang.NoSuchMethodException If the method was not found
+ * @throws java.lang.IllegalAccessException If the method cannot be accessed
+ * @throws java.lang.reflect.InvocationTargetException Some other problems?
+ */
+ protected void setBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName, final String columnName, final Boolean value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+ // Trace messahe
+ this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
+
+ // Get field type
+ Class<?> type = this.getType(instance, targetClass, columnName);
+
+ // Get method instance
+ Method method = this.getMethodFromName(instance, targetClass, methodName, type);
+
+ // Try to get the value by invoking the method
+ method.invoke(instance, value);
+
+ // Trace message
+ this.getLogger().trace("EXIT!"); //NOI18N
+ }
+
/**
* Manager instance
*
* @param targetClass Target class to look in
* @param methodName Method name to look for
* @return Any value from field
+ * @throws java.lang.NoSuchMethodException If the method was not found
+ * @throws java.lang.IllegalAccessException If the method cannot be accessed
+ * @throws java.lang.reflect.InvocationTargetException Some other problems?
*/
- protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) {
+ protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Trace messahe
- this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
+ this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},methodName={2}", instance, targetClass, methodName)); //NOI18N
// Get method to call
Method method = this.getMethodFromName(instance, targetClass, methodName);
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("method={0},instance={1}", method, instance)); //NOI18N
+
// Get value from field
- Object object = null;
+ Object value = method.invoke(instance);
- try {
- object = method.invoke(instance);
- } catch (final IllegalArgumentException ex) {
- // Other problem
- this.abortProgramWithException(ex);
- } catch (final IllegalAccessException ex) {
- // Other problem
- this.abortProgramWithException(ex);
- } catch (final InvocationTargetException ex) {
- // Other problem
- this.abortProgramWithException(ex);
- }
+ // Trace messahe
+ this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
// Return value
- return object;
+ return value;
+ }
+
+ /**
+ * Sets any field value with given method name by invoking it
+ *
+ * @param instance The instance to call
+ * @param targetClass Target class to look in
+ * @param methodName Method name to look for
+ * @param columnName Column name
+ * @param value Any value from field
+ * @throws java.lang.NoSuchMethodException If the method was not found
+ * @throws java.lang.IllegalAccessException If the method cannot be accessed
+ * @throws java.lang.reflect.InvocationTargetException Some other problems?
+ */
+ protected void setField (final FrameworkInterface instance, final String targetClass, final String methodName, final String columnName, final Object value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+ // Trace messahe
+ this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},methodName={2},value={3}", instance, targetClass, methodName, value)); //NOI18N
+
+ // Get field type
+ Class<?> type = this.getType(instance, targetClass, columnName);
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("type={0}", type)); //NOI18N
+
+ // Init object
+ Object object = value;
+
+ // Is the value null?
+ if ("null".equals(value)) { //NOI18N
+ // Warning message
+ this.getLogger().warn(MessageFormat.format("columnName={0} has null value.", columnName)); //NOI18N
+
+ // Set null
+ object = null;
+ } else {
+ // Hard-coded "cast" again ... :-(
+ // TODO Can't we get rid of this???
+ switch (type.getSimpleName()) {
+ case "Long": // Long object //NOI18N
+ object = Long.parseLong((String) value);
+ break;
+
+ case "Float": // Float object //NOI18N
+ object = Float.parseFloat((String) value);
+ break;
+
+ case "Boolean": // Boolean object //NOI18N
+ object = Boolean.parseBoolean((String) value);
+ break;
+
+ case "String": // String object //NOI18N
+ break;
+
+ default: // Unsupported type
+ throw new IllegalArgumentException(MessageFormat.format("value {0} has unsupported type {1}", value, type.getSimpleName())); //NOI18N
+ }
+ }
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("object={0}", object)); //NOI18N
+
+ // Get method to call
+ Method method = this.getMethodFromName(instance, targetClass, methodName, type);
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("method={0},instance={1},value[{2}]={3}", method, instance, value.getClass().getSimpleName(), value)); //NOI18N
+
+ // Get value from field
+ method.invoke(instance, object);
+
+ // Trace messahe
+ this.getLogger().trace("EXIT!"); //NOI18N
}
/**
/**
* Name of used database table, handled over to backend
*
- * @return the tableName
+ * @param tableName the tableName to set
*/
- protected final String getTableName () {
- return this.tableName;
+ protected final void setTableName (final String tableName) {
+ this.tableName = tableName;
}
/**
- * Name of used database table, handled over to backend
+ * Converts null to empty string or leaves original string.
*
- * @param tableName the tableName to set
+ * @param str Any string
+ * @return Empty string if null or original string
*/
- protected final void setTableName (final String tableName) {
- this.tableName = tableName;
+ protected Object convertNullToEmpty (final Object str) {
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("str={0}", str)); //NOI18N
+
+ // Is it null?
+ if (null == str) {
+ // Return empty string
+ return ""; //NOI18N
+ }
+
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("str={0} - EXIT!", str)); //NOI18N
+
+ // Return it
+ return str;
}
/**
- * Getter for DatabaseFrontend instance
+ * Creates an iterator from given instance and class name.
*
- * @return DatabaseFrontend instance
+ * @param instance Instance to run getter calls on
+ * @param className Class name to iterate over
+ * @return An iterator over all object's fields
+ * @throws java.lang.NoSuchMethodException If the called method does not exist
+ * @throws java.lang.IllegalAccessException If the method cannot be accessed
+ * @throws java.lang.reflect.InvocationTargetException Any other problems?
*/
- protected final DatabaseFrontend getWrapper () {
- return this.wrapper;
+ protected Iterator<Map.Entry<Field, Object>> fieldIterator (final Storable instance, final String className) throws IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className)); //NOI18N
+
+ // Get all attributes from given instance
+ Field[] fields = this.getClassFromTarget(instance, className).getDeclaredFields();
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("Found {0} fields.", fields.length)); //NOI18N
+
+ // A simple map with K=fieldName and V=Value is fine
+ Map<Field, Object> map = new HashMap<>(fields.length);
+
+ // Walk through all
+ for (final Field field : fields) {
+ // Debug log
+ this.getLogger().debug(MessageFormat.format("field={0}", field.getName())); //NOI18N
+
+ // Does the field start with "$"?
+ if (field.getName().startsWith("$")) { //NOI18N
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("Skipping field={0} as it starts with a dollar character.", field.getName())); //NOI18N
+
+ // Skip it silently
+ continue;
+ }
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("Calling getValueFromColumn({0}) on instance {1} ...", field.getName(), instance)); //NOI18N
+
+ // Get value from it
+ Object value = instance.getValueFromColumn(field.getName());
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("Adding field={0},value={1}", field.getName(), value)); //NOI18N
+
+ // Add it to list
+ map.put(field, value);
+ }
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", map.size())); //NOI18N
+
+ // Return list iterator
+ return map.entrySet().iterator();
}
/**
- * Setter for wrapper instance
+ * Instance for database backend
+ *
+ * @return the backend
+ */
+ protected final DatabaseBackend getBackend () {
+ return this.backend;
+ }
+
+ /**
+ * Instance for database backend
*
- * @param wrapper A DatabaseFrontend instance
+ * @param backend the backend to set
*/
- protected final void setWrapper (final DatabaseFrontend wrapper) {
- this.wrapper = wrapper;
+ protected final void setBackend (final DatabaseBackend backend) {
+ this.backend = backend;
}
/**
this.contact = contact;
}
+ /**
+ * Getter for DatabaseFrontend instance
+ *
+ * @return DatabaseFrontend instance
+ */
+ protected final DatabaseFrontend getFrontend () {
+ return this.frontend;
+ }
+
+ /**
+ * Setter for wrapper instance
+ *
+ * @param frontend A DatabaseFrontend instance
+ */
+ protected final void setFrontend (final DatabaseFrontend frontend) {
+ this.frontend = frontend;
+ }
+
+ /**
+ * Setter for session id
+ *
+ * @param sessionId Session id
+ */
+ @Override
+ public final void setSessionId (final String sessionId) {
+ this.sessionId = sessionId;
+ }
+
+ /**
+ * Getter for session id
+ *
+ * @return Session id
+ */
+ @Override
+ public final String getSessionId () {
+ return this.sessionId;
+ }
+
+ /**
+ * Checks if the bundle is initialized
+ *
+ * @return Whether the bundle has been initialized
+ */
+ protected boolean isBundledInitialized () {
+ // Check it
+ return (bundle instanceof ResourceBundle);
+ }
+
/**
* Initializes i18n bundles
*/
protected void initBundle () {
+ // Trace message
+ this.getLogger().trace("CALLED!"); //NOI18N
+
// Is the bundle set?
- if (bundle instanceof ResourceBundle) {
+ if (this.isBundledInitialized()) {
// Is already set
- throw new IllegalStateException("called twice");
+ throw new IllegalStateException("called twice"); //NOI18N
}
// Set instance
- bundle = ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE); // NOI18N
+ setBundle(ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE)); // NOI18N
+
+ // Trace message
+ this.getLogger().trace("EXIT!"); //NOI18N
+ }
+
+ /**
+ * Prepares all properties, the file is written if it is not found
+ *
+ * @throws java.io.IOException If any IO problem occurs
+ */
+ protected void initProperties () throws IOException {
+ // Trace message
+ this.getLogger().trace("CALLED!"); //NOI18N
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
+
+ // Are some properties loaded?
+ if (!BaseFrameworkSystem.properties.isEmpty()) {
+ // Some are already loaded, abort here
+ return;
+ }
+
+ try {
+ // Try to read it
+ BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
+ } catch (final FileNotFoundException ex) {
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
+
+ /*
+ * The file is not found which is normal for first run, so
+ * initialize default values.
+ */
+ this.initPropertiesWithDefault();
+
+ // Write file
+ this.writePropertiesFile();
+ }
+
+ // Trace message
+ this.getLogger().trace("EXIT!"); //NOI18N
}
/**
* Checks whether the given field is a boolean field by probing it.
- *
+ *
* @param instance Instance to call
* @param targetClass Target class
* @param columnName Column name to check
// Not found
isBool = false;
- } catch (final SecurityException ex) {
- // Really bad?
- this.abortProgramWithException(ex);
}
// Trace message
}
/**
- * Creates an iterator from given instance and class name.
+ * Sets value in properties instance.
+ *
+ * @param key Property key (part) to set
+ * @param value Property value to set
+ */
+ protected void setProperty (final String key, final String value) {
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("key={0},value={1} - CALLED!", key, value)); //NOI18N
+
+ // Both should not be null
+ if (null == key) {
+ // key is null
+ throw new NullPointerException("key is null"); //NOI18N
+ } else if (null == value) {
+ // value is null
+ throw new NullPointerException("value is null"); //NOI18N
+ }
+
+ // Set it
+ properties.setProperty(String.format("org.mxchange.%s", key), value); //NOI18N
+
+ // Trace message
+ this.getLogger().trace("EXIT!"); //NOI18N
+ }
+
+ /**
+ * Some getter for properties names (without org.mxchange)
+ *
+ * @return An array with property names
+ */
+ protected String[] getPropertyNames () {
+ // Init array
+ String[] names = {
+ "database.backend.class", //NOI18N
+ "database.backend.storagepath", //NOI18N
+ "database.mysql.login", //NOI18N
+ "database.mysql.host", //NOI18N
+ "database.mysql.password", //NOI18N
+ "database.mysql.dbname", //NOI18N
+ };
+
+ // Return it
+ return names;
+ }
+
+ /**
+ * Some "setter" for a value in given Storable instance and target class
*
- * @param instance Instance to run getter calls on
- * @param className Class name to iterate over
- * @return An iterator over all object's fields
+ * @param instance An instance of a Storable class
+ * @param targetClass The target class (where the field resides)
+ * @param columnName Column name (= field name)
+ * @param value Value to set
+ * @throws java.lang.NoSuchMethodException If the setter is not found
+ * @throws java.lang.IllegalAccessException If the setter cannot be accessed
+ * @throws java.lang.reflect.InvocationTargetException Any other problem?
*/
- protected Iterator<Map.Entry<Field, Object>> fieldIterator (final FrameworkInterface instance, final String className) {
+ protected void setValueInStorableFromColumn (final Storable instance, final String targetClass, final String columnName, final Object value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
// Trace message
- this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className));
+ this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2},value={3} - CALLED!", instance, targetClass, columnName, value)); //NOI18N
- // Get all attributes from given instance
- Field[] fields = this.getClassFromTarget(instance, className).getDeclaredFields();
+ // A '$' means not our field
+ if (columnName.startsWith("$")) { //NOI18N
+ // Don't handle these
+ throw new IllegalArgumentException("columnsName contains $"); //NOI18N
+ }
+
+ // Determine if the given column is boolean
+ if (this.isBooleanField(instance, targetClass, columnName)) {
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("Column {0} represents a boolean field.", columnName)); //NOI18N
+
+ // Yes, then call other method
+ this.setBooleanField(instance, targetClass, this.convertColumnNameToSetterMethod(columnName), columnName, (Boolean) value);
+ }
+
+ // Convert column name to field name
+ String methodName = this.convertColumnNameToSetterMethod(columnName);
// Debug message
- this.getLogger().debug(MessageFormat.format("Found {0} fields.", fields.length));
+ this.getLogger().debug(MessageFormat.format("methodName={0}", methodName)); //NOI18N
- // A simple map with K=fieldName and V=Value is fine
- Map<Field, Object> map = new HashMap<>(fields.length);
+ // Get field
+ this.setField(instance, targetClass, methodName, columnName, value);
- // Walk through all
- for (final Field field : fields) {
- // Debug log
- this.getLogger().debug(MessageFormat.format("field={0}", field.getName()));
+ // Trace message
+ this.getLogger().trace("EXIT!"); //NOI18N
+ }
- // Does the field start with "$"?
- if (field.getName().startsWith("$")) {
- // Skip it silently
- continue;
- }
+ /**
+ * Some "getter" for a value from given Storable instance and target class
+ *
+ * @param instance An instance of a Storable class
+ * @param targetClass The target class (where the field resides)
+ * @param columnName Column name (= field name)
+ * @return value Value to get
+ * @throws java.lang.NoSuchMethodException If the getter was not found
+ * @throws java.lang.IllegalAccessException If the getter cannot be accessed
+ * @throws java.lang.reflect.InvocationTargetException Some other problems?
+ */
+ protected Object getValueInStorableFromColumn (final Storable instance, final String targetClass, final String columnName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
- // Get value from it
- Object value = this.getValueFromColumn(field.getName());
+ // A '$' means not our field
+ if (columnName.startsWith("$")) { //NOI18N
+ // Don't handle these
+ throw new IllegalArgumentException("columnsName contains $"); //NOI18N
+ }
+ // Determine if the given column is boolean
+ if (this.isBooleanField(instance, targetClass, columnName)) {
// Debug message
- this.getLogger().debug(MessageFormat.format("value={0}", value));
+ this.getLogger().debug(MessageFormat.format("Column {0} represents a boolean field.", columnName)); //NOI18N
- // Add it to list
- map.put(field, value);
+ // Yes, then call other method
+ return this.getBooleanField(instance, targetClass, this.convertColumnNameToGetterMethod(columnName, true));
}
+ // Convert column name to field name
+ String methodName = this.convertColumnNameToGetterMethod(columnName, false);
+
// Debug message
- this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", map.size()));
+ this.getLogger().debug(MessageFormat.format("methodName={0}", methodName)); //NOI18N
- // Return list iterator
- return map.entrySet().iterator();
+ // Get field
+ Object value = this.getField(instance, targetClass, methodName);
+
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
+
+ // Return value
+ return value;
}
/**
- * Converts null to empty string or leaves original string.
+ * Some getter for type reflection of given column name
*
- * @param str Any string
- * @return Empty string if null or original string
+ * @param instance The instance to check
+ * @param targetClass Target class to check
+ * @param columnName Column name
+ * @return Type reflection of value
*/
- protected String convertNullToEmpty (final String str) {
+ private Class<?> getType (final FrameworkInterface instance, final String targetClass, final String columnName) {
// Trace message
- this.getLogger().trace(MessageFormat.format("str={0}", str));
+ this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
- // Is it null?
- if (str == null) {
- // Return empty string
- return "";
+ // Init field tye
+ Class<?> type = null;
+
+ // Get super class fields
+ Field[] superFields = this.getClassFromTarget(instance, "BaseFrameworkSystem").getDeclaredFields(); //NOI18N
+
+ // Get all attributes from given instance
+ Field[] fields = ArrayUtils.addAll(superFields, this.getClassFromTarget(instance, targetClass).getDeclaredFields());
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("fields()={0}", fields.length)); //NOI18N
+
+ // Convert column_name to fieldName ;-)
+ String fieldName = this.convertColumnNameToFieldName(columnName);
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("fieldName={0}", fieldName)); //NOI18N
+
+ // Search for proper field instance
+ for (final Field field : fields) {
+ // Is a dollar character there?
+ if (field.getName().startsWith("$")) { //NOI18N
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("Field name {0} starts with a dollar, skipped.", field.getName())); //NOI18N
+ // Skip this
+ continue;
+ }
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("field.getName()={0},fieldName={1}", field.getName(), fieldName)); //NOI18N
+
+ // Does it match?
+ if (field.getName().equals(fieldName)) {
+ // Found it
+ type = field.getType();
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("Found fieldName={0}: setting type={1}", fieldName, type.getSimpleName())); //NOI18N
+
+ // Don't continue with searching
+ break;
+ }
+ }
+
+ // Debug message
+ this.getLogger().debug(MessageFormat.format("type={0}", type)); //NOI18N
+
+ // type should not be null
+ if (null == type) {
+ // No null allowed
+ throw new NullPointerException("type is null"); //NOI18N
}
// Trace message
- this.getLogger().trace(MessageFormat.format("str={0} - EXIT!", str));
+ this.getLogger().debug(MessageFormat.format("type={0} - EXIT!", type)); //NOI18N
// Return it
- return str;
+ return type;
}
}