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 final 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);
91 bundle = ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE); // NOI18N
95 * No instances can be created of this class
97 protected BaseFrameworkSystem () {
98 // Init properties file
99 this.initProperties();
103 * Application instance
105 * @return the application
108 public final Application getApplication () {
109 return this.application;
118 public final Client getClient () {
123 * Checks if given boolean field is available and set to same value
125 * @param columnName Column name to check
126 * @param bool Boolean value
127 * @return Whether all conditions are met
130 public boolean isValueEqual (final String columnName, final boolean bool) {
132 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
138 * @param exception Exception to log
141 public final void logException (final Throwable exception) {
142 // Log this exception
143 this.getLogger().catching(exception);
147 * Prepares all properties, the file is written if it is not found
149 private void initProperties () {
151 this.getLogger().trace("CALLED!"); //NOI18N
154 this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
156 // Are some properties loaded?
157 if (!BaseFrameworkSystem.properties.isEmpty()) {
158 // Some are already loaded, abort here
164 BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
167 this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
168 } catch (final FileNotFoundException ex) {
170 this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
173 * The file is not found which is normal for first run, so
174 * initialize default values.
176 this.initPropertiesWithDefault();
179 this.writePropertiesFile();
180 } catch (final IOException ex) {
181 // Something else didn't work
182 this.abortProgramWithException(ex);
186 this.getLogger().trace("EXIT!"); //NOI18N
190 * Initializes properties with default values
192 private void initPropertiesWithDefault () {
194 this.getLogger().trace("CALLED!"); //NOI18N
196 // Init default values:
197 // Default database backend
198 BaseFrameworkSystem.properties.put("org.mxchange.database.backendType", "base64csv"); //NOI18N
201 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
202 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.dbname", "test"); //NOI18N
203 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.login", ""); //NOI18N
204 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.password", ""); //NOI18N
207 this.getLogger().trace("EXIT!"); //NOI18N
211 * Writes the properties file to disk
213 private void writePropertiesFile () {
215 this.getLogger().trace("CALLED!"); //NOI18N
219 BaseFrameworkSystem.properties.store(new PrintWriter(FrameworkInterface.PROPERTIES_CONFIG_FILE), "This file is automatically generated. You may wish to alter it."); //NOI18N
220 } catch (final IOException ex) {
221 this.abortProgramWithException(ex);
225 this.getLogger().trace("EXIT!"); //NOI18N
229 * Converts a column name like "foo_bar" to an attribute name like "fooBar"
231 * @param columnName Column name to convert
232 * @return Attribute name
234 protected String convertColumnNameToAttribute (final String columnName) {
236 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
238 // First all lower case
239 String lower = columnName.toLowerCase();
242 StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
245 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
251 while (tokenizer.hasMoreTokens()) {
253 String token = tokenizer.nextToken();
255 // Is later than first element?
257 // Make first character upper-case
258 char c = token.charAt(0);
259 token = String.valueOf(c).toUpperCase() + token.substring(1);
263 builder.append(token);
270 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
273 return builder.toString();
277 * Converts a column name like "foo_bar" to a method name like "getFooBar"
278 * for non-booleans and to "isFooBar" for boolean fields.
280 * @param columnName Column name to convert
281 * @param isBool Whether the parameter is boolean
282 * @return Attribute name
284 protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
286 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
289 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
292 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
297 builder.append("is"); //NOI18N
300 builder.append("get"); //NOI18N
304 while (tokenizer.hasMoreTokens()) {
306 String token = tokenizer.nextToken();
309 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
311 // Make it upper-case
312 char c = token.charAt(0);
313 token = String.valueOf(c).toUpperCase() + token.substring(1);
316 builder.append(token);
320 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
323 return builder.toString();
327 * Some "getter" for an array from given string and tokenizer
329 * @param str String to tokenize and get array from
330 * @param delimiter Delimiter
331 * @param size Size of array
332 * @return Array from tokenized string
334 protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
336 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
339 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
341 // Init array and index
342 String[] tokens = new String[size];
345 // Run through all tokens
346 while (tokenizer.hasMoreTokens()) {
347 // Get current token and add it
348 tokens[index] = tokenizer.nextToken();
351 this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
358 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
365 * Returns boolean field value from given method call
367 * @param instance The instance to call
368 * @param targetClass Target class to look in
369 * @param methodName Method name to look for
370 * @return Boolean value from field
372 protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) {
374 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
376 // Get method instance
377 Method method = this.getMethodFromName(instance, targetClass, methodName);
379 // Get value from field
380 Boolean value = false;
383 value = (Boolean) method.invoke(instance);
384 } catch (final IllegalArgumentException ex) {
386 this.abortProgramWithException(ex);
387 } catch (final IllegalAccessException ex) {
389 this.abortProgramWithException(ex);
390 } catch (final InvocationTargetException ex) {
392 this.abortProgramWithException(ex);
402 * @param client the client to set
404 protected final void setClient (final Client client) {
405 this.client = client;
409 * Application instance
411 * @param application the application to set
413 protected final void setApplication (final Application application) {
414 this.application = application;
423 public final Logger getLogger () {
430 * @return the contactManager
433 public final Manageable getManager () {
438 * Getter for human-readable string from given key
440 * @param key Key to return
441 * @return Human-readable message
444 public final String getMessageStringFromKey (final String key) {
446 return this.getBundle().getString(key);
450 * Some "getter for a value from given column name. This name will be
451 * translated into a method name and then this method is called.
453 * @param columnName Column name
454 * @return Value from field
457 public Object getValueFromColumn (final String columnName) {
458 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0}", columnName)); //NOI18N
462 * Some "getter" for target class instance from given name.
464 * @param instance Instance to iterate on
465 * @param targetClass Class name to look for
466 * @return Class instance
468 @SuppressWarnings ("unchecked")
469 private Class<? extends FrameworkInterface> getClassFromTarget (final FrameworkInterface instance, final String targetClass) {
471 this.getLogger().debug(MessageFormat.format("instance={0},targetClass={1}", instance, targetClass)); //NOI18N
473 // Instance reflaction of this class
474 Class<? extends FrameworkInterface> c = instance.getClass();
477 while (!targetClass.equals(c.getSimpleName())) {
479 this.getLogger().debug(MessageFormat.format("c={0}", c.getSimpleName())); //NOI18N
481 // Get super class (causes unchecked warning)
482 c = (Class<? extends FrameworkInterface>) c.getSuperclass();
486 this.getLogger().trace(MessageFormat.format("c={0} - EXIT!", c)); //NOI18N
493 * Some "getter" for a Method instance from given method name
495 * @param instance Actual instance to call
496 * @param targetClass Target class name
497 * @param methodName Method name
498 * @return A Method instance
500 private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) {
502 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
504 // Get target class instance
505 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
507 // Init field instance
508 Method method = null;
510 // Use reflection to get all attributes
512 method = c.getDeclaredMethod(methodName, new Class<?>[0]);
513 } catch (final SecurityException ex) {
515 this.abortProgramWithException(ex);
516 } catch (final NoSuchMethodException ex) {
518 this.abortProgramWithException(ex);
522 assert (method instanceof Method) : "method is not a Method instance"; //NOI18N
525 this.getLogger().trace(MessageFormat.format("method={0} - EXIT!", method)); //NOI18N
532 * Aborts program with given exception
534 * @param throwable Any type of Throwable
536 protected final void abortProgramWithException (final Throwable throwable) {
538 this.getLogger().catching(throwable);
546 * Getter for bundle instance
548 * @return Resource bundle
550 protected final ResourceBundle getBundle () {
557 * @param manager the manager instance to set
559 protected final void setContactManager (final Manageable manager) {
560 this.manager = manager;
564 * Returns any field value from given method call
566 * @param instance The instance to call
567 * @param targetClass Target class to look in
568 * @param methodName Method name to look for
569 * @return Any value from field
571 protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) {
573 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
575 // Get method to call
576 Method method = this.getMethodFromName(instance, targetClass, methodName);
578 // Get value from field
579 Object object = null;
582 object = method.invoke(instance);
583 } catch (final IllegalArgumentException ex) {
585 this.abortProgramWithException(ex);
586 } catch (final IllegalAccessException ex) {
588 this.abortProgramWithException(ex);
589 } catch (final InvocationTargetException ex) {
591 this.abortProgramWithException(ex);
599 * Getter for property which must exist
601 * @param key Key to get
602 * @return Propety value
604 protected final String getProperty (final String key) {
605 return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.addressbook.%s", key)); //NOI18N
609 * Name of used database table, handled over to backend
611 * @return the tableName
613 protected final String getTableName () {
614 return this.tableName;
618 * Name of used database table, handled over to backend
620 * @param tableName the tableName to set
622 protected final void setTableName (final String tableName) {
623 this.tableName = tableName;
627 * Getter for DatabaseFrontend instance
629 * @return DatabaseFrontend instance
631 protected DatabaseFrontend getWrapper () {
636 * Setter for wrapper instance
638 * @param wrapper A DatabaseFrontend instance
640 protected void setWrapper (final DatabaseFrontend wrapper) {
641 this.wrapper = wrapper;
645 * Checks whether the given field is a boolean field by probing it.
647 * @param instance Instance to call
648 * @param targetClass Target class
649 * @param columnName Column name to check
650 * @return Whether the given column name represents a boolean field
652 protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
654 this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
656 // Convert column name to getter name (boolean)
657 String methodName = this.convertColumnNameToGetterMethod(columnName, true);
659 // Get class instance
660 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
662 // Defauzlt is boolean
663 boolean isBool = true;
666 // Now try to instance the method
667 Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
668 } catch (final NoSuchMethodException ex) {
670 this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
674 } catch (final SecurityException ex) {
676 this.abortProgramWithException(ex);
680 this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N