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.
182 * @throws java.lang.IllegalAccessException If the method cannot be accessed
183 * @throws java.lang.reflect.InvocationTargetException Any other problems?
186 public Object getValueFromColumn (final String columnName) throws IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
187 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0}", columnName)); //NOI18N
191 * Some "getter" for target class instance from given name.
193 * @param instance Instance to iterate on
194 * @param targetClass Class name to look for
195 * @return Class instance
197 @SuppressWarnings("unchecked")
198 private Class<? extends FrameworkInterface> getClassFromTarget (final FrameworkInterface instance, final String targetClass) {
200 this.getLogger().debug(MessageFormat.format("instance={0},targetClass={1}", instance, targetClass)); //NOI18N
202 // Instance reflaction of this class
203 Class<? extends FrameworkInterface> c = instance.getClass();
206 while (!targetClass.equals(c.getSimpleName())) {
208 this.getLogger().debug(MessageFormat.format("c={0}", c.getSimpleName())); //NOI18N
210 // Get super class (causes unchecked warning)
211 c = (Class<? extends FrameworkInterface>) c.getSuperclass();
215 this.getLogger().trace(MessageFormat.format("c={0} - EXIT!", c)); //NOI18N
222 * Some "getter" for a Method instance from given method name
224 * @param instance Actual instance to call
225 * @param targetClass Target class name
226 * @param methodName Method name
227 * @return A Method instance
229 private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException {
231 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
233 // Get target class instance
234 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
236 // Init field instance
237 Method method = null;
239 // Use reflection to get all attributes
240 method = c.getDeclaredMethod(methodName, new Class<?>[0]);
243 assert (method instanceof Method) : "method is not a Method instance"; //NOI18N
246 this.getLogger().trace(MessageFormat.format("method={0} - EXIT!", method)); //NOI18N
253 * Setter for self instance
255 private void setSelfInstance () {
256 // Need to set it here
261 * Aborts program with given exception
263 * @param throwable Any type of Throwable
265 protected final void abortProgramWithException (final Throwable throwable) {
267 this.getLogger().catching(throwable);
274 * Application instance
276 * @param application the application to set
278 protected final void setApplication (final Application application) {
279 this.application = application;
288 public final Client getClient () {
293 * Getter for bundle instance
295 * @return Resource bundle
297 protected final ResourceBundle getBundle () {
298 return BaseFrameworkSystem.bundle;
304 * @param client the client to set
306 protected final void setClient (final Client client) {
307 this.client = client;
311 * Name of used database table, handled over to backend
313 * @return the tableName
315 public final String getTableName () {
316 return this.tableName;
320 * Checks if given boolean field is available and set to same value
322 * @param columnName Column name to check
323 * @param bool Boolean value
324 * @return Whether all conditions are met
325 * @throws NoSuchMethodException May be thrown by some implementations
326 * @throws java.lang.IllegalAccessException If the method cannot be accessed
327 * @throws java.lang.reflect.InvocationTargetException Any other problems?
330 public boolean isFieldValueEqual (final String columnName, final boolean bool) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
332 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
338 * @param exception Exception to log
341 public final void logException (final Throwable exception) {
342 // Log this exception
343 this.getLogger().catching(exception);
347 * Initializes properties with default values
349 private void initPropertiesWithDefault () {
351 this.getLogger().trace("CALLED!"); //NOI18N
353 // Init default values:
354 // Default database backend
355 BaseFrameworkSystem.properties.put("org.mxchange.database.backend.class", "org.mxchange.jcore.database.backend.base64.Base64CsvDatabaseBackend"); //NOI18N
356 BaseFrameworkSystem.properties.put("database.backend.storagepath", "data/"); //NOI18N
359 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
360 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.dbname", "test"); //NOI18N
361 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.login", ""); //NOI18N
362 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.password", ""); //NOI18N
365 this.getLogger().trace("EXIT!"); //NOI18N
369 * Writes the properties file to disk
371 private void writePropertiesFile () throws IOException {
373 this.getLogger().trace("CALLED!"); //NOI18N
376 BaseFrameworkSystem.properties.store(new PrintWriter(FrameworkInterface.PROPERTIES_CONFIG_FILE), "This file is automatically generated. You may wish to alter it."); //NOI18N
379 this.getLogger().trace("EXIT!"); //NOI18N
383 * Converts a column name like "foo_bar" to an attribute name like "fooBar"
385 * @param columnName Column name to convert
386 * @return Attribute name
388 protected String convertColumnNameToAttribute (final String columnName) {
390 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
392 // First all lower case
393 String lower = columnName.toLowerCase();
396 StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
399 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
405 while (tokenizer.hasMoreTokens()) {
407 String token = tokenizer.nextToken();
409 // Is later than first element?
411 // Make first character upper-case
412 char c = token.charAt(0);
413 token = String.valueOf(c).toUpperCase() + token.substring(1);
417 builder.append(token);
424 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
427 return builder.toString();
431 * Converts a column name like "foo_bar" to a method name like "getFooBar"
432 * for non-booleans and to "isFooBar" for boolean fields.
434 * @param columnName Column name to convert
435 * @param isBool Whether the parameter is boolean
436 * @return Attribute name
438 protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
440 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
443 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
446 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
451 builder.append("is"); //NOI18N
454 builder.append("get"); //NOI18N
458 while (tokenizer.hasMoreTokens()) {
460 String token = tokenizer.nextToken();
463 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
465 // Make it upper-case
466 char c = token.charAt(0);
467 token = String.valueOf(c).toUpperCase() + token.substring(1);
470 builder.append(token);
474 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
477 return builder.toString();
481 * Some "getter" for an array from given string and tokenizer
483 * @param str String to tokenize and get array from
484 * @param delimiter Delimiter
485 * @param size Size of array
486 * @return Array from tokenized string
487 * @todo Get rid of size parameter
489 protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
491 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
494 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
496 // Init array and index
497 String[] tokens = new String[size];
500 // Run through all tokens
501 while (tokenizer.hasMoreTokens()) {
502 // Get current token and add it
503 tokens[index] = tokenizer.nextToken();
506 this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
513 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
520 * Returns boolean field value from given method name by invoking it
522 * @param instance The instance to call
523 * @param targetClass Target class to look in
524 * @param methodName Method name to look for
525 * @return Boolean value from field
526 * @throws java.lang.NoSuchMethodException If the method was not found
527 * @throws java.lang.IllegalAccessException If the method cannot be accessed
528 * @throws java.lang.reflect.InvocationTargetException Some other problems?
530 protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
532 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
534 // Get method instance
535 Method method = this.getMethodFromName(instance, targetClass, methodName);
537 // Get value from field
538 Boolean value = false;
540 // Try to get the value by invoking the method
541 value = (Boolean) method.invoke(instance);
550 * @param manager the manager instance to set
552 protected final void setContactManager (final Manageable manager) {
553 this.manager = manager;
557 * Returns any field value from given method name by invoking it
559 * @param instance The instance to call
560 * @param targetClass Target class to look in
561 * @param methodName Method name to look for
562 * @return Any value from field
563 * @throws java.lang.NoSuchMethodException If the method was not found
564 * @throws java.lang.IllegalAccessException If the method cannot be accessed
565 * @throws java.lang.reflect.InvocationTargetException Some other problems?
567 protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
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 = method.invoke(instance);
582 * Getter for property which must exist
584 * @param key Key to get
585 * @return Propety value
587 protected final String getProperty (final String key) {
588 return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.%s", key)); //NOI18N
592 * Name of used database table, handled over to backend
594 * @param tableName the tableName to set
596 protected final void setTableName (final String tableName) {
597 this.tableName = tableName;
601 * Converts null to empty string or leaves original string.
603 * @param str Any string
604 * @return Empty string if null or original string
606 protected Object convertNullToEmpty (final Object str) {
608 this.getLogger().trace(MessageFormat.format("str={0}", str)); //NOI18N
612 // Return empty string
617 this.getLogger().trace(MessageFormat.format("str={0} - EXIT!", str)); //NOI18N
624 * Creates an iterator from given instance and class name.
626 * @param instance Instance to run getter calls on
627 * @param className Class name to iterate over
628 * @return An iterator over all object's fields
629 * @throws java.lang.NoSuchMethodException If the called method does not exist
630 * @throws java.lang.IllegalAccessException If the method cannot be accessed
631 * @throws java.lang.reflect.InvocationTargetException Any other problems?
633 protected Iterator<Map.Entry<Field, Object>> fieldIterator (final FrameworkInterface instance, final String className) throws IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
635 this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className)); //NOI18N
637 // Get all attributes from given instance
638 Field[] fields = this.getClassFromTarget(instance, className).getDeclaredFields();
641 this.getLogger().debug(MessageFormat.format("Found {0} fields.", fields.length)); //NOI18N
643 // A simple map with K=fieldName and V=Value is fine
644 Map<Field, Object> map = new HashMap<>(fields.length);
647 for (final Field field : fields) {
649 this.getLogger().debug(MessageFormat.format("field={0}", field.getName())); //NOI18N
651 // Does the field start with "$"?
652 if (field.getName().startsWith("$")) { //NOI18N
654 this.getLogger().debug(MessageFormat.format("Skipping field={0} as it starts with a dollar character.", field.getName())); //NOI18N
661 this.getLogger().debug(MessageFormat.format("Calling getValueFromColumn({0}) on instance {1} ...", field.getName(), instance)); //NOI18N
664 Object value = instance.getValueFromColumn(field.getName());
667 this.getLogger().debug(MessageFormat.format("Adding field={0},value={1}", field.getName(), value)); //NOI18N
670 map.put(field, value);
674 this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", map.size())); //NOI18N
676 // Return list iterator
677 return map.entrySet().iterator();
681 * Instance for database backend
683 * @return the backend
685 protected final DatabaseBackend getBackend () {
690 * Instance for database backend
692 * @param backend the backend to set
694 protected final void setBackend (final DatabaseBackend backend) {
695 this.backend = backend;
699 * Getter for Contact instance
701 * @return Contact instance
703 protected final Contact getContact () {
708 * Setter for Contact instance
710 * @param contact A Contact instance
712 protected final void setContact (final Contact contact) {
713 this.contact = contact;
717 * Getter for DatabaseFrontend instance
719 * @return DatabaseFrontend instance
721 protected final DatabaseFrontend getFrontend () {
726 * Setter for wrapper instance
728 * @param wrapper A DatabaseFrontend instance
730 protected final void setFrontend (final DatabaseFrontend wrapper) {
731 this.wrapper = wrapper;
735 * Initializes i18n bundles
737 protected void initBundle () {
739 this.getLogger().trace("CALLED!");
741 // Is the bundle set?
742 if (bundle instanceof ResourceBundle) {
744 throw new IllegalStateException("called twice"); //NOI18N
748 bundle = ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE); // NOI18N
751 this.getLogger().trace("EXIT!");
755 * Prepares all properties, the file is written if it is not found
757 * @throws java.io.IOException If any IO problem occurs
759 protected void initProperties () throws IOException {
761 this.getLogger().trace("CALLED!"); //NOI18N
764 this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
766 // Are some properties loaded?
767 if (!BaseFrameworkSystem.properties.isEmpty()) {
768 // Some are already loaded, abort here
774 BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
777 this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
778 } catch (final FileNotFoundException ex) {
780 this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
783 * The file is not found which is normal for first run, so
784 * initialize default values.
786 this.initPropertiesWithDefault();
789 this.writePropertiesFile();
793 this.getLogger().trace("EXIT!"); //NOI18N
797 * Checks whether the given field is a boolean field by probing it.
799 * @param instance Instance to call
800 * @param targetClass Target class
801 * @param columnName Column name to check
802 * @return Whether the given column name represents a boolean field
804 protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
806 this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
808 // Convert column name to getter name (boolean)
809 String methodName = this.convertColumnNameToGetterMethod(columnName, true);
811 // Get class instance
812 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
814 // Defauzlt is boolean
815 boolean isBool = true;
818 // Now try to instance the method
819 Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
820 } catch (final NoSuchMethodException ex) {
822 this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
829 this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N
836 * Sets value in properties instance.
838 * @param key Property key (part) to set
839 * @param value Property value to set
841 protected void setProperty (final String key, final String value) {
843 this.getLogger().trace(MessageFormat.format("key={0},value={1} - CALLED!", key, value)); //NOI18N
845 // Both should not be null
848 throw new NullPointerException("key is null");
849 } else if (value == null) {
851 throw new NullPointerException("value is null");
855 properties.setProperty(String.format("org.mxchange.%s", key), value); //NOI18N
858 this.getLogger().trace("EXIT!"); //NOI18N
862 * Some getter for properties names (without org.mxchange)
864 * @return An array with property names
866 protected String[] getPropertyNames () {
869 "database.backend.class", //NOI18N
870 "database.backend.storagepath", //NOI18N
871 "database.mysql.login", //NOI18N
872 "database.mysql.host", //NOI18N
873 "database.mysql.password", //NOI18N
874 "database.mysql.dbname", //NOI18N