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 final void abortProgramWithException (final Throwable throwable) {
269 this.getLogger().catching(throwable);
277 * Application instance
279 * @param application the application to set
281 protected final void setApplication (final Application application) {
282 this.application = application;
291 public final Client getClient () {
296 * Getter for bundle instance
298 * @return Resource bundle
300 protected final ResourceBundle getBundle () {
301 return BaseFrameworkSystem.bundle;
307 * @param client the client to set
309 protected final void setClient (final Client client) {
310 this.client = client;
314 * Name of used database table, handled over to backend
316 * @return the tableName
318 public final String getTableName () {
319 return this.tableName;
323 * Checks if given boolean field is available and set to same value
325 * @param columnName Column name to check
326 * @param bool Boolean value
327 * @return Whether all conditions are met
330 public boolean isValueEqual (final String columnName, final boolean bool) {
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
358 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
359 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.dbname", "test"); //NOI18N
360 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.login", ""); //NOI18N
361 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.password", ""); //NOI18N
364 this.getLogger().trace("EXIT!"); //NOI18N
368 * Writes the properties file to disk
370 private void writePropertiesFile () {
372 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
377 } catch (final IOException ex) {
378 this.abortProgramWithException(ex);
382 this.getLogger().trace("EXIT!"); //NOI18N
386 * Converts a column name like "foo_bar" to an attribute name like "fooBar"
388 * @param columnName Column name to convert
389 * @return Attribute name
391 protected String convertColumnNameToAttribute (final String columnName) {
393 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
395 // First all lower case
396 String lower = columnName.toLowerCase();
399 StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
402 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
408 while (tokenizer.hasMoreTokens()) {
410 String token = tokenizer.nextToken();
412 // Is later than first element?
414 // Make first character upper-case
415 char c = token.charAt(0);
416 token = String.valueOf(c).toUpperCase() + token.substring(1);
420 builder.append(token);
427 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
430 return builder.toString();
434 * Converts a column name like "foo_bar" to a method name like "getFooBar"
435 * for non-booleans and to "isFooBar" for boolean fields.
437 * @param columnName Column name to convert
438 * @param isBool Whether the parameter is boolean
439 * @return Attribute name
441 protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
443 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
446 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
449 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
454 builder.append("is"); //NOI18N
457 builder.append("get"); //NOI18N
461 while (tokenizer.hasMoreTokens()) {
463 String token = tokenizer.nextToken();
466 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
468 // Make it upper-case
469 char c = token.charAt(0);
470 token = String.valueOf(c).toUpperCase() + token.substring(1);
473 builder.append(token);
477 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
480 return builder.toString();
484 * Some "getter" for an array from given string and tokenizer
486 * @param str String to tokenize and get array from
487 * @param delimiter Delimiter
488 * @param size Size of array
489 * @return Array from tokenized string
490 * @todo Get rid of size parameter
492 protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
494 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
497 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
499 // Init array and index
500 String[] tokens = new String[size];
503 // Run through all tokens
504 while (tokenizer.hasMoreTokens()) {
505 // Get current token and add it
506 tokens[index] = tokenizer.nextToken();
509 this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
516 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
523 * Returns boolean field value from given method name by invoking it
525 * @param instance The instance to call
526 * @param targetClass Target class to look in
527 * @param methodName Method name to look for
528 * @return Boolean value from field
530 protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) {
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;
541 value = (Boolean) method.invoke(instance);
542 } catch (final IllegalArgumentException | IllegalAccessException | InvocationTargetException ex) {
544 this.abortProgramWithException(ex);
554 * @param manager the manager instance to set
556 protected final void setContactManager (final Manageable manager) {
557 this.manager = manager;
561 * Returns any field value from given method name by invoking it
563 * @param instance The instance to call
564 * @param targetClass Target class to look in
565 * @param methodName Method name to look for
566 * @return Any value from field
568 protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) {
570 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
572 // Get method to call
573 Method method = this.getMethodFromName(instance, targetClass, methodName);
575 // Get value from field
576 Object object = null;
579 object = method.invoke(instance);
580 } catch (final IllegalArgumentException | IllegalAccessException | InvocationTargetException ex) {
582 this.abortProgramWithException(ex);
590 * Getter for property which must exist
592 * @param key Key to get
593 * @return Propety value
595 protected final String getProperty (final String key) {
596 return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.%s", key)); //NOI18N
600 * Name of used database table, handled over to backend
602 * @param tableName the tableName to set
604 protected final void setTableName (final String tableName) {
605 this.tableName = tableName;
609 * Converts null to empty string or leaves original string.
611 * @param str Any string
612 * @return Empty string if null or original string
614 protected Object convertNullToEmpty (final Object str) {
616 this.getLogger().trace(MessageFormat.format("str={0}", str));
620 // Return empty string
625 this.getLogger().trace(MessageFormat.format("str={0} - EXIT!", str));
632 * Creates an iterator from given instance and class name.
634 * @param instance Instance to run getter calls on
635 * @param className Class name to iterate over
636 * @return An iterator over all object's fields
638 protected Iterator<Map.Entry<Field, Object>> fieldIterator (final FrameworkInterface instance, final String className) {
640 this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className));
642 // Get all attributes from given instance
643 Field[] fields = this.getClassFromTarget(instance, className).getDeclaredFields();
646 this.getLogger().debug(MessageFormat.format("Found {0} fields.", fields.length));
648 // A simple map with K=fieldName and V=Value is fine
649 Map<Field, Object> map = new HashMap<>(fields.length);
652 for (final Field field : fields) {
654 this.getLogger().debug(MessageFormat.format("field={0}", field.getName()));
656 // Does the field start with "$"?
657 if (field.getName().startsWith("$")) {
663 Object value = this.getValueFromColumn(field.getName());
666 this.getLogger().debug(MessageFormat.format("value={0}", value));
669 map.put(field, value);
673 this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", map.size()));
675 // Return list iterator
676 return map.entrySet().iterator();
680 * Instance for database backend
682 * @return the backend
684 protected final DatabaseBackend getBackend () {
689 * Instance for database backend
691 * @param backend the backend to set
693 protected final void setBackend (final DatabaseBackend backend) {
694 this.backend = backend;
698 * Getter for Contact instance
700 * @return Contact instance
702 protected final Contact getContact () {
707 * Setter for Contact instance
709 * @param contact A Contact instance
711 protected final void setContact (final Contact contact) {
712 this.contact = contact;
716 * Getter for DatabaseFrontend instance
718 * @return DatabaseFrontend instance
720 protected final DatabaseFrontend getFrontend () {
725 * Setter for wrapper instance
727 * @param wrapper A DatabaseFrontend instance
729 protected final void setFrontend (final DatabaseFrontend wrapper) {
730 this.wrapper = wrapper;
734 * Initializes i18n bundles
736 protected void initBundle () {
737 // Is the bundle set?
738 if (bundle instanceof ResourceBundle) {
740 throw new IllegalStateException("called twice");
744 bundle = ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE); // NOI18N
748 * Prepares all properties, the file is written if it is not found
750 protected void initProperties () {
752 this.getLogger().trace("CALLED!"); //NOI18N
755 this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
757 // Are some properties loaded?
758 if (!BaseFrameworkSystem.properties.isEmpty()) {
759 // Some are already loaded, abort here
765 BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
768 this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
769 } catch (final FileNotFoundException ex) {
771 this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
774 * The file is not found which is normal for first run, so
775 * initialize default values.
777 this.initPropertiesWithDefault();
780 this.writePropertiesFile();
781 } catch (final IOException ex) {
782 // Something else didn't work
783 this.abortProgramWithException(ex);
787 this.getLogger().trace("EXIT!"); //NOI18N
791 * Checks whether the given field is a boolean field by probing it.
793 * @param instance Instance to call
794 * @param targetClass Target class
795 * @param columnName Column name to check
796 * @return Whether the given column name represents a boolean field
798 protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
800 this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
802 // Convert column name to getter name (boolean)
803 String methodName = this.convertColumnNameToGetterMethod(columnName, true);
805 // Get class instance
806 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
808 // Defauzlt is boolean
809 boolean isBool = true;
812 // Now try to instance the method
813 Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
814 } catch (final NoSuchMethodException ex) {
816 this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
820 } catch (final SecurityException ex) {
822 this.abortProgramWithException(ex);
826 this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N