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.ArrayList;
30 import java.util.Arrays;
31 import java.util.Iterator;
32 import java.util.List;
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.frontend.DatabaseFrontend;
42 import org.mxchange.jcore.manager.Manageable;
47 * @author Roland Haeder
49 public class BaseFrameworkSystem implements FrameworkInterface {
53 private static ResourceBundle bundle;
56 * Instance for own properties
58 private static final Properties properties = new Properties(System.getProperties());
63 private static FrameworkInterface selfInstance;
68 private final Logger LOG;
71 * Application instance
73 private Application application;
79 private Client client;
84 private Contact contact;
89 private Manageable manager;
92 * Name of used database table, handled over to backend
94 private String tableName;
97 * DatabaseFrontend instance
99 private DatabaseFrontend wrapper;
106 LOG = LogManager.getLogger(this);
110 * Getter for this application
112 * @return Instance from this application
114 public static final FrameworkInterface getInstance () {
120 * No instances can be created of this class
122 protected BaseFrameworkSystem () {
123 // Init properties file
124 this.initProperties();
127 this.setSelfInstance();
131 * Application instance
133 * @return the application
136 public final Application getApplication () {
137 return this.application;
146 public final Logger getLogger () {
153 * @return the contactManager
156 public final Manageable getManager () {
161 * Getter for human-readable string from given key
163 * @param key Key to return
164 * @return Human-readable message
167 public final String getMessageStringFromKey (final String key) {
169 return this.getBundle().getString(key);
173 * Some "getter for a value from given column name. This name will be
174 * translated into a method name and then this method is called.
176 * @param columnName Column name
177 * @return Value from field
180 public Object getValueFromColumn (final String columnName) {
181 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0}", columnName)); //NOI18N
185 * Some "getter" for target class instance from given name.
187 * @param instance Instance to iterate on
188 * @param targetClass Class name to look for
189 * @return Class instance
191 @SuppressWarnings ("unchecked")
192 private Class<? extends FrameworkInterface> getClassFromTarget (final FrameworkInterface instance, final String targetClass) {
194 this.getLogger().debug(MessageFormat.format("instance={0},targetClass={1}", instance, targetClass)); //NOI18N
196 // Instance reflaction of this class
197 Class<? extends FrameworkInterface> c = instance.getClass();
200 while (!targetClass.equals(c.getSimpleName())) {
202 this.getLogger().debug(MessageFormat.format("c={0}", c.getSimpleName())); //NOI18N
204 // Get super class (causes unchecked warning)
205 c = (Class<? extends FrameworkInterface>) c.getSuperclass();
209 this.getLogger().trace(MessageFormat.format("c={0} - EXIT!", c)); //NOI18N
216 * Some "getter" for a Method instance from given method name
218 * @param instance Actual instance to call
219 * @param targetClass Target class name
220 * @param methodName Method name
221 * @return A Method instance
223 private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) {
225 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
227 // Get target class instance
228 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
230 // Init field instance
231 Method method = null;
233 // Use reflection to get all attributes
235 method = c.getDeclaredMethod(methodName, new Class<?>[0]);
236 } catch (final SecurityException ex) {
238 this.abortProgramWithException(ex);
239 } catch (final 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 * Checks if given boolean field is available and set to same value
316 * @param columnName Column name to check
317 * @param bool Boolean value
318 * @return Whether all conditions are met
321 public boolean isValueEqual (final String columnName, final boolean bool) {
323 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
329 * @param exception Exception to log
332 public final void logException (final Throwable exception) {
333 // Log this exception
334 this.getLogger().catching(exception);
338 * Prepares all properties, the file is written if it is not found
340 private void initProperties () {
342 this.getLogger().trace("CALLED!"); //NOI18N
345 this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
347 // Are some properties loaded?
348 if (!BaseFrameworkSystem.properties.isEmpty()) {
349 // Some are already loaded, abort here
355 BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
358 this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
359 } catch (final FileNotFoundException ex) {
361 this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
364 * The file is not found which is normal for first run, so
365 * initialize default values.
367 this.initPropertiesWithDefault();
370 this.writePropertiesFile();
371 } catch (final IOException ex) {
372 // Something else didn't work
373 this.abortProgramWithException(ex);
377 this.getLogger().trace("EXIT!"); //NOI18N
381 * Initializes properties with default values
383 private void initPropertiesWithDefault () {
385 this.getLogger().trace("CALLED!"); //NOI18N
387 // Init default values:
388 // Default database backend
389 BaseFrameworkSystem.properties.put("org.mxchange.database.backendType", "base64csv"); //NOI18N
392 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
393 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.dbname", "test"); //NOI18N
394 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.login", ""); //NOI18N
395 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.password", ""); //NOI18N
398 this.getLogger().trace("EXIT!"); //NOI18N
402 * Writes the properties file to disk
404 private void writePropertiesFile () {
406 this.getLogger().trace("CALLED!"); //NOI18N
410 BaseFrameworkSystem.properties.store(new PrintWriter(FrameworkInterface.PROPERTIES_CONFIG_FILE), "This file is automatically generated. You may wish to alter it."); //NOI18N
411 } catch (final IOException ex) {
412 this.abortProgramWithException(ex);
416 this.getLogger().trace("EXIT!"); //NOI18N
420 * Converts a column name like "foo_bar" to an attribute name like "fooBar"
422 * @param columnName Column name to convert
423 * @return Attribute name
425 protected String convertColumnNameToAttribute (final String columnName) {
427 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
429 // First all lower case
430 String lower = columnName.toLowerCase();
433 StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
436 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
442 while (tokenizer.hasMoreTokens()) {
444 String token = tokenizer.nextToken();
446 // Is later than first element?
448 // Make first character upper-case
449 char c = token.charAt(0);
450 token = String.valueOf(c).toUpperCase() + token.substring(1);
454 builder.append(token);
461 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
464 return builder.toString();
468 * Converts a column name like "foo_bar" to a method name like "getFooBar"
469 * for non-booleans and to "isFooBar" for boolean fields.
471 * @param columnName Column name to convert
472 * @param isBool Whether the parameter is boolean
473 * @return Attribute name
475 protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
477 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
480 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
483 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
488 builder.append("is"); //NOI18N
491 builder.append("get"); //NOI18N
495 while (tokenizer.hasMoreTokens()) {
497 String token = tokenizer.nextToken();
500 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
502 // Make it upper-case
503 char c = token.charAt(0);
504 token = String.valueOf(c).toUpperCase() + token.substring(1);
507 builder.append(token);
511 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
514 return builder.toString();
518 * Some "getter" for an array from given string and tokenizer
520 * @param str String to tokenize and get array from
521 * @param delimiter Delimiter
522 * @param size Size of array
523 * @return Array from tokenized string
524 * @todo Get rid of size parameter
526 protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
528 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
531 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
533 // Init array and index
534 String[] tokens = new String[size];
537 // Run through all tokens
538 while (tokenizer.hasMoreTokens()) {
539 // Get current token and add it
540 tokens[index] = tokenizer.nextToken();
543 this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
550 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
557 * Returns boolean field value from given method call
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 Boolean value from field
564 protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) {
566 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
568 // Get method instance
569 Method method = this.getMethodFromName(instance, targetClass, methodName);
571 // Get value from field
572 Boolean value = false;
575 value = (Boolean) method.invoke(instance);
576 } catch (final IllegalArgumentException ex) {
578 this.abortProgramWithException(ex);
579 } catch (final IllegalAccessException ex) {
581 this.abortProgramWithException(ex);
582 } catch (final InvocationTargetException ex) {
584 this.abortProgramWithException(ex);
594 * @param manager the manager instance to set
596 protected final void setContactManager (final Manageable manager) {
597 this.manager = manager;
601 * Returns any field value from given method call
603 * @param instance The instance to call
604 * @param targetClass Target class to look in
605 * @param methodName Method name to look for
606 * @return Any value from field
608 protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) {
610 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
612 // Get method to call
613 Method method = this.getMethodFromName(instance, targetClass, methodName);
615 // Get value from field
616 Object object = null;
619 object = method.invoke(instance);
620 } catch (final IllegalArgumentException ex) {
622 this.abortProgramWithException(ex);
623 } catch (final IllegalAccessException ex) {
625 this.abortProgramWithException(ex);
626 } catch (final InvocationTargetException ex) {
628 this.abortProgramWithException(ex);
636 * Getter for property which must exist
638 * @param key Key to get
639 * @return Propety value
641 protected final String getProperty (final String key) {
642 return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.%s", key)); //NOI18N
646 * Name of used database table, handled over to backend
648 * @return the tableName
650 protected final String getTableName () {
651 return this.tableName;
655 * Name of used database table, handled over to backend
657 * @param tableName the tableName to set
659 protected final void setTableName (final String tableName) {
660 this.tableName = tableName;
664 * Getter for DatabaseFrontend instance
666 * @return DatabaseFrontend instance
668 protected final DatabaseFrontend getWrapper () {
673 * Setter for wrapper instance
675 * @param wrapper A DatabaseFrontend instance
677 protected final void setWrapper (final DatabaseFrontend wrapper) {
678 this.wrapper = wrapper;
682 * Getter for Contact instance
684 * @return Contact instance
686 protected final Contact getContact () {
691 * Setter for Contact instance
693 * @param contact A Contact instance
695 protected final void setContact (final Contact contact) {
696 this.contact = contact;
700 * Initializes i18n bundles
702 protected void initBundle () {
703 // Is the bundle set?
704 if (bundle instanceof ResourceBundle) {
706 throw new IllegalStateException("called twice");
710 bundle = ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE); // NOI18N
714 * Checks whether the given field is a boolean field by probing it.
716 * @param instance Instance to call
717 * @param targetClass Target class
718 * @param columnName Column name to check
719 * @return Whether the given column name represents a boolean field
721 protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
723 this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
725 // Convert column name to getter name (boolean)
726 String methodName = this.convertColumnNameToGetterMethod(columnName, true);
728 // Get class instance
729 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
731 // Defauzlt is boolean
732 boolean isBool = true;
735 // Now try to instance the method
736 Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
737 } catch (final NoSuchMethodException ex) {
739 this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
743 } catch (final SecurityException ex) {
745 this.abortProgramWithException(ex);
749 this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N
756 * Creates an iterator from given instance and class name. The class name
757 * is required in getValueFromColumn() to make a proper call.
759 * @param instance Instance to run getter calls on
760 * @param className Class name to iterate over
761 * @return An iterator over all object's fields
763 protected Iterator<Object> fieldIterator (final FrameworkInterface instance, final String className) {
765 this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className));
767 // Get all attributes from given instance
768 Field[] fields = instance.getClass().getDeclaredFields();
771 List<Object> list = new ArrayList<>(fields.length);
774 for (final Field field : fields) {
776 Object value = this.getValueFromColumn(field.getName());
779 assert(list.add(value)) : MessageFormat.format("value {0} has not been added", value);
783 this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", list.size()));
785 // Return list iterator
786 return list.iterator();