*/
package org.mxchange.jcore;
-import java.io.BufferedReader;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
import java.text.MessageFormat;
-import java.util.ArrayList;
import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
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.frontend.DatabaseFrontend;
import org.mxchange.jcore.manager.Manageable;
+import org.mxchange.jcore.model.contact.Contact;
/**
* General class
* @author Roland Haeder
*/
public class BaseFrameworkSystem implements FrameworkInterface {
+
/**
* Bundle instance
*/
private static ResourceBundle bundle;
- /**
- * Instance for own properties
- */
- private static final Properties properties = new Properties(System.getProperties());
-
/**
* Self instance
*/
*/
private Application application;
-
/**
* Client instance
*/
private Manageable manager;
/**
- * Name of used database table, handled over to backend
- */
- private String tableName;
-
- /**
- * DatabaseFrontend instance
+ * Initialize object
*/
- private DatabaseFrontend wrapper;
+ {
+ // Init logger
+ this.LOG = LogManager.getLogger(this);
+ // Need to set it here
+ selfInstance = this;
+ }
/**
- * Initialize object
+ * No instances can be created of this class
*/
- {
- LOG = LogManager.getLogger(this);
+ protected BaseFrameworkSystem () {
}
/**
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 the application
- */
@Override
public final Application getApplication () {
return this.application;
}
/**
- * Getter for logger
+ * Getter for logger instance
*
- * @return Logger
+ * @return Logger instance
*/
- @Override
- public final Logger getLogger () {
+ protected final Logger getLogger () {
return this.LOG;
}
- /**
- * Manager instance
- *
- * @return the contactManager
- */
@Override
public final Manageable getManager () {
return this.manager;
}
- /**
- * Getter for human-readable string from given key
- *
- * @param key Key to return
- * @return Human-readable message
- */
@Override
public final String getMessageStringFromKey (final String key) {
// Return message
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 instance Instance to iterate on
- * @param targetClass Class name to look for
- * @return Class instance
- */
- @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
-
- // Instance reflaction of this class
- Class<? extends FrameworkInterface> c = instance.getClass();
-
- // Analyze class
- while (!targetClass.equals(c.getSimpleName())) {
- // Debug message
- this.getLogger().debug(MessageFormat.format("c={0}", c.getSimpleName())); //NOI18N
-
- // Get super class (causes unchecked warning)
- c = (Class<? extends FrameworkInterface>) c.getSuperclass();
- }
-
- // Trace message
- this.getLogger().trace(MessageFormat.format("c={0} - EXIT!", c)); //NOI18N
-
- // Return it
- return c;
- }
-
- /**
- * 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
- * @return A Method instance
- */
- private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) {
- // 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
- Method method = null;
-
- // Use reflection to get all attributes
- try {
- 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;
- }
-
- /**
- * Setter for self instance
- */
- private void setSelfInstance () {
- // Need to set it here
- selfInstance = this;
- }
-
/**
* 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);
-
}
/**
this.application = application;
}
- /**
- * Client instance
- *
- * @return the client
- */
@Override
public final Client getClient () {
return this.client;
}
/**
- * Client instance
+ * Setter for bundle instance
*
- * @param client the client to set
+ * @param bundle the bundle to set
*/
- protected final void setClient (final Client client) {
- this.client = client;
+ protected static void setBundle (final ResourceBundle bundle) {
+ BaseFrameworkSystem.bundle = bundle;
}
/**
- * Checks if given boolean field is available and set to same value
+ * Client instance
*
- * @param columnName Column name to check
- * @param bool Boolean value
- * @return Whether all conditions are met
+ * @param client the client to set
*/
- @Override
- public boolean isValueEqual (final String columnName, final boolean bool) {
- // Not implemented
- throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
+ protected final void setClient (final Client client) {
+ this.client = client;
}
- /**
- * Log exception
- *
- * @param exception Exception to log
- */
@Override
public final void logException (final Throwable exception) {
// Log this exception
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
- */
- private void initPropertiesWithDefault () {
- // Trace message
- this.getLogger().trace("CALLED!"); //NOI18N
-
- // Init default values:
- // Default database backend
- BaseFrameworkSystem.properties.put("org.mxchange.database.backendType", "base64csv"); //NOI18N
-
- // For MySQL backend
- BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
- BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.dbname", "test"); //NOI18N
- BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.login", ""); //NOI18N
- BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.password", ""); //NOI18N
-
- // Trace message
- this.getLogger().trace("EXIT!"); //NOI18N
- }
-
- /**
- * Writes the properties file to disk
- */
- private void writePropertiesFile () {
- // 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);
- }
-
- // Trace message
- this.getLogger().trace("EXIT!"); //NOI18N
- }
-
- /**
- * Converts a column name like "foo_bar" to an attribute name like "fooBar"
- *
- * @param columnName Column name to convert
- * @return Attribute name
- */
- protected String convertColumnNameToAttribute (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
-
- // Resulting string
- StringBuilder builder = new StringBuilder(tokenizer.countTokens());
-
- // Init counter
- int count = 0;
-
- // Walk through all
- while (tokenizer.hasMoreTokens()) {
- // Get token
- String token = tokenizer.nextToken();
-
- // Is later than first element?
- if (count > 0) {
- // Make first character upper-case
- char c = token.charAt(0);
- token = String.valueOf(c).toUpperCase() + token.substring(1);
- }
-
- // Add token
- builder.append(token);
-
- // Increment counter
- count++;
- }
-
- // Trace message
- this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
-
- // Return result
- 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
- * @param isBool Whether the parameter is boolean
- * @return Attribute name
- */
- protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
- // 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());
-
- // Is it boolean?
- if (isBool) {
- // Append "is"
- builder.append("is"); //NOI18N
- } else {
- // Append "get"
- builder.append("get"); //NOI18N
- }
-
- // Walk through all
- while (tokenizer.hasMoreTokens()) {
- // Get token
- String token = tokenizer.nextToken();
-
- // Debug message
- this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
-
- // Make it upper-case
- char c = token.charAt(0);
- token = String.valueOf(c).toUpperCase() + token.substring(1);
-
- // 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
+ * @return Array from tokenized string TODO Get rid of size parameter
+ * TODO: Move to own utility class
*/
- 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
}
/**
- * Returns boolean field value from given method name by invoking it
+ * Converts null to empty string or leaves original object untouched.
*
- * @param instance The instance to call
- * @param targetClass Target class to look in
- * @param methodName Method name to look for
- * @return Boolean value from field
+ * @param object Any string
+ * @return Empty string if null or original string
+ * TODO: Move to own utility class
*/
- protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) {
- // Trace messahe
- this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
-
- // Get method instance
- Method method = this.getMethodFromName(instance, targetClass, methodName);
-
- // Get value from field
- Boolean value = false;
-
- 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);
+ protected Object convertNullToEmpty (final Object object) {
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("object={0}", object)); //NOI18N
+
+ // Is it null?
+ if (null == object) {
+ // Return empty string
+ return ""; //NOI18N
}
- // Return value
- return value;
+ // Trace message
+ this.getLogger().trace(MessageFormat.format("object={0} - EXIT!", object)); //NOI18N
+
+ // Return it
+ return object;
}
/**
*
* @param manager the manager instance to set
*/
- protected final void setContactManager (final Manageable manager) {
+ protected final void setManager (final Manageable manager) {
this.manager = manager;
}
- /**
- * Returns any field value from 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
- * @return Any value from field
- */
- protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) {
- // Trace messahe
- this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
-
- // Get method to call
- Method method = this.getMethodFromName(instance, targetClass, methodName);
-
- // Get value from field
- Object object = null;
-
- 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);
- }
-
- // Return value
- return object;
- }
-
- /**
- * Getter for property which must exist
- *
- * @param key Key to get
- * @return Propety value
- */
- protected final String getProperty (final String key) {
- return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.%s", key)); //NOI18N
- }
-
- /**
- * Name of used database table, handled over to backend
- *
- * @return the tableName
- */
- protected final String getTableName () {
- return this.tableName;
- }
-
- /**
- * Name of used database table, handled over to backend
- *
- * @param tableName the tableName to set
- */
- protected final void setTableName (final String tableName) {
- this.tableName = tableName;
- }
-
- /**
- * Getter for DatabaseFrontend instance
- *
- * @return DatabaseFrontend instance
- */
- protected final DatabaseFrontend getWrapper () {
- return this.wrapper;
- }
-
- /**
- * Setter for wrapper instance
- *
- * @param wrapper A DatabaseFrontend instance
- */
- protected final void setWrapper (final DatabaseFrontend wrapper) {
- this.wrapper = wrapper;
- }
-
/**
* Getter for Contact instance
*
* Initializes i18n bundles
*/
protected void initBundle () {
+ // Trace message
+ this.getLogger().trace("CALLED!"); //NOI18N
+
// Is the bundle set?
- if (bundle instanceof ResourceBundle) {
+ if (BaseFrameworkSystem.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
- /**
- * 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
- * @return Whether the given column name represents a boolean field
- */
- protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
// Trace message
- this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
-
- // Convert column name to getter name (boolean)
- String methodName = this.convertColumnNameToGetterMethod(columnName, true);
-
- // Get class instance
- Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
-
- // Defauzlt is boolean
- boolean isBool = true;
-
- try {
- // Now try to instance the method
- Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
- } catch (final NoSuchMethodException ex) {
- // Debug message
- this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
-
- // Not found
- isBool = false;
- } catch (final SecurityException ex) {
- // Really bad?
- this.abortProgramWithException(ex);
- }
-
- // Trace message
- this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N
-
- // Return result
- return isBool;
+ this.getLogger().trace("EXIT!"); //NOI18N
}
/**
- * Creates an iterator from given instance and class name.
- *
- * @param instance Instance to run getter calls on
- * @param className Class name to iterate over
- * @return An iterator over all object's fields
+ * Checks if the bundle is initialized
+ *
+ * @return Whether the bundle has been initialized
*/
- protected Iterator<Object> fieldIterator (final FrameworkInterface instance, final String className) {
- // Trace message
- this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className));
-
- // 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));
-
- // A list is fine
- List<Object> list = new ArrayList<>(fields.length);
-
- // Walk through all
- for (final Field field : fields) {
- // Debug log
- this.getLogger().debug(MessageFormat.format("field={0}", field.getName()));
-
- // Does the field start with "$"?
- if (field.getName().startsWith("$")) {
- // Skip it silently
- continue;
- }
-
- // Get value from it
- Object value = this.getValueFromColumn(field.getName());
-
- // Debug message
- this.getLogger().debug(MessageFormat.format("value={0}", value));
-
- // Add it to list
- boolean added = list.add(value);
-
- // Debug log
- this.getLogger().debug("added=" + added);
- }
-
- // Debug message
- this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", list.size()));
-
- // Return list iterator
- return list.iterator();
+ protected static boolean isBundledInitialized () {
+ // Check it
+ return (bundle instanceof ResourceBundle);
}
}