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.
181 * @throws NoSuchMethodException Some implementations may throw this.
184 public Object getValueFromColumn (final String columnName) throws IllegalArgumentException, NoSuchMethodException {
185 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0}", columnName)); //NOI18N
189 * Some "getter" for target class instance from given name.
191 * @param instance Instance to iterate on
192 * @param targetClass Class name to look for
193 * @return Class instance
195 @SuppressWarnings ("unchecked")
196 private Class<? extends FrameworkInterface> getClassFromTarget (final FrameworkInterface instance, final String targetClass) {
198 this.getLogger().debug(MessageFormat.format("instance={0},targetClass={1}", instance, targetClass)); //NOI18N
200 // Instance reflaction of this class
201 Class<? extends FrameworkInterface> c = instance.getClass();
204 while (!targetClass.equals(c.getSimpleName())) {
206 this.getLogger().debug(MessageFormat.format("c={0}", c.getSimpleName())); //NOI18N
208 // Get super class (causes unchecked warning)
209 c = (Class<? extends FrameworkInterface>) c.getSuperclass();
213 this.getLogger().trace(MessageFormat.format("c={0} - EXIT!", c)); //NOI18N
220 * Some "getter" for a Method instance from given method name
222 * @param instance Actual instance to call
223 * @param targetClass Target class name
224 * @param methodName Method name
225 * @return A Method instance
227 private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException {
229 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
231 // Get target class instance
232 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
234 // Init field instance
235 Method method = null;
237 // Use reflection to get all attributes
238 method = c.getDeclaredMethod(methodName, new Class<?>[0]);
241 assert (method instanceof Method) : "method is not a Method instance"; //NOI18N
244 this.getLogger().trace(MessageFormat.format("method={0} - EXIT!", method)); //NOI18N
251 * Setter for self instance
253 private void setSelfInstance () {
254 // Need to set it here
259 * Aborts program with given exception
261 * @param throwable Any type of Throwable
263 protected final void abortProgramWithException (final Throwable throwable) {
265 this.getLogger().catching(throwable);
272 * Application instance
274 * @param application the application to set
276 protected final void setApplication (final Application application) {
277 this.application = application;
286 public final Client getClient () {
291 * Getter for bundle instance
293 * @return Resource bundle
295 protected final ResourceBundle getBundle () {
296 return BaseFrameworkSystem.bundle;
302 * @param client the client to set
304 protected final void setClient (final Client client) {
305 this.client = client;
309 * Name of used database table, handled over to backend
311 * @return the tableName
313 public final String getTableName () {
314 return this.tableName;
318 * Checks if given boolean field is available and set to same value
320 * @param columnName Column name to check
321 * @param bool Boolean value
322 * @return Whether all conditions are met
323 * @throws NoSuchMethodException May be thrown by some implementations
326 public boolean isValueEqual (final String columnName, final boolean bool) throws NoSuchMethodException {
328 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
334 * @param exception Exception to log
337 public final void logException (final Throwable exception) {
338 // Log this exception
339 this.getLogger().catching(exception);
343 * Initializes properties with default values
345 private void initPropertiesWithDefault () {
347 this.getLogger().trace("CALLED!"); //NOI18N
349 // Init default values:
350 // Default database backend
351 BaseFrameworkSystem.properties.put("org.mxchange.database.backend.class", "org.mxchange.jcore.database.backend.base64.Base64CsvDatabaseBackend"); //NOI18N
352 BaseFrameworkSystem.properties.put("database.backend.storagepath", "data");
355 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
356 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.dbname", "test"); //NOI18N
357 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.login", ""); //NOI18N
358 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.password", ""); //NOI18N
361 this.getLogger().trace("EXIT!"); //NOI18N
365 * Writes the properties file to disk
367 private void writePropertiesFile () throws IOException {
369 this.getLogger().trace("CALLED!"); //NOI18N
372 BaseFrameworkSystem.properties.store(new PrintWriter(FrameworkInterface.PROPERTIES_CONFIG_FILE), "This file is automatically generated. You may wish to alter it."); //NOI18N
375 this.getLogger().trace("EXIT!"); //NOI18N
379 * Converts a column name like "foo_bar" to an attribute name like "fooBar"
381 * @param columnName Column name to convert
382 * @return Attribute name
384 protected String convertColumnNameToAttribute (final String columnName) {
386 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
388 // First all lower case
389 String lower = columnName.toLowerCase();
392 StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
395 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
401 while (tokenizer.hasMoreTokens()) {
403 String token = tokenizer.nextToken();
405 // Is later than first element?
407 // Make first character upper-case
408 char c = token.charAt(0);
409 token = String.valueOf(c).toUpperCase() + token.substring(1);
413 builder.append(token);
420 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
423 return builder.toString();
427 * Converts a column name like "foo_bar" to a method name like "getFooBar"
428 * for non-booleans and to "isFooBar" for boolean fields.
430 * @param columnName Column name to convert
431 * @param isBool Whether the parameter is boolean
432 * @return Attribute name
434 protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
436 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
439 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
442 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
447 builder.append("is"); //NOI18N
450 builder.append("get"); //NOI18N
454 while (tokenizer.hasMoreTokens()) {
456 String token = tokenizer.nextToken();
459 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
461 // Make it upper-case
462 char c = token.charAt(0);
463 token = String.valueOf(c).toUpperCase() + token.substring(1);
466 builder.append(token);
470 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
473 return builder.toString();
477 * Some "getter" for an array from given string and tokenizer
479 * @param str String to tokenize and get array from
480 * @param delimiter Delimiter
481 * @param size Size of array
482 * @return Array from tokenized string
483 * @todo Get rid of size parameter
485 protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
487 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
490 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
492 // Init array and index
493 String[] tokens = new String[size];
496 // Run through all tokens
497 while (tokenizer.hasMoreTokens()) {
498 // Get current token and add it
499 tokens[index] = tokenizer.nextToken();
502 this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
509 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
516 * Returns boolean field value from given method name by invoking it
518 * @param instance The instance to call
519 * @param targetClass Target class to look in
520 * @param methodName Method name to look for
521 * @return Boolean value from field
522 * @throws java.lang.NoSuchMethodException If the method was not found
523 * @throws java.lang.IllegalAccessException If the method cannot be accessed
524 * @throws java.lang.reflect.InvocationTargetException Some other problems?
526 protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
528 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
530 // Get method instance
531 Method method = this.getMethodFromName(instance, targetClass, methodName);
533 // Get value from field
534 Boolean value = false;
536 // Try to get the value by invoking the method
537 value = (Boolean) method.invoke(instance);
546 * @param manager the manager instance to set
548 protected final void setContactManager (final Manageable manager) {
549 this.manager = manager;
553 * Returns any field value from given method name by invoking it
555 * @param instance The instance to call
556 * @param targetClass Target class to look in
557 * @param methodName Method name to look for
558 * @return Any value from field
559 * @throws java.lang.NoSuchMethodException If the method was not found
560 * @throws java.lang.IllegalAccessException If the method cannot be accessed
561 * @throws java.lang.reflect.InvocationTargetException Some other problems?
563 protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
565 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
567 // Get method to call
568 Method method = this.getMethodFromName(instance, targetClass, methodName);
570 // Get value from field
571 Object object = method.invoke(instance);
578 * Getter for property which must exist
580 * @param key Key to get
581 * @return Propety value
583 protected final String getProperty (final String key) {
584 return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.%s", key)); //NOI18N
588 * Name of used database table, handled over to backend
590 * @param tableName the tableName to set
592 protected final void setTableName (final String tableName) {
593 this.tableName = tableName;
597 * Converts null to empty string or leaves original string.
599 * @param str Any string
600 * @return Empty string if null or original string
602 protected Object convertNullToEmpty (final Object str) {
604 this.getLogger().trace(MessageFormat.format("str={0}", str)); //NOI18N
608 // Return empty string
613 this.getLogger().trace(MessageFormat.format("str={0} - EXIT!", str)); //NOI18N
620 * Creates an iterator from given instance and class name.
622 * @param instance Instance to run getter calls on
623 * @param className Class name to iterate over
624 * @return An iterator over all object's fields
625 * @throws java.lang.NoSuchMethodException If the called method does not exist
627 protected Iterator<Map.Entry<Field, Object>> fieldIterator (final FrameworkInterface instance, final String className) throws IllegalArgumentException, NoSuchMethodException {
629 this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className)); //NOI18N
631 // Get all attributes from given instance
632 Field[] fields = this.getClassFromTarget(instance, className).getDeclaredFields();
635 this.getLogger().debug(MessageFormat.format("Found {0} fields.", fields.length)); //NOI18N
637 // A simple map with K=fieldName and V=Value is fine
638 Map<Field, Object> map = new HashMap<>(fields.length);
641 for (final Field field : fields) {
643 this.getLogger().debug(MessageFormat.format("field={0}", field.getName())); //NOI18N
645 // Does the field start with "$"?
646 if (field.getName().startsWith("$")) { //NOI18N
648 this.getLogger().debug(MessageFormat.format("Skipping field={0} as it starts with a dollar character.", field.getName())); //NOI18N
655 this.getLogger().debug(MessageFormat.format("Calling getValueFromColumn({0}) on instance {1} ...", field.getName(), instance));
658 Object value = instance.getValueFromColumn(field.getName());
661 this.getLogger().debug(MessageFormat.format("Adding field={0},value={1}", field.getName(), value)); //NOI18N
664 map.put(field, value);
668 this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", map.size())); //NOI18N
670 // Return list iterator
671 return map.entrySet().iterator();
675 * Instance for database backend
677 * @return the backend
679 protected final DatabaseBackend getBackend () {
684 * Instance for database backend
686 * @param backend the backend to set
688 protected final void setBackend (final DatabaseBackend backend) {
689 this.backend = backend;
693 * Getter for Contact instance
695 * @return Contact instance
697 protected final Contact getContact () {
702 * Setter for Contact instance
704 * @param contact A Contact instance
706 protected final void setContact (final Contact contact) {
707 this.contact = contact;
711 * Getter for DatabaseFrontend instance
713 * @return DatabaseFrontend instance
715 protected final DatabaseFrontend getFrontend () {
720 * Setter for wrapper instance
722 * @param wrapper A DatabaseFrontend instance
724 protected final void setFrontend (final DatabaseFrontend wrapper) {
725 this.wrapper = wrapper;
729 * Initializes i18n bundles
731 protected void initBundle () {
732 // Is the bundle set?
733 if (bundle instanceof ResourceBundle) {
735 throw new IllegalStateException("called twice"); //NOI18N
739 bundle = ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE); // NOI18N
743 * Prepares all properties, the file is written if it is not found
745 * @throws java.io.IOException If any IO problem occurs
747 protected void initProperties () throws IOException {
749 this.getLogger().trace("CALLED!"); //NOI18N
752 this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
754 // Are some properties loaded?
755 if (!BaseFrameworkSystem.properties.isEmpty()) {
756 // Some are already loaded, abort here
762 BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
765 this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
766 } catch (final FileNotFoundException ex) {
768 this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
771 * The file is not found which is normal for first run, so
772 * initialize default values.
774 this.initPropertiesWithDefault();
777 this.writePropertiesFile();
781 this.getLogger().trace("EXIT!"); //NOI18N
785 * Checks whether the given field is a boolean field by probing it.
787 * @param instance Instance to call
788 * @param targetClass Target class
789 * @param columnName Column name to check
790 * @return Whether the given column name represents a boolean field
792 protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
794 this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
796 // Convert column name to getter name (boolean)
797 String methodName = this.convertColumnNameToGetterMethod(columnName, true);
799 // Get class instance
800 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
802 // Defauzlt is boolean
803 boolean isBool = true;
806 // Now try to instance the method
807 Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
808 } catch (final NoSuchMethodException ex) {
810 this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
817 this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N
824 * Sets value in properties instance.
826 * @param key Property key (part) to set
827 * @param value Property value to set
829 protected void setProperty (final String key, final String value) {
831 this.getLogger().trace(MessageFormat.format("key={0},value={1} - CALLED!", key, value));
834 properties.setProperty(String.format("org.mxchange.%s", key), value);
837 this.getLogger().trace("EXIT!");
841 * Some getter for properties names (without org.mxchange)
843 * @return An array with property names
845 protected String[] getPropertyNames () {
848 "database.backend.class",
849 "database.backend.storagepath",
850 "database.mysql.login",
851 "database.mysql.host",
852 "database.mysql.password",
853 "database.mysql.dbname",