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.InvocationTargetException;
26 import java.lang.reflect.Method;
27 import java.text.MessageFormat;
28 import java.util.Arrays;
29 import java.util.Properties;
30 import java.util.ResourceBundle;
31 import java.util.StringTokenizer;
32 import org.apache.logging.log4j.LogManager;
33 import org.apache.logging.log4j.Logger;
34 import org.mxchange.jcore.application.Application;
35 import org.mxchange.jcore.client.Client;
36 import org.mxchange.jcore.database.frontend.DatabaseFrontend;
37 import org.mxchange.jcore.manager.Manageable;
42 * @author Roland Haeder
44 public class BaseFrameworkSystem implements FrameworkInterface {
47 * Instance for own properties
49 private static final Properties properties = new Properties(System.getProperties());
54 private final Logger LOG;
57 * Application instance
59 private Application application;
64 private static ResourceBundle bundle;
69 private Client client;
74 private Manageable manager;
77 * Name of used database table, handled over to backend
79 private String tableName;
82 * DatabaseFrontend instance
84 private DatabaseFrontend wrapper;
90 LOG = LogManager.getLogger(this);
94 * No instances can be created of this class
96 protected BaseFrameworkSystem () {
97 // Init properties file
98 this.initProperties();
102 * Initializes i18n bundles
104 protected void initBundle () {
105 // Is the bundle set?
106 if (bundle instanceof ResourceBundle) {
108 throw new IllegalStateException("called twice");
112 bundle = ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE); // NOI18N
116 * Application instance
118 * @return the application
121 public final Application getApplication () {
122 return this.application;
131 public final Client getClient () {
136 * Checks if given boolean field is available and set to same value
138 * @param columnName Column name to check
139 * @param bool Boolean value
140 * @return Whether all conditions are met
143 public boolean isValueEqual (final String columnName, final boolean bool) {
145 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
151 * @param exception Exception to log
154 public final void logException (final Throwable exception) {
155 // Log this exception
156 this.getLogger().catching(exception);
160 * Prepares all properties, the file is written if it is not found
162 private void initProperties () {
164 this.getLogger().trace("CALLED!"); //NOI18N
167 this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
169 // Are some properties loaded?
170 if (!BaseFrameworkSystem.properties.isEmpty()) {
171 // Some are already loaded, abort here
177 BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
180 this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
181 } catch (final FileNotFoundException ex) {
183 this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
186 * The file is not found which is normal for first run, so
187 * initialize default values.
189 this.initPropertiesWithDefault();
192 this.writePropertiesFile();
193 } catch (final IOException ex) {
194 // Something else didn't work
195 this.abortProgramWithException(ex);
199 this.getLogger().trace("EXIT!"); //NOI18N
203 * Initializes properties with default values
205 private void initPropertiesWithDefault () {
207 this.getLogger().trace("CALLED!"); //NOI18N
209 // Init default values:
210 // Default database backend
211 BaseFrameworkSystem.properties.put("org.mxchange.database.backendType", "base64csv"); //NOI18N
214 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
215 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.dbname", "test"); //NOI18N
216 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.login", ""); //NOI18N
217 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.password", ""); //NOI18N
220 this.getLogger().trace("EXIT!"); //NOI18N
224 * Writes the properties file to disk
226 private void writePropertiesFile () {
228 this.getLogger().trace("CALLED!"); //NOI18N
232 BaseFrameworkSystem.properties.store(new PrintWriter(FrameworkInterface.PROPERTIES_CONFIG_FILE), "This file is automatically generated. You may wish to alter it."); //NOI18N
233 } catch (final IOException ex) {
234 this.abortProgramWithException(ex);
238 this.getLogger().trace("EXIT!"); //NOI18N
242 * Converts a column name like "foo_bar" to an attribute name like "fooBar"
244 * @param columnName Column name to convert
245 * @return Attribute name
247 protected String convertColumnNameToAttribute (final String columnName) {
249 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
251 // First all lower case
252 String lower = columnName.toLowerCase();
255 StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
258 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
264 while (tokenizer.hasMoreTokens()) {
266 String token = tokenizer.nextToken();
268 // Is later than first element?
270 // Make first character upper-case
271 char c = token.charAt(0);
272 token = String.valueOf(c).toUpperCase() + token.substring(1);
276 builder.append(token);
283 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
286 return builder.toString();
290 * Converts a column name like "foo_bar" to a method name like "getFooBar"
291 * for non-booleans and to "isFooBar" for boolean fields.
293 * @param columnName Column name to convert
294 * @param isBool Whether the parameter is boolean
295 * @return Attribute name
297 protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
299 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
302 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
305 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
310 builder.append("is"); //NOI18N
313 builder.append("get"); //NOI18N
317 while (tokenizer.hasMoreTokens()) {
319 String token = tokenizer.nextToken();
322 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
324 // Make it upper-case
325 char c = token.charAt(0);
326 token = String.valueOf(c).toUpperCase() + token.substring(1);
329 builder.append(token);
333 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
336 return builder.toString();
340 * Some "getter" for an array from given string and tokenizer
342 * @param str String to tokenize and get array from
343 * @param delimiter Delimiter
344 * @param size Size of array
345 * @return Array from tokenized string
347 protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
349 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
352 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
354 // Init array and index
355 String[] tokens = new String[size];
358 // Run through all tokens
359 while (tokenizer.hasMoreTokens()) {
360 // Get current token and add it
361 tokens[index] = tokenizer.nextToken();
364 this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
371 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
378 * Returns boolean field value from given method call
380 * @param instance The instance to call
381 * @param targetClass Target class to look in
382 * @param methodName Method name to look for
383 * @return Boolean value from field
385 protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) {
387 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
389 // Get method instance
390 Method method = this.getMethodFromName(instance, targetClass, methodName);
392 // Get value from field
393 Boolean value = false;
396 value = (Boolean) method.invoke(instance);
397 } catch (final IllegalArgumentException ex) {
399 this.abortProgramWithException(ex);
400 } catch (final IllegalAccessException ex) {
402 this.abortProgramWithException(ex);
403 } catch (final InvocationTargetException ex) {
405 this.abortProgramWithException(ex);
415 * @param client the client to set
417 protected final void setClient (final Client client) {
418 this.client = client;
422 * Application instance
424 * @param application the application to set
426 protected final void setApplication (final Application application) {
427 this.application = application;
436 public final Logger getLogger () {
443 * @return the contactManager
446 public final Manageable getManager () {
451 * Getter for human-readable string from given key
453 * @param key Key to return
454 * @return Human-readable message
457 public final String getMessageStringFromKey (final String key) {
459 return this.getBundle().getString(key);
463 * Some "getter for a value from given column name. This name will be
464 * translated into a method name and then this method is called.
466 * @param columnName Column name
467 * @return Value from field
470 public Object getValueFromColumn (final String columnName) {
471 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0}", columnName)); //NOI18N
475 * Some "getter" for target class instance from given name.
477 * @param instance Instance to iterate on
478 * @param targetClass Class name to look for
479 * @return Class instance
481 @SuppressWarnings ("unchecked")
482 private Class<? extends FrameworkInterface> getClassFromTarget (final FrameworkInterface instance, final String targetClass) {
484 this.getLogger().debug(MessageFormat.format("instance={0},targetClass={1}", instance, targetClass)); //NOI18N
486 // Instance reflaction of this class
487 Class<? extends FrameworkInterface> c = instance.getClass();
490 while (!targetClass.equals(c.getSimpleName())) {
492 this.getLogger().debug(MessageFormat.format("c={0}", c.getSimpleName())); //NOI18N
494 // Get super class (causes unchecked warning)
495 c = (Class<? extends FrameworkInterface>) c.getSuperclass();
499 this.getLogger().trace(MessageFormat.format("c={0} - EXIT!", c)); //NOI18N
506 * Some "getter" for a Method instance from given method name
508 * @param instance Actual instance to call
509 * @param targetClass Target class name
510 * @param methodName Method name
511 * @return A Method instance
513 private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) {
515 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
517 // Get target class instance
518 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
520 // Init field instance
521 Method method = null;
523 // Use reflection to get all attributes
525 method = c.getDeclaredMethod(methodName, new Class<?>[0]);
526 } catch (final SecurityException ex) {
528 this.abortProgramWithException(ex);
529 } catch (final NoSuchMethodException ex) {
531 this.abortProgramWithException(ex);
535 assert (method instanceof Method) : "method is not a Method instance"; //NOI18N
538 this.getLogger().trace(MessageFormat.format("method={0} - EXIT!", method)); //NOI18N
545 * Aborts program with given exception
547 * @param throwable Any type of Throwable
549 protected final void abortProgramWithException (final Throwable throwable) {
551 this.getLogger().catching(throwable);
559 * Getter for bundle instance
561 * @return Resource bundle
563 protected final ResourceBundle getBundle () {
570 * @param manager the manager instance to set
572 protected final void setContactManager (final Manageable manager) {
573 this.manager = manager;
577 * Returns any field value from given method call
579 * @param instance The instance to call
580 * @param targetClass Target class to look in
581 * @param methodName Method name to look for
582 * @return Any value from field
584 protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) {
586 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
588 // Get method to call
589 Method method = this.getMethodFromName(instance, targetClass, methodName);
591 // Get value from field
592 Object object = null;
595 object = method.invoke(instance);
596 } catch (final IllegalArgumentException ex) {
598 this.abortProgramWithException(ex);
599 } catch (final IllegalAccessException ex) {
601 this.abortProgramWithException(ex);
602 } catch (final InvocationTargetException ex) {
604 this.abortProgramWithException(ex);
612 * Getter for property which must exist
614 * @param key Key to get
615 * @return Propety value
617 protected final String getProperty (final String key) {
618 return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.addressbook.%s", key)); //NOI18N
622 * Name of used database table, handled over to backend
624 * @return the tableName
626 protected final String getTableName () {
627 return this.tableName;
631 * Name of used database table, handled over to backend
633 * @param tableName the tableName to set
635 protected final void setTableName (final String tableName) {
636 this.tableName = tableName;
640 * Getter for DatabaseFrontend instance
642 * @return DatabaseFrontend instance
644 protected DatabaseFrontend getWrapper () {
649 * Setter for wrapper instance
651 * @param wrapper A DatabaseFrontend instance
653 protected void setWrapper (final DatabaseFrontend wrapper) {
654 this.wrapper = wrapper;
658 * Checks whether the given field is a boolean field by probing it.
660 * @param instance Instance to call
661 * @param targetClass Target class
662 * @param columnName Column name to check
663 * @return Whether the given column name represents a boolean field
665 protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
667 this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
669 // Convert column name to getter name (boolean)
670 String methodName = this.convertColumnNameToGetterMethod(columnName, true);
672 // Get class instance
673 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
675 // Defauzlt is boolean
676 boolean isBool = true;
679 // Now try to instance the method
680 Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
681 } catch (final NoSuchMethodException ex) {
683 this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
687 } catch (final SecurityException ex) {
689 this.abortProgramWithException(ex);
693 this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N