]> git.mxchange.org Git - jcore.git/blob - src/org/mxchange/jcore/BaseFrameworkSystem.java
Better compare this way:
[jcore.git] / src / org / mxchange / jcore / BaseFrameworkSystem.java
1 /*
2  * Copyright (C) 2015 Roland Haeder
3  *
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.
8  *
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.
13  *
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/>.
16  */
17 package org.mxchange.jcore;
18
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;
32 import java.util.Map;
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.database.storage.Storeable;
44 import org.mxchange.jcore.manager.Manageable;
45
46 /**
47  * General class
48  *
49  * @author Roland Haeder
50  */
51 public class BaseFrameworkSystem implements FrameworkInterface {
52
53         /**
54          * Bundle instance
55          */
56         private static ResourceBundle bundle;
57
58         /**
59          * Instance for own properties
60          */
61         private static final Properties properties = new Properties(System.getProperties());
62
63         /**
64          * Self instance
65          */
66         private static FrameworkInterface selfInstance;
67
68         /**
69          * Class' logger
70          */
71         private final Logger LOG;
72
73         /**
74          * Application instance
75          */
76         private Application application;
77
78         /**
79          * Instance for database backend
80          */
81         private DatabaseBackend backend;
82
83         /**
84          * Client instance
85          */
86         private Client client;
87
88         /**
89          * Contact instance
90          */
91         private Contact contact;
92
93         /**
94          * Manager instance
95          */
96         private Manageable manager;
97
98         /**
99          * Name of used database table, handled over to backend
100          */
101         private String tableName;
102
103         /**
104          * DatabaseFrontend instance
105          */
106         private DatabaseFrontend frontend;
107
108         /**
109          * Initialize object
110          */
111         {
112                 LOG = LogManager.getLogger(this);
113         }
114
115         /**
116          * No instances can be created of this class
117          */
118         protected BaseFrameworkSystem () {
119                 // Set own instance
120                 this.setSelfInstance();
121         }
122
123         /**
124          * Getter for this application
125          *
126          * @return Instance from this application
127          */
128         public static final FrameworkInterface getInstance () {
129                 // Return it
130                 return selfInstance;
131         }
132
133         /**
134          * Application instance
135          *
136          * @return the application
137          */
138         @Override
139         public final Application getApplication () {
140                 return this.application;
141         }
142
143         /**
144          * Getter for logger
145          *
146          * @return Logger
147          */
148         @Override
149         public final Logger getLogger () {
150                 return this.LOG;
151         }
152
153         /**
154          * Manager instance
155          *
156          * @return the contactManager
157          */
158         @Override
159         public final Manageable getManager () {
160                 return this.manager;
161         }
162
163         /**
164          * Getter for human-readable string from given key
165          *
166          * @param key Key to return
167          * @return Human-readable message
168          */
169         @Override
170         public final String getMessageStringFromKey (final String key) {
171                 // Return message
172                 return this.getBundle().getString(key);
173         }
174
175         /**
176          * Some "getter" for target class instance from given name.
177          *
178          * @param instance Instance to iterate on
179          * @param targetClass Class name to look for
180          * @return Class instance
181          */
182         @SuppressWarnings("unchecked")
183         private Class<? extends FrameworkInterface> getClassFromTarget (final FrameworkInterface instance, final String targetClass) {
184                 // Trace message
185                 this.getLogger().debug(MessageFormat.format("instance={0},targetClass={1}", instance, targetClass)); //NOI18N
186
187                 // Instance reflaction of this class
188                 Class<? extends FrameworkInterface> c = instance.getClass();
189
190                 // Analyze class
191                 while (!targetClass.equals(c.getSimpleName())) {
192                         // Debug message
193                         this.getLogger().debug(MessageFormat.format("c={0}", c.getSimpleName())); //NOI18N
194
195                         // Get super class (causes unchecked warning)
196                         c = (Class<? extends FrameworkInterface>) c.getSuperclass();
197                 }
198
199                 // Trace message
200                 this.getLogger().trace(MessageFormat.format("c={0} - EXIT!", c)); //NOI18N
201
202                 // Return it
203                 return c;
204         }
205
206         /**
207          * Some "getter" for a Method instance from given method name
208          *
209          * @param instance Actual instance to call
210          * @param targetClass Target class name
211          * @param methodName Method name
212          * @return A Method instance
213          */
214         private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException {
215                 // Trace messahe
216                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
217
218                 // Get target class instance
219                 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
220
221                 // Init field instance
222                 Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
223
224                 // Assert on field
225                 assert (method instanceof Method) : "method is not a Method instance"; //NOI18N
226
227                 // Trace message
228                 this.getLogger().trace(MessageFormat.format("method={0} - EXIT!", method)); //NOI18N
229
230                 // Return it
231                 return method;
232         }
233
234         /**
235          * Some "getter" for a Method instance from given method name
236          *
237          * @param instance Actual instance to call
238          * @param targetClass Target class name
239          * @param methodName Method name
240          * @param type Type reflection to check type from
241          * @return A Method instance
242          */
243         private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName, final Class<?> type) throws NoSuchMethodException {
244                 // Trace messahe
245                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1},type={2}", targetClass, methodName, type)); //NOI18N
246
247                 // Get target class instance
248                 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
249
250                 // Init field instance
251                 Method method = c.getDeclaredMethod(methodName, type);
252
253                 // Assert on field
254                 assert (method instanceof Method) : "method is not a Method instance"; //NOI18N
255
256                 // Trace message
257                 this.getLogger().trace(MessageFormat.format("method={0} - EXIT!", method)); //NOI18N
258
259                 // Return it
260                 return method;
261         }
262
263         /**
264          * Setter for self instance
265          */
266         private void setSelfInstance () {
267                 // Need to set it here
268                 selfInstance = this;
269         }
270
271         /**
272          * Aborts program with given exception
273          *
274          * @param throwable Any type of Throwable
275          */
276         protected final void abortProgramWithException (final Throwable throwable) {
277                 // Log exception ...
278                 this.logException(throwable);
279
280                 // .. and exit
281                 System.exit(1);
282         }
283
284         /**
285          * Application instance
286          *
287          * @param application the application to set
288          */
289         protected final void setApplication (final Application application) {
290                 this.application = application;
291         }
292
293         /**
294          * Client instance
295          *
296          * @return the client
297          */
298         @Override
299         public final Client getClient () {
300                 return this.client;
301         }
302
303         /**
304          * Getter for bundle instance
305          *
306          * @return Resource bundle
307          */
308         protected final ResourceBundle getBundle () {
309                 return BaseFrameworkSystem.bundle;
310         }
311
312         /**
313          * Setter for bundle instance
314          *
315          * @param bundle the bundle to set
316          */
317         protected static void setBundle (final ResourceBundle bundle) {
318                 BaseFrameworkSystem.bundle = bundle;
319         }
320
321         /**
322          * Client instance
323          *
324          * @param client the client to set
325          */
326         protected final void setClient (final Client client) {
327                 this.client = client;
328         }
329
330         /**
331          * Name of used database table, handled over to backend
332          *
333          * @return the tableName
334          */
335         public final String getTableName () {
336                 return this.tableName;
337         }
338
339         /**
340          * Checks if given boolean field is available and set to same value
341          *
342          * @param columnName Column name to check
343          * @param bool Boolean value
344          * @return Whether all conditions are met
345          * @throws NoSuchMethodException May be thrown by some implementations
346          * @throws java.lang.IllegalAccessException If the method cannot be accessed
347          * @throws java.lang.reflect.InvocationTargetException Any other problems?
348          */
349         @Override
350         public boolean isFieldValueEqual (final String columnName, final boolean bool) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
351                 // Not implemented
352                 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
353         }
354
355         /**
356          * Log exception
357          *
358          * @param exception Exception to log
359          */
360         @Override
361         public final void logException (final Throwable exception) {
362                 // Log this exception
363                 this.getLogger().catching(exception);
364         }
365
366         /**
367          * Initializes properties with default values
368          */
369         private void initPropertiesWithDefault () {
370                 // Trace message
371                 this.getLogger().trace("CALLED!"); //NOI18N
372
373                 // Init default values:
374                 // Default database backend
375                 BaseFrameworkSystem.properties.put("org.mxchange.database.backend.class", "org.mxchange.jcore.database.backend.base64.Base64CsvDatabaseBackend"); //NOI18N
376                 BaseFrameworkSystem.properties.put("org.mxchange.database.backend.storagepath", "data/"); //NOI18N
377                 BaseFrameworkSystem.properties.put("org.mxchange.database.datasource.name", ""); //NOI18N
378
379                 // For MySQL backend
380                 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
381                 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.dbname", "test"); //NOI18N
382                 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.login", ""); //NOI18N
383                 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.password", ""); //NOI18N
384
385                 // Trace message
386                 this.getLogger().trace("EXIT!"); //NOI18N
387         }
388
389         /**
390          * Writes the properties file to disk
391          */
392         private void writePropertiesFile () throws IOException {
393                 // Trace message
394                 this.getLogger().trace("CALLED!"); //NOI18N
395
396                 // Write it
397                 BaseFrameworkSystem.properties.store(new PrintWriter(FrameworkInterface.PROPERTIES_CONFIG_FILE), "This file is automatically generated. You may wish to alter it."); //NOI18N
398
399                 // Trace message
400                 this.getLogger().trace("EXIT!"); //NOI18N
401         }
402
403         /**
404          * Converts a column name like "foo_bar" to an attribute name like "fooBar"
405          *
406          * @param columnName Column name to convert
407          * @return Attribute name
408          */
409         protected String convertColumnNameToFieldName (final String columnName) {
410                 // Trace message
411                 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
412
413                 // First all lower case
414                 String lower = columnName.toLowerCase();
415
416                 // Then split on "_"
417                 StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
418
419                 // Resulting string
420                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
421
422                 // Init counter
423                 int count = 0;
424
425                 // Walk through all
426                 while (tokenizer.hasMoreTokens()) {
427                         // Get token
428                         String token = tokenizer.nextToken();
429
430                         // Is later than first element?
431                         if (count > 0) {
432                                 // Make first character upper-case
433                                 char c = token.charAt(0);
434                                 token = String.valueOf(c).toUpperCase() + token.substring(1);
435                         }
436
437                         // Add token
438                         builder.append(token);
439
440                         // Increment counter
441                         count++;
442                 }
443
444                 // Trace message
445                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
446
447                 // Return result
448                 return builder.toString();
449         }
450
451         /**
452          * Converts a column name like "foo_bar" to a method name like "getFooBar"
453          * for non-booleans and to "isFooBar" for boolean fields.
454          *
455          * @param columnName Column name to convert
456          * @param isBool Whether the parameter is boolean
457          * @return Attribute name
458          */
459         protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
460                 // Trace message
461                 this.getLogger().trace(MessageFormat.format("columnName={0},isBool={1} - CALLED!", columnName, isBool)); //NOI18N
462
463                 // Then split on "_"
464                 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
465
466                 // Resulting string
467                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
468
469                 // Is it boolean?
470                 if (isBool) {
471                         // Append "is"
472                         builder.append("is"); //NOI18N
473                 } else {
474                         // Append "get"
475                         builder.append("get"); //NOI18N
476                 }
477
478                 // Walk through all
479                 while (tokenizer.hasMoreTokens()) {
480                         // Get token
481                         String token = tokenizer.nextToken();
482
483                         // Debug message
484                         this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
485
486                         // Make it upper-case
487                         char c = token.charAt(0);
488                         token = String.valueOf(c).toUpperCase() + token.substring(1);
489
490                         // Add token
491                         builder.append(token);
492                 }
493
494                 // Trace message
495                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
496
497                 // Return result
498                 return builder.toString();
499         }
500
501         /**
502          * Converts a column name like "foo_bar" to a method name like "getFooBar"
503          * for non-booleans and to "isFooBar" for boolean fields.
504          *
505          * @param columnName Column name to convert
506          * @return Attribute name
507          */
508         protected String convertColumnNameToSetterMethod (final String columnName) {
509                 // Trace message
510                 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
511
512                 // Then split on "_"
513                 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
514
515                 // Resulting string
516                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
517
518                 // Append "set"
519                 builder.append("set"); //NOI18N
520
521                 // Walk through all
522                 while (tokenizer.hasMoreTokens()) {
523                         // Get token
524                         String token = tokenizer.nextToken();
525
526                         // Debug message
527                         this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
528
529                         // Make it upper-case
530                         char c = token.charAt(0);
531                         token = String.valueOf(c).toUpperCase() + token.substring(1);
532
533                         // Add token
534                         builder.append(token);
535                 }
536
537                 // Trace message
538                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
539
540                 // Return result
541                 return builder.toString();
542         }
543
544         /**
545          * Some "getter" for an array from given string and tokenizer
546          *
547          * @param str String to tokenize and get array from
548          * @param delimiter Delimiter
549          * @param size Size of array
550          * @return Array from tokenized string
551          * @todo Get rid of size parameter
552          */
553         protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
554                 // Trace message
555                 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
556
557                 // Get tokenizer
558                 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
559
560                 // Init array and index
561                 String[] tokens = new String[size];
562                 int index = 0;
563
564                 // Run through all tokens
565                 while (tokenizer.hasMoreTokens()) {
566                         // Get current token and add it
567                         tokens[index] = tokenizer.nextToken();
568
569                         // Debug message
570                         this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
571
572                         // Increment index
573                         index++;
574                 }
575
576                 // Trace message
577                 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
578
579                 // Return it
580                 return tokens;
581         }
582
583         /**
584          * Returns boolean field value from given method name by invoking it
585          *
586          * @param instance The instance to call
587          * @param targetClass Target class to look in
588          * @param methodName Method name to look for
589          * @return Boolean value from field
590          * @throws java.lang.NoSuchMethodException If the method was not found
591          * @throws java.lang.IllegalAccessException If the method cannot be accessed
592          * @throws java.lang.reflect.InvocationTargetException Some other problems?
593          */
594         protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
595                 // Trace messahe
596                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
597
598                 // Get method instance
599                 Method method = this.getMethodFromName(instance, targetClass, methodName);
600
601                 // Get value from field
602                 Boolean value = (Boolean) method.invoke(instance);
603
604                 // Trace message
605                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
606
607                 // Return value
608                 return value;
609         }
610
611         /**
612          * Sets boolean field value with given method name by invoking it
613          *
614          * @param instance The instance to call
615          * @param targetClass Target class to look in
616          * @param methodName Method name to look for
617          * @param columnName Column name
618          * @param value Boolean value from field
619          * @throws java.lang.NoSuchMethodException If the method was not found
620          * @throws java.lang.IllegalAccessException If the method cannot be accessed
621          * @throws java.lang.reflect.InvocationTargetException Some other problems?
622          */
623         protected void setBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName, final String columnName, final Boolean value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
624                 // Trace messahe
625                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
626
627                 // Get field type
628                 Class<?> type = this.getType(instance, targetClass, columnName);
629
630                 // Get method instance
631                 Method method = this.getMethodFromName(instance, targetClass, methodName, type);
632
633                 // Try to get the value by invoking the method
634                 method.invoke(instance, value);
635
636                 // Trace message
637                 this.getLogger().trace("EXIT!"); //NOI18N
638         }
639
640         /**
641          * Manager instance
642          *
643          * @param manager the manager instance to set
644          */
645         protected final void setContactManager (final Manageable manager) {
646                 this.manager = manager;
647         }
648
649         /**
650          * Returns any field value from given method name by invoking it
651          *
652          * @param instance The instance to call
653          * @param targetClass Target class to look in
654          * @param methodName Method name to look for
655          * @return Any value from field
656          * @throws java.lang.NoSuchMethodException If the method was not found
657          * @throws java.lang.IllegalAccessException If the method cannot be accessed
658          * @throws java.lang.reflect.InvocationTargetException Some other problems?
659          */
660         protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
661                 // Trace messahe
662                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},methodName={2}", instance, targetClass, methodName)); //NOI18N
663
664                 // Get method to call
665                 Method method = this.getMethodFromName(instance, targetClass, methodName);
666
667                 // Debug message
668                 this.getLogger().debug(MessageFormat.format("method={0},instance={1}", method, instance)); //NOI18N
669
670                 // Get value from field
671                 Object value = method.invoke(instance);
672
673                 // Trace messahe
674                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
675
676                 // Return value
677                 return value;
678         }
679
680         /**
681          * Sets any field value with given method name by invoking it
682          *
683          * @param instance The instance to call
684          * @param targetClass Target class to look in
685          * @param methodName Method name to look for
686          * @param columnName Column name
687          * @param value Any value from field
688          * @throws java.lang.NoSuchMethodException If the method was not found
689          * @throws java.lang.IllegalAccessException If the method cannot be accessed
690          * @throws java.lang.reflect.InvocationTargetException Some other problems?
691          */
692         protected void setField (final FrameworkInterface instance, final String targetClass, final String methodName, final String columnName, final Object value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
693                 // Trace messahe
694                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},methodName={2},value={3}", instance, targetClass, methodName, value)); //NOI18N
695
696                 // Get field type
697                 Class<?> type = this.getType(instance, targetClass, columnName);
698
699                 // Debug message
700                 this.getLogger().debug(MessageFormat.format("type={0}", type)); //NOI18N
701
702                 // Init object
703                 Object object = value;
704
705                 // Is the value null?
706                 if ("null".equals(value)) { //NOI18N
707                         // Warning message
708                         this.getLogger().warn(MessageFormat.format("columnName={0} has null value.", columnName)); //NOI18N
709
710                         // Set null
711                         object = null;
712                 } else {
713                         // Hard-coded "cast" again ... :-(
714                         // @TODO Can't we get rid of this???
715                         switch (type.getSimpleName()) {
716                                 case "Long": // Long object //NOI18N
717                                         object = Long.parseLong((String) value);
718                                         break;
719
720                                 case "Float": // Float object //NOI18N
721                                         object = Float.parseFloat((String) value);
722                                         break;
723
724                                 case "Boolean": // Boolean object //NOI18N
725                                         object = Boolean.parseBoolean((String) value);
726                                         break;
727
728                                 case "String": // String object //NOI18N
729                                         break;
730
731                                 default: // Unsupported type
732                                         throw new IllegalArgumentException(MessageFormat.format("value {0} has unsupported type {1}", value, type.getSimpleName())); //NOI18N
733                         }
734                 }
735
736                 // Debug message
737                 this.getLogger().debug(MessageFormat.format("object={0}", object)); //NOI18N
738
739                 // Get method to call
740                 Method method = this.getMethodFromName(instance, targetClass, methodName, type);
741
742                 // Debug message
743                 this.getLogger().debug(MessageFormat.format("method={0},instance={1},value[{2}]={3}", method, instance, value.getClass().getSimpleName(), value)); //NOI18N
744
745                 // Get value from field
746                 method.invoke(instance, object);
747
748                 // Trace messahe
749                 this.getLogger().trace("EXIT!"); //NOI18N
750         }
751
752         /**
753          * Getter for property which must exist
754          *
755          * @param key Key to get
756          * @return Propety value
757          */
758         protected final String getProperty (final String key) {
759                 return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.%s", key)); //NOI18N
760         }
761
762         /**
763          * Name of used database table, handled over to backend
764          *
765          * @param tableName the tableName to set
766          */
767         protected final void setTableName (final String tableName) {
768                 this.tableName = tableName;
769         }
770
771         /**
772          * Converts null to empty string or leaves original string.
773          *
774          * @param str Any string
775          * @return Empty string if null or original string
776          */
777         protected Object convertNullToEmpty (final Object str) {
778                 // Trace message
779                 this.getLogger().trace(MessageFormat.format("str={0}", str)); //NOI18N
780
781                 // Is it null?
782                 if (null == str) {
783                         // Return empty string
784                         return ""; //NOI18N
785                 }
786
787                 // Trace message
788                 this.getLogger().trace(MessageFormat.format("str={0} - EXIT!", str)); //NOI18N
789
790                 // Return it
791                 return str;
792         }
793
794         /**
795          * Creates an iterator from given instance and class name.
796          *
797          * @param instance Instance to run getter calls on
798          * @param className Class name to iterate over
799          * @return An iterator over all object's fields
800          * @throws java.lang.NoSuchMethodException If the called method does not exist
801          * @throws java.lang.IllegalAccessException If the method cannot be accessed
802          * @throws java.lang.reflect.InvocationTargetException Any other problems?
803          */
804         protected Iterator<Map.Entry<Field, Object>> fieldIterator (final Storeable instance, final String className) throws IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
805                 // Trace message
806                 this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className)); //NOI18N
807
808                 // Get all attributes from given instance
809                 Field[] fields = this.getClassFromTarget(instance, className).getDeclaredFields();
810
811                 // Debug message
812                 this.getLogger().debug(MessageFormat.format("Found {0} fields.", fields.length)); //NOI18N
813
814                 // A simple map with K=fieldName and V=Value is fine
815                 Map<Field, Object> map = new HashMap<>(fields.length);
816
817                 // Walk through all
818                 for (final Field field : fields) {
819                         // Debug log
820                         this.getLogger().debug(MessageFormat.format("field={0}", field.getName())); //NOI18N
821
822                         // Does the field start with "$"?
823                         if (field.getName().startsWith("$")) { //NOI18N
824                                 // Debug message
825                                 this.getLogger().debug(MessageFormat.format("Skipping field={0} as it starts with a dollar character.", field.getName())); //NOI18N
826
827                                 // Skip it silently
828                                 continue;
829                         }
830
831                         // Debug message
832                         this.getLogger().debug(MessageFormat.format("Calling getValueFromColumn({0}) on instance {1} ...", field.getName(), instance)); //NOI18N
833
834                         // Get value from it
835                         Object value = instance.getValueFromColumn(field.getName());
836
837                         // Debug message
838                         this.getLogger().debug(MessageFormat.format("Adding field={0},value={1}", field.getName(), value)); //NOI18N
839
840                         // Add it to list
841                         map.put(field, value);
842                 }
843
844                 // Debug message
845                 this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", map.size())); //NOI18N
846
847                 // Return list iterator
848                 return map.entrySet().iterator();
849         }
850
851         /**
852          * Instance for database backend
853          *
854          * @return the backend
855          */
856         protected final DatabaseBackend getBackend () {
857                 return this.backend;
858         }
859
860         /**
861          * Instance for database backend
862          *
863          * @param backend the backend to set
864          */
865         protected final void setBackend (final DatabaseBackend backend) {
866                 this.backend = backend;
867         }
868
869         /**
870          * Getter for Contact instance
871          *
872          * @return Contact instance
873          */
874         protected final Contact getContact () {
875                 return this.contact;
876         }
877
878         /**
879          * Setter for Contact instance
880          *
881          * @param contact A Contact instance
882          */
883         protected final void setContact (final Contact contact) {
884                 this.contact = contact;
885         }
886
887         /**
888          * Getter for DatabaseFrontend instance
889          *
890          * @return DatabaseFrontend instance
891          */
892         protected final DatabaseFrontend getFrontend () {
893                 return this.frontend;
894         }
895
896         /**
897          * Setter for wrapper instance
898          *
899          * @param frontend A DatabaseFrontend instance
900          */
901         protected final void setFrontend (final DatabaseFrontend frontend) {
902                 this.frontend = frontend;
903         }
904
905         /**
906          * Initializes i18n bundles
907          */
908         protected void initBundle () {
909                 // Trace message
910                 this.getLogger().trace("CALLED!"); //NOI18N
911
912                 // Is the bundle set?
913                 if (bundle instanceof ResourceBundle) {
914                         // Is already set
915                         throw new IllegalStateException("called twice"); //NOI18N
916                 }
917
918                 // Set instance
919                 setBundle(ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE)); // NOI18N
920
921                 // Trace message
922                 this.getLogger().trace("EXIT!"); //NOI18N
923         }
924
925         /**
926          * Prepares all properties, the file is written if it is not found
927          *
928          * @throws java.io.IOException If any IO problem occurs
929          */
930         protected void initProperties () throws IOException {
931                 // Trace message
932                 this.getLogger().trace("CALLED!"); //NOI18N
933
934                 // Debug message
935                 this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
936
937                 // Are some properties loaded?
938                 if (!BaseFrameworkSystem.properties.isEmpty()) {
939                         // Some are already loaded, abort here
940                         return;
941                 }
942
943                 try {
944                         // Try to read it
945                         BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
946
947                         // Debug message
948                         this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
949                 } catch (final FileNotFoundException ex) {
950                         // Debug message
951                         this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
952
953                         /*
954                          * The file is not found which is normal for first run, so
955                          * initialize default values.
956                          */
957                         this.initPropertiesWithDefault();
958
959                         // Write file
960                         this.writePropertiesFile();
961                 }
962
963                 // Trace message
964                 this.getLogger().trace("EXIT!"); //NOI18N
965         }
966
967         /**
968          * Checks whether the given field is a boolean field by probing it.
969          *
970          * @param instance Instance to call
971          * @param targetClass Target class
972          * @param columnName Column name to check
973          * @return Whether the given column name represents a boolean field
974          */
975         protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
976                 // Trace message
977                 this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
978
979                 // Convert column name to getter name (boolean)
980                 String methodName = this.convertColumnNameToGetterMethod(columnName, true);
981
982                 // Get class instance
983                 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
984
985                 // Defauzlt is boolean
986                 boolean isBool = true;
987
988                 try {
989                         // Now try to instance the method
990                         Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
991                 } catch (final NoSuchMethodException ex) {
992                         // Debug message
993                         this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
994
995                         // Not found
996                         isBool = false;
997                 }
998
999                 // Trace message
1000                 this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N
1001
1002                 // Return result
1003                 return isBool;
1004         }
1005
1006         /**
1007          * Sets value in properties instance.
1008          *
1009          * @param key Property key (part) to set
1010          * @param value Property value to set
1011          */
1012         protected void setProperty (final String key, final String value) {
1013                 // Trace message
1014                 this.getLogger().trace(MessageFormat.format("key={0},value={1} - CALLED!", key, value)); //NOI18N
1015
1016                 // Both should not be null
1017                 if (null == key) {
1018                         // key is null
1019                         throw new NullPointerException("key is null"); //NOI18N
1020                 } else if (null == value) {
1021                         // value is null
1022                         throw new NullPointerException("value is null"); //NOI18N
1023                 }
1024
1025                 // Set it
1026                 properties.setProperty(String.format("org.mxchange.%s", key), value); //NOI18N
1027
1028                 // Trace message
1029                 this.getLogger().trace("EXIT!"); //NOI18N
1030         }
1031
1032         /**
1033          * Some getter for properties names (without org.mxchange)
1034          *
1035          * @return An array with property names
1036          */
1037         protected String[] getPropertyNames () {
1038                 // Init array
1039                 String[] names = {
1040                         "database.backend.class", //NOI18N
1041                         "database.backend.storagepath", //NOI18N
1042                         "database.mysql.login", //NOI18N
1043                         "database.mysql.host", //NOI18N
1044                         "database.mysql.password", //NOI18N
1045                         "database.mysql.dbname", //NOI18N
1046                 };
1047
1048                 // Return it
1049                 return names;
1050         }
1051
1052         /**
1053          * Some "setter" for a value in given Storeable instance and target class
1054          * 
1055          * @param instance An instance of a Storeable class
1056          * @param targetClass The target class (where the field resides)
1057          * @param columnName Column name (= field name)
1058          * @param value Value to set
1059          * @throws java.lang.NoSuchMethodException If the setter is not found
1060          * @throws java.lang.IllegalAccessException If the setter cannot be accessed
1061          * @throws java.lang.reflect.InvocationTargetException Any other problem?
1062          */
1063         protected void setValueInStoreableFromColumn (final Storeable instance, final String targetClass, final String columnName, final Object value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
1064                 // Trace message
1065                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2},value={3} - CALLED!", instance, targetClass, columnName, value)); //NOI18N
1066
1067                 // A '$' means not our field
1068                 if (columnName.startsWith("$")) { //NOI18N
1069                         // Don't handle these
1070                         throw new IllegalArgumentException("columnsName contains $"); //NOI18N
1071                 }
1072
1073                 // Determine if the given column is boolean
1074                 if (this.isBooleanField(instance, targetClass, columnName)) {
1075                         // Debug message
1076                         this.getLogger().debug(MessageFormat.format("Column {0} represents a boolean field.", columnName)); //NOI18N
1077
1078                         // Yes, then call other method
1079                         this.setBooleanField(instance, targetClass, this.convertColumnNameToSetterMethod(columnName), columnName, (Boolean) value);
1080                 }
1081
1082                 // Convert column name to field name
1083                 String methodName = this.convertColumnNameToSetterMethod(columnName);
1084
1085                 // Debug message
1086                 this.getLogger().debug(MessageFormat.format("methodName={0}", methodName)); //NOI18N
1087
1088                 // Get field
1089                 this.setField(instance, targetClass, methodName, columnName, value);
1090
1091                 // Trace message
1092                 this.getLogger().trace("EXIT!"); //NOI18N
1093         }
1094
1095         /**
1096          * Some "getter" for a value from given Storeable instance and target class
1097          *
1098          * @param instance An instance of a Storeable class
1099          * @param targetClass The target class (where the field resides)
1100          * @param columnName Column name (= field name)
1101          * @return  value Value to get
1102          * @throws java.lang.NoSuchMethodException If the getter was not found
1103          * @throws java.lang.IllegalAccessException If the getter cannot be accessed
1104          * @throws java.lang.reflect.InvocationTargetException Some other problems?
1105          */
1106         protected Object getValueInStoreableFromColumn (final Storeable instance, final String targetClass, final String columnName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
1107                 // Trace message
1108                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
1109
1110                 // A '$' means not our field
1111                 if (columnName.startsWith("$")) { //NOI18N
1112                         // Don't handle these
1113                         throw new IllegalArgumentException("columnsName contains $"); //NOI18N
1114                 }
1115
1116                 // Determine if the given column is boolean
1117                 if (this.isBooleanField(instance, targetClass, columnName)) {
1118                         // Debug message
1119                         this.getLogger().debug(MessageFormat.format("Column {0} represents a boolean field.", columnName)); //NOI18N
1120
1121                         // Yes, then call other method
1122                         return this.getBooleanField(instance, targetClass, this.convertColumnNameToGetterMethod(columnName, true));
1123                 }
1124
1125                 // Convert column name to field name
1126                 String methodName = this.convertColumnNameToGetterMethod(columnName, false);
1127
1128                 // Debug message
1129                 this.getLogger().debug(MessageFormat.format("methodName={0}", methodName)); //NOI18N
1130
1131                 // Get field
1132                 Object value = this.getField(instance, targetClass, methodName);
1133
1134                 // Trace message
1135                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
1136
1137                 // Return value
1138                 return value;
1139         }
1140
1141         /**
1142          * Some getter for type reflection of given column name
1143          *
1144          * @param instance The instance to check
1145          * @param targetClass Target class to check
1146          * @param columnName Column name
1147          * @return Type reflection of value
1148          */
1149         private Class<?> getType (final FrameworkInterface instance, final String targetClass, final String columnName) {
1150                 // Trace message
1151                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
1152
1153                 // Init field tye
1154                 Class<?> type = null;
1155
1156                 // Get all attributes from given instance
1157                 Field[] fields = this.getClassFromTarget(instance, targetClass).getDeclaredFields();
1158
1159                 // Debug message
1160                 this.getLogger().debug(MessageFormat.format("fields()={0}", fields.length)); //NOI18N
1161
1162                 // Convert column_name to fieldName ;-)
1163                 String fieldName = this.convertColumnNameToFieldName(columnName);
1164
1165                 // Debug message
1166                 this.getLogger().debug(MessageFormat.format("fieldName={0}", fieldName)); //NOI18N
1167
1168                 // Search for proper field instance
1169                 for (final Field field : fields) {
1170                         // Debug message
1171                         this.getLogger().debug(MessageFormat.format("field.getName()={0},fieldName={1}", field.getName(), fieldName)); //NOI18N
1172
1173                         // Does it match?
1174                         if (field.getName().equals(fieldName)) {
1175                                 // Found it
1176                                 type = field.getType();
1177
1178                                 // Debug message
1179                                 this.getLogger().debug(MessageFormat.format("Found fieldName={0}: setting type={1}", fieldName, type.getSimpleName())); //NOI18N
1180
1181                                 // Don't continue with searching
1182                                 break;
1183                         }
1184                 }
1185
1186                 // Debug message
1187                 this.getLogger().debug(MessageFormat.format("type={0}", type));
1188
1189                 // type should not be null
1190                 if (null == type) {
1191                         // No null allowed
1192                         throw new NullPointerException("type is null"); //NOI18N
1193                 }
1194
1195                 // Trace message
1196                 this.getLogger().debug(MessageFormat.format("type={0} - EXIT!", type)); //NOI18N
1197
1198                 // Return it
1199                 return type;
1200         }
1201 }