2 * Copyright (C) 2015 Roland Haeder
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 package org.mxchange.jcore;
19 import java.io.BufferedReader;
20 import java.io.FileInputStream;
21 import java.io.FileNotFoundException;
22 import java.io.IOException;
23 import java.io.InputStreamReader;
24 import java.io.PrintWriter;
25 import java.lang.reflect.Field;
26 import java.lang.reflect.InvocationTargetException;
27 import java.lang.reflect.Method;
28 import java.text.MessageFormat;
29 import java.util.Arrays;
30 import java.util.HashMap;
31 import java.util.Iterator;
33 import java.util.Properties;
34 import java.util.ResourceBundle;
35 import java.util.StringTokenizer;
36 import org.apache.logging.log4j.LogManager;
37 import org.apache.logging.log4j.Logger;
38 import org.mxchange.jcore.application.Application;
39 import org.mxchange.jcore.client.Client;
40 import org.mxchange.jcore.contact.Contact;
41 import org.mxchange.jcore.database.backend.DatabaseBackend;
42 import org.mxchange.jcore.database.frontend.DatabaseFrontend;
43 import org.mxchange.jcore.manager.Manageable;
48 * @author Roland Haeder
50 public class BaseFrameworkSystem implements FrameworkInterface {
55 private static ResourceBundle bundle;
58 * Instance for own properties
60 private static final Properties properties = new Properties(System.getProperties());
65 private static FrameworkInterface selfInstance;
70 private final Logger LOG;
73 * Application instance
75 private Application application;
78 * Instance for database backend
80 private DatabaseBackend backend;
85 private Client client;
90 private Contact contact;
95 private Manageable manager;
98 * Name of used database table, handled over to backend
100 private String tableName;
103 * DatabaseFrontend instance
105 private DatabaseFrontend wrapper;
111 LOG = LogManager.getLogger(this);
115 * No instances can be created of this class
117 protected BaseFrameworkSystem () {
119 this.setSelfInstance();
123 * Getter for this application
125 * @return Instance from this application
127 public static final FrameworkInterface getInstance () {
133 * Application instance
135 * @return the application
138 public final Application getApplication () {
139 return this.application;
148 public final Logger getLogger () {
155 * @return the contactManager
158 public final Manageable getManager () {
163 * Getter for human-readable string from given key
165 * @param key Key to return
166 * @return Human-readable message
169 public final String getMessageStringFromKey (final String key) {
171 return this.getBundle().getString(key);
175 * Some "getter for a value from given column name. This name will be
176 * translated into a method name and then this method is called.
178 * @param columnName Column name
179 * @return Value from field
180 * @throws IllegalArgumentException Some implementations may throw this.
183 public Object getValueFromColumn (final String columnName) throws IllegalArgumentException {
184 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0}", columnName)); //NOI18N
188 * Some "getter" for target class instance from given name.
190 * @param instance Instance to iterate on
191 * @param targetClass Class name to look for
192 * @return Class instance
194 @SuppressWarnings ("unchecked")
195 private Class<? extends FrameworkInterface> getClassFromTarget (final FrameworkInterface instance, final String targetClass) {
197 this.getLogger().debug(MessageFormat.format("instance={0},targetClass={1}", instance, targetClass)); //NOI18N
199 // Instance reflaction of this class
200 Class<? extends FrameworkInterface> c = instance.getClass();
203 while (!targetClass.equals(c.getSimpleName())) {
205 this.getLogger().debug(MessageFormat.format("c={0}", c.getSimpleName())); //NOI18N
207 // Get super class (causes unchecked warning)
208 c = (Class<? extends FrameworkInterface>) c.getSuperclass();
212 this.getLogger().trace(MessageFormat.format("c={0} - EXIT!", c)); //NOI18N
219 * Some "getter" for a Method instance from given method name
221 * @param instance Actual instance to call
222 * @param targetClass Target class name
223 * @param methodName Method name
224 * @return A Method instance
226 private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) {
228 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
230 // Get target class instance
231 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
233 // Init field instance
234 Method method = null;
236 // Use reflection to get all attributes
238 method = c.getDeclaredMethod(methodName, new Class<?>[0]);
239 } catch (final SecurityException | NoSuchMethodException ex) {
241 this.abortProgramWithException(ex);
245 assert (method instanceof Method) : "method is not a Method instance"; //NOI18N
248 this.getLogger().trace(MessageFormat.format("method={0} - EXIT!", method)); //NOI18N
255 * Setter for self instance
257 private void setSelfInstance () {
258 // Need to set it here
263 * Aborts program with given exception
265 * @param throwable Any type of Throwable
267 protected void abortProgramWithException (final Throwable throwable) {
269 this.getLogger().catching(throwable);
276 * Application instance
278 * @param application the application to set
280 protected final void setApplication (final Application application) {
281 this.application = application;
290 public final Client getClient () {
295 * Getter for bundle instance
297 * @return Resource bundle
299 protected final ResourceBundle getBundle () {
300 return BaseFrameworkSystem.bundle;
306 * @param client the client to set
308 protected final void setClient (final Client client) {
309 this.client = client;
313 * Name of used database table, handled over to backend
315 * @return the tableName
317 public final String getTableName () {
318 return this.tableName;
322 * Checks if given boolean field is available and set to same value
324 * @param columnName Column name to check
325 * @param bool Boolean value
326 * @return Whether all conditions are met
329 public boolean isValueEqual (final String columnName, final boolean bool) {
331 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
337 * @param exception Exception to log
340 public final void logException (final Throwable exception) {
341 // Log this exception
342 this.getLogger().catching(exception);
346 * Initializes properties with default values
348 private void initPropertiesWithDefault () {
350 this.getLogger().trace("CALLED!"); //NOI18N
352 // Init default values:
353 // Default database backend
354 BaseFrameworkSystem.properties.put("org.mxchange.database.backend.class", "org.mxchange.jcore.database.backend.base64.Base64CsvDatabaseBackend"); //NOI18N
357 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
358 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.dbname", "test"); //NOI18N
359 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.login", ""); //NOI18N
360 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.password", ""); //NOI18N
363 this.getLogger().trace("EXIT!"); //NOI18N
367 * Writes the properties file to disk
369 private void writePropertiesFile () {
371 this.getLogger().trace("CALLED!"); //NOI18N
375 BaseFrameworkSystem.properties.store(new PrintWriter(FrameworkInterface.PROPERTIES_CONFIG_FILE), "This file is automatically generated. You may wish to alter it."); //NOI18N
376 } catch (final IOException ex) {
377 this.abortProgramWithException(ex);
381 this.getLogger().trace("EXIT!"); //NOI18N
385 * Converts a column name like "foo_bar" to an attribute name like "fooBar"
387 * @param columnName Column name to convert
388 * @return Attribute name
390 protected String convertColumnNameToAttribute (final String columnName) {
392 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
394 // First all lower case
395 String lower = columnName.toLowerCase();
398 StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
401 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
407 while (tokenizer.hasMoreTokens()) {
409 String token = tokenizer.nextToken();
411 // Is later than first element?
413 // Make first character upper-case
414 char c = token.charAt(0);
415 token = String.valueOf(c).toUpperCase() + token.substring(1);
419 builder.append(token);
426 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
429 return builder.toString();
433 * Converts a column name like "foo_bar" to a method name like "getFooBar"
434 * for non-booleans and to "isFooBar" for boolean fields.
436 * @param columnName Column name to convert
437 * @param isBool Whether the parameter is boolean
438 * @return Attribute name
440 protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
442 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
445 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
448 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
453 builder.append("is"); //NOI18N
456 builder.append("get"); //NOI18N
460 while (tokenizer.hasMoreTokens()) {
462 String token = tokenizer.nextToken();
465 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
467 // Make it upper-case
468 char c = token.charAt(0);
469 token = String.valueOf(c).toUpperCase() + token.substring(1);
472 builder.append(token);
476 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
479 return builder.toString();
483 * Some "getter" for an array from given string and tokenizer
485 * @param str String to tokenize and get array from
486 * @param delimiter Delimiter
487 * @param size Size of array
488 * @return Array from tokenized string
489 * @todo Get rid of size parameter
491 protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
493 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
496 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
498 // Init array and index
499 String[] tokens = new String[size];
502 // Run through all tokens
503 while (tokenizer.hasMoreTokens()) {
504 // Get current token and add it
505 tokens[index] = tokenizer.nextToken();
508 this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
515 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
522 * Returns boolean field value from given method name by invoking it
524 * @param instance The instance to call
525 * @param targetClass Target class to look in
526 * @param methodName Method name to look for
527 * @return Boolean value from field
529 protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) {
531 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
533 // Get method instance
534 Method method = this.getMethodFromName(instance, targetClass, methodName);
536 // Get value from field
537 Boolean value = false;
540 value = (Boolean) method.invoke(instance);
541 } catch (final IllegalArgumentException | IllegalAccessException | InvocationTargetException ex) {
543 this.abortProgramWithException(ex);
553 * @param manager the manager instance to set
555 protected final void setContactManager (final Manageable manager) {
556 this.manager = manager;
560 * Returns any field value from given method name by invoking it
562 * @param instance The instance to call
563 * @param targetClass Target class to look in
564 * @param methodName Method name to look for
565 * @return Any value from field
567 protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) {
569 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
571 // Get method to call
572 Method method = this.getMethodFromName(instance, targetClass, methodName);
574 // Get value from field
575 Object object = null;
578 object = method.invoke(instance);
579 } catch (final IllegalArgumentException | IllegalAccessException | InvocationTargetException ex) {
581 this.abortProgramWithException(ex);
589 * Getter for property which must exist
591 * @param key Key to get
592 * @return Propety value
594 protected final String getProperty (final String key) {
595 return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.%s", key)); //NOI18N
599 * Name of used database table, handled over to backend
601 * @param tableName the tableName to set
603 protected final void setTableName (final String tableName) {
604 this.tableName = tableName;
608 * Converts null to empty string or leaves original string.
610 * @param str Any string
611 * @return Empty string if null or original string
613 protected Object convertNullToEmpty (final Object str) {
615 this.getLogger().trace(MessageFormat.format("str={0}", str)); //NOI18N
619 // Return empty string
624 this.getLogger().trace(MessageFormat.format("str={0} - EXIT!", str)); //NOI18N
631 * Creates an iterator from given instance and class name.
633 * @param instance Instance to run getter calls on
634 * @param className Class name to iterate over
635 * @return An iterator over all object's fields
637 protected Iterator<Map.Entry<Field, Object>> fieldIterator (final FrameworkInterface instance, final String className) {
639 this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className)); //NOI18N
641 // Get all attributes from given instance
642 Field[] fields = this.getClassFromTarget(instance, className).getDeclaredFields();
645 this.getLogger().debug(MessageFormat.format("Found {0} fields.", fields.length)); //NOI18N
647 // A simple map with K=fieldName and V=Value is fine
648 Map<Field, Object> map = new HashMap<>(fields.length);
651 for (final Field field : fields) {
653 this.getLogger().debug(MessageFormat.format("field={0}", field.getName())); //NOI18N
655 // Does the field start with "$"?
656 if (field.getName().startsWith("$")) { //NOI18N
658 this.getLogger().debug(MessageFormat.format("Skipping field={0} as it starts with a dollar character.", field.getName())); //NOI18N
665 this.getLogger().debug(MessageFormat.format("Calling getValueFromColumn({0}) on instance {1} ...", field.getName(), instance));
668 Object value = instance.getValueFromColumn(field.getName());
671 this.getLogger().debug(MessageFormat.format("Adding field={0},value={1}", field.getName(), value)); //NOI18N
674 map.put(field, value);
678 this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", map.size())); //NOI18N
680 // Return list iterator
681 return map.entrySet().iterator();
685 * Instance for database backend
687 * @return the backend
689 protected final DatabaseBackend getBackend () {
694 * Instance for database backend
696 * @param backend the backend to set
698 protected final void setBackend (final DatabaseBackend backend) {
699 this.backend = backend;
703 * Getter for Contact instance
705 * @return Contact instance
707 protected final Contact getContact () {
712 * Setter for Contact instance
714 * @param contact A Contact instance
716 protected final void setContact (final Contact contact) {
717 this.contact = contact;
721 * Getter for DatabaseFrontend instance
723 * @return DatabaseFrontend instance
725 protected final DatabaseFrontend getFrontend () {
730 * Setter for wrapper instance
732 * @param wrapper A DatabaseFrontend instance
734 protected final void setFrontend (final DatabaseFrontend wrapper) {
735 this.wrapper = wrapper;
739 * Initializes i18n bundles
741 protected void initBundle () {
742 // Is the bundle set?
743 if (bundle instanceof ResourceBundle) {
745 throw new IllegalStateException("called twice"); //NOI18N
749 bundle = ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE); // NOI18N
753 * Prepares all properties, the file is written if it is not found
755 protected void initProperties () {
757 this.getLogger().trace("CALLED!"); //NOI18N
760 this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
762 // Are some properties loaded?
763 if (!BaseFrameworkSystem.properties.isEmpty()) {
764 // Some are already loaded, abort here
770 BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
773 this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
774 } catch (final FileNotFoundException ex) {
776 this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
779 * The file is not found which is normal for first run, so
780 * initialize default values.
782 this.initPropertiesWithDefault();
785 this.writePropertiesFile();
786 } catch (final IOException ex) {
787 // Something else didn't work
788 this.abortProgramWithException(ex);
792 this.getLogger().trace("EXIT!"); //NOI18N
796 * Checks whether the given field is a boolean field by probing it.
798 * @param instance Instance to call
799 * @param targetClass Target class
800 * @param columnName Column name to check
801 * @return Whether the given column name represents a boolean field
803 protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
805 this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
807 // Convert column name to getter name (boolean)
808 String methodName = this.convertColumnNameToGetterMethod(columnName, true);
810 // Get class instance
811 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
813 // Defauzlt is boolean
814 boolean isBool = true;
817 // Now try to instance the method
818 Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
819 } catch (final NoSuchMethodException ex) {
821 this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
825 } catch (final SecurityException ex) {
827 this.abortProgramWithException(ex);
831 this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N
838 * Sets value in properties instance.
840 * @param key Property key (part) to set
841 * @param value Property value to set
843 protected void setProperty (final String key, final String value) {
845 this.getLogger().trace(MessageFormat.format("key={0},value={1} - CALLED!", key, value));
848 properties.setProperty(String.format("org.mxchange.%s", key), value);
851 this.getLogger().trace("EXIT!");
855 * Some getter for properties names (without org.mxchange)
857 * @return An array with property names
859 protected String[] getPropertyNames () {
862 "database.backend.class",
863 "database.mysql.login",
864 "database.mysql.host",
865 "database.mysql.password",
866 "database.mysql.dbname",