]> git.mxchange.org Git - jcore.git/blob - src/org/mxchange/jcore/BaseFrameworkSystem.java
Replace multiple-added strings/objects into MessageFormat.format() call to reduce...
[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 wrapper;
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.getLogger().catching(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          * Client instance
314          *
315          * @param client the client to set
316          */
317         protected final void setClient (final Client client) {
318                 this.client = client;
319         }
320
321         /**
322          * Name of used database table, handled over to backend
323          *
324          * @return the tableName
325          */
326         public final String getTableName () {
327                 return this.tableName;
328         }
329
330         /**
331          * Checks if given boolean field is available and set to same value
332          *
333          * @param columnName Column name to check
334          * @param bool Boolean value
335          * @return Whether all conditions are met
336          * @throws NoSuchMethodException May be thrown by some implementations
337          * @throws java.lang.IllegalAccessException If the method cannot be accessed
338          * @throws java.lang.reflect.InvocationTargetException Any other problems?
339          */
340         @Override
341         public boolean isFieldValueEqual (final String columnName, final boolean bool) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
342                 // Not implemented
343                 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
344         }
345
346         /**
347          * Log exception
348          *
349          * @param exception Exception to log
350          */
351         @Override
352         public final void logException (final Throwable exception) {
353                 // Log this exception
354                 this.getLogger().catching(exception);
355         }
356
357         /**
358          * Initializes properties with default values
359          */
360         private void initPropertiesWithDefault () {
361                 // Trace message
362                 this.getLogger().trace("CALLED!"); //NOI18N
363
364                 // Init default values:
365                 // Default database backend
366                 BaseFrameworkSystem.properties.put("org.mxchange.database.backend.class", "org.mxchange.jcore.database.backend.base64.Base64CsvDatabaseBackend"); //NOI18N
367                 BaseFrameworkSystem.properties.put("database.backend.storagepath", "data/"); //NOI18N
368
369                 // For MySQL backend
370                 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.host", "localhost"); //NOI18N
371                 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.dbname", "test"); //NOI18N
372                 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.login", ""); //NOI18N
373                 BaseFrameworkSystem.properties.put("org.mxchange.database.mysql.password", ""); //NOI18N
374
375                 // Trace message
376                 this.getLogger().trace("EXIT!"); //NOI18N
377         }
378
379         /**
380          * Writes the properties file to disk
381          */
382         private void writePropertiesFile () throws IOException {
383                 // Trace message
384                 this.getLogger().trace("CALLED!"); //NOI18N
385
386                 // Write it
387                 BaseFrameworkSystem.properties.store(new PrintWriter(FrameworkInterface.PROPERTIES_CONFIG_FILE), "This file is automatically generated. You may wish to alter it."); //NOI18N
388
389                 // Trace message
390                 this.getLogger().trace("EXIT!"); //NOI18N
391         }
392
393         /**
394          * Converts a column name like "foo_bar" to an attribute name like "fooBar"
395          *
396          * @param columnName Column name to convert
397          * @return Attribute name
398          */
399         protected String convertColumnNameToAttribute (final String columnName) {
400                 // Trace message
401                 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
402
403                 // First all lower case
404                 String lower = columnName.toLowerCase();
405
406                 // Then split on "_"
407                 StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
408
409                 // Resulting string
410                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
411
412                 // Init counter
413                 int count = 0;
414
415                 // Walk through all
416                 while (tokenizer.hasMoreTokens()) {
417                         // Get token
418                         String token = tokenizer.nextToken();
419
420                         // Is later than first element?
421                         if (count > 0) {
422                                 // Make first character upper-case
423                                 char c = token.charAt(0);
424                                 token = String.valueOf(c).toUpperCase() + token.substring(1);
425                         }
426
427                         // Add token
428                         builder.append(token);
429
430                         // Increment counter
431                         count++;
432                 }
433
434                 // Trace message
435                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
436
437                 // Return result
438                 return builder.toString();
439         }
440
441         /**
442          * Converts a column name like "foo_bar" to a method name like "getFooBar"
443          * for non-booleans and to "isFooBar" for boolean fields.
444          *
445          * @param columnName Column name to convert
446          * @param isBool Whether the parameter is boolean
447          * @return Attribute name
448          */
449         protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
450                 // Trace message
451                 this.getLogger().trace(MessageFormat.format("columnName={0},isBool={1} - CALLED!", columnName, isBool)); //NOI18N
452
453                 // Then split on "_"
454                 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
455
456                 // Resulting string
457                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
458
459                 // Is it boolean?
460                 if (isBool) {
461                         // Append "is"
462                         builder.append("is"); //NOI18N
463                 } else {
464                         // Append "get"
465                         builder.append("get"); //NOI18N
466                 }
467
468                 // Walk through all
469                 while (tokenizer.hasMoreTokens()) {
470                         // Get token
471                         String token = tokenizer.nextToken();
472
473                         // Debug message
474                         this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
475
476                         // Make it upper-case
477                         char c = token.charAt(0);
478                         token = String.valueOf(c).toUpperCase() + token.substring(1);
479
480                         // Add token
481                         builder.append(token);
482                 }
483
484                 // Trace message
485                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
486
487                 // Return result
488                 return builder.toString();
489         }
490
491         /**
492          * Converts a column name like "foo_bar" to a method name like "getFooBar"
493          * for non-booleans and to "isFooBar" for boolean fields.
494          *
495          * @param columnName Column name to convert
496          * @return Attribute name
497          */
498         protected String convertColumnNameToSetterMethod (final String columnName) {
499                 // Trace message
500                 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
501
502                 // Then split on "_"
503                 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
504
505                 // Resulting string
506                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
507
508                 // Append "set"
509                 builder.append("set"); //NOI18N
510
511                 // Walk through all
512                 while (tokenizer.hasMoreTokens()) {
513                         // Get token
514                         String token = tokenizer.nextToken();
515
516                         // Debug message
517                         this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
518
519                         // Make it upper-case
520                         char c = token.charAt(0);
521                         token = String.valueOf(c).toUpperCase() + token.substring(1);
522
523                         // Add token
524                         builder.append(token);
525                 }
526
527                 // Trace message
528                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
529
530                 // Return result
531                 return builder.toString();
532         }
533
534         /**
535          * Some "getter" for an array from given string and tokenizer
536          *
537          * @param str String to tokenize and get array from
538          * @param delimiter Delimiter
539          * @param size Size of array
540          * @return Array from tokenized string
541          * @todo Get rid of size parameter
542          */
543         protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
544                 // Trace message
545                 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
546
547                 // Get tokenizer
548                 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
549
550                 // Init array and index
551                 String[] tokens = new String[size];
552                 int index = 0;
553
554                 // Run through all tokens
555                 while (tokenizer.hasMoreTokens()) {
556                         // Get current token and add it
557                         tokens[index] = tokenizer.nextToken();
558
559                         // Debug message
560                         this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
561
562                         // Increment index
563                         index++;
564                 }
565
566                 // Trace message
567                 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
568
569                 // Return it
570                 return tokens;
571         }
572
573         /**
574          * Returns boolean field value from given method name by invoking it
575          *
576          * @param instance The instance to call
577          * @param targetClass Target class to look in
578          * @param methodName Method name to look for
579          * @return Boolean value from field
580          * @throws java.lang.NoSuchMethodException If the method was not found
581          * @throws java.lang.IllegalAccessException If the method cannot be accessed
582          * @throws java.lang.reflect.InvocationTargetException Some other problems?
583          */
584         protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
585                 // Trace messahe
586                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
587
588                 // Get method instance
589                 Method method = this.getMethodFromName(instance, targetClass, methodName);
590
591                 // Get value from field
592                 Boolean value = (Boolean) method.invoke(instance);
593
594                 // Trace message
595                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
596
597                 // Return value
598                 return value;
599         }
600
601         /**
602          * Sets boolean field value with given method name by invoking it
603          *
604          * @param instance The instance to call
605          * @param targetClass Target class to look in
606          * @param methodName Method name to look for
607          * @param columnName Column name
608          * @param value Boolean value from field
609          * @throws java.lang.NoSuchMethodException If the method was not found
610          * @throws java.lang.IllegalAccessException If the method cannot be accessed
611          * @throws java.lang.reflect.InvocationTargetException Some other problems?
612          */
613         protected void setBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName, final String columnName, final Boolean value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
614                 // Trace messahe
615                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
616
617                 // Get field type
618                 Class<?> type = this.getType(instance, targetClass, columnName);
619
620                 // Get method instance
621                 Method method = this.getMethodFromName(instance, targetClass, methodName, type);
622
623                 // Try to get the value by invoking the method
624                 method.invoke(instance, value);
625
626                 // Trace message
627                 this.getLogger().trace("EXIT!"); //NOI18N
628         }
629
630         /**
631          * Manager instance
632          *
633          * @param manager the manager instance to set
634          */
635         protected final void setContactManager (final Manageable manager) {
636                 this.manager = manager;
637         }
638
639         /**
640          * Returns any field value from given method name by invoking it
641          *
642          * @param instance The instance to call
643          * @param targetClass Target class to look in
644          * @param methodName Method name to look for
645          * @return Any value from field
646          * @throws java.lang.NoSuchMethodException If the method was not found
647          * @throws java.lang.IllegalAccessException If the method cannot be accessed
648          * @throws java.lang.reflect.InvocationTargetException Some other problems?
649          */
650         protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
651                 // Trace messahe
652                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},methodName={2}", instance, targetClass, methodName)); //NOI18N
653
654                 // Get method to call
655                 Method method = this.getMethodFromName(instance, targetClass, methodName);
656
657                 // Debug message
658                 this.getLogger().debug(MessageFormat.format("method={0},instance={1}", method, instance)); //NOI18N
659
660                 // Get value from field
661                 Object value = method.invoke(instance);
662
663                 // Trace messahe
664                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
665
666                 // Return value
667                 return value;
668         }
669
670         /**
671          * Sets any field value with given method name by invoking it
672          *
673          * @param instance The instance to call
674          * @param targetClass Target class to look in
675          * @param methodName Method name to look for
676          * @param columnName Column name
677          * @param value Any value from field
678          * @throws java.lang.NoSuchMethodException If the method was not found
679          * @throws java.lang.IllegalAccessException If the method cannot be accessed
680          * @throws java.lang.reflect.InvocationTargetException Some other problems?
681          */
682         protected void setField (final FrameworkInterface instance, final String targetClass, final String methodName, final String columnName, final Object value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
683                 // Trace messahe
684                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},methodName={2},value={3}", instance, targetClass, methodName, value)); //NOI18N
685
686                 // Get field type
687                 Class<?> type = this.getType(instance, targetClass, columnName);
688
689                 // Debug message
690                 this.getLogger().debug(MessageFormat.format("type={0}", type)); //NOI18N
691
692                 // Init object
693                 Object object = value;
694
695                 // Hard-coded "cast" again ... :-(
696                 // @TODO Can't we get rid of this???
697                 switch (type.getSimpleName()) {
698                         case "Long": // Long object //NOI18N
699                                 object = Long.parseLong((String) value);
700                                 break;
701
702                         case "Float": // Float object //NOI18N
703                                 object = Float.parseFloat((String) value);
704                                 break;
705
706                         case "Boolean": // Boolean object //NOI18N
707                                 object = Boolean.parseBoolean((String) value);
708                                 break;
709
710                         case "String": // String object //NOI18N
711                                 break;
712
713                         default: // Unsupported type
714                                 throw new IllegalArgumentException(MessageFormat.format("value {0} has unsupported type {1}", value, type.getSimpleName())); //NOI18N
715                 }
716
717                 // Debug message
718                 this.getLogger().debug(MessageFormat.format("object[{0}]={1}", object.getClass().getSimpleName(), object)); //NOI18N
719
720                 // Get method to call
721                 Method method = this.getMethodFromName(instance, targetClass, methodName, type);
722
723                 // Debug message
724                 this.getLogger().debug(MessageFormat.format("method={0},instance={1},value[{2}]={3}", method, instance, value.getClass().getSimpleName(), value)); //NOI18N
725
726                 // Get value from field
727                 method.invoke(instance, object);
728
729                 // Trace messahe
730                 this.getLogger().trace("EXIT!"); //NOI18N
731         }
732
733         /**
734          * Getter for property which must exist
735          *
736          * @param key Key to get
737          * @return Propety value
738          */
739         protected final String getProperty (final String key) {
740                 return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.%s", key)); //NOI18N
741         }
742
743         /**
744          * Name of used database table, handled over to backend
745          *
746          * @param tableName the tableName to set
747          */
748         protected final void setTableName (final String tableName) {
749                 this.tableName = tableName;
750         }
751
752         /**
753          * Converts null to empty string or leaves original string.
754          *
755          * @param str Any string
756          * @return Empty string if null or original string
757          */
758         protected Object convertNullToEmpty (final Object str) {
759                 // Trace message
760                 this.getLogger().trace(MessageFormat.format("str={0}", str)); //NOI18N
761
762                 // Is it null?
763                 if (str == null) {
764                         // Return empty string
765                         return ""; //NOI18N
766                 }
767
768                 // Trace message
769                 this.getLogger().trace(MessageFormat.format("str={0} - EXIT!", str)); //NOI18N
770
771                 // Return it
772                 return str;
773         }
774
775         /**
776          * Creates an iterator from given instance and class name.
777          *
778          * @param instance Instance to run getter calls on
779          * @param className Class name to iterate over
780          * @return An iterator over all object's fields
781          * @throws java.lang.NoSuchMethodException If the called method does not exist
782          * @throws java.lang.IllegalAccessException If the method cannot be accessed
783          * @throws java.lang.reflect.InvocationTargetException Any other problems?
784          */
785         protected Iterator<Map.Entry<Field, Object>> fieldIterator (final Storeable instance, final String className) throws IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
786                 // Trace message
787                 this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className)); //NOI18N
788
789                 // Get all attributes from given instance
790                 Field[] fields = this.getClassFromTarget(instance, className).getDeclaredFields();
791
792                 // Debug message
793                 this.getLogger().debug(MessageFormat.format("Found {0} fields.", fields.length)); //NOI18N
794
795                 // A simple map with K=fieldName and V=Value is fine
796                 Map<Field, Object> map = new HashMap<>(fields.length);
797
798                 // Walk through all
799                 for (final Field field : fields) {
800                         // Debug log
801                         this.getLogger().debug(MessageFormat.format("field={0}", field.getName())); //NOI18N
802
803                         // Does the field start with "$"?
804                         if (field.getName().startsWith("$")) { //NOI18N
805                                 // Debug message
806                                 this.getLogger().debug(MessageFormat.format("Skipping field={0} as it starts with a dollar character.", field.getName())); //NOI18N
807
808                                 // Skip it silently
809                                 continue;
810                         }
811
812                         // Debug message
813                         this.getLogger().debug(MessageFormat.format("Calling getValueFromColumn({0}) on instance {1} ...", field.getName(), instance)); //NOI18N
814
815                         // Get value from it
816                         Object value = instance.getValueFromColumn(field.getName());
817
818                         // Debug message
819                         this.getLogger().debug(MessageFormat.format("Adding field={0},value={1}", field.getName(), value)); //NOI18N
820
821                         // Add it to list
822                         map.put(field, value);
823                 }
824
825                 // Debug message
826                 this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", map.size())); //NOI18N
827
828                 // Return list iterator
829                 return map.entrySet().iterator();
830         }
831
832         /**
833          * Instance for database backend
834          *
835          * @return the backend
836          */
837         protected final DatabaseBackend getBackend () {
838                 return this.backend;
839         }
840
841         /**
842          * Instance for database backend
843          *
844          * @param backend the backend to set
845          */
846         protected final void setBackend (final DatabaseBackend backend) {
847                 this.backend = backend;
848         }
849
850         /**
851          * Getter for Contact instance
852          *
853          * @return Contact instance
854          */
855         protected final Contact getContact () {
856                 return this.contact;
857         }
858
859         /**
860          * Setter for Contact instance
861          *
862          * @param contact A Contact instance
863          */
864         protected final void setContact (final Contact contact) {
865                 this.contact = contact;
866         }
867
868         /**
869          * Getter for DatabaseFrontend instance
870          *
871          * @return DatabaseFrontend instance
872          */
873         protected final DatabaseFrontend getFrontend () {
874                 return this.wrapper;
875         }
876
877         /**
878          * Setter for wrapper instance
879          *
880          * @param wrapper A DatabaseFrontend instance
881          */
882         protected final void setFrontend (final DatabaseFrontend wrapper) {
883                 this.wrapper = wrapper;
884         }
885
886         /**
887          * Initializes i18n bundles
888          */
889         protected void initBundle () {
890                 // Trace message
891                 this.getLogger().trace("CALLED!"); //NOI18N
892
893                 // Is the bundle set?
894                 if (bundle instanceof ResourceBundle) {
895                         // Is already set
896                         throw new IllegalStateException("called twice"); //NOI18N
897                 }
898
899                 // Set instance
900                 bundle = ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE); // NOI18N
901
902                 // Trace message
903                 this.getLogger().trace("EXIT!"); //NOI18N
904         }
905
906         /**
907          * Prepares all properties, the file is written if it is not found
908          *
909          * @throws java.io.IOException If any IO problem occurs
910          */
911         protected void initProperties () throws IOException {
912                 // Trace message
913                 this.getLogger().trace("CALLED!"); //NOI18N
914
915                 // Debug message
916                 this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
917
918                 // Are some properties loaded?
919                 if (!BaseFrameworkSystem.properties.isEmpty()) {
920                         // Some are already loaded, abort here
921                         return;
922                 }
923
924                 try {
925                         // Try to read it
926                         BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
927
928                         // Debug message
929                         this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
930                 } catch (final FileNotFoundException ex) {
931                         // Debug message
932                         this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
933
934                         /*
935                          * The file is not found which is normal for first run, so
936                          * initialize default values.
937                          */
938                         this.initPropertiesWithDefault();
939
940                         // Write file
941                         this.writePropertiesFile();
942                 }
943
944                 // Trace message
945                 this.getLogger().trace("EXIT!"); //NOI18N
946         }
947
948         /**
949          * Checks whether the given field is a boolean field by probing it.
950          *
951          * @param instance Instance to call
952          * @param targetClass Target class
953          * @param columnName Column name to check
954          * @return Whether the given column name represents a boolean field
955          */
956         protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
957                 // Trace message
958                 this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
959
960                 // Convert column name to getter name (boolean)
961                 String methodName = this.convertColumnNameToGetterMethod(columnName, true);
962
963                 // Get class instance
964                 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
965
966                 // Defauzlt is boolean
967                 boolean isBool = true;
968
969                 try {
970                         // Now try to instance the method
971                         Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
972                 } catch (final NoSuchMethodException ex) {
973                         // Debug message
974                         this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
975
976                         // Not found
977                         isBool = false;
978                 }
979
980                 // Trace message
981                 this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N
982
983                 // Return result
984                 return isBool;
985         }
986
987         /**
988          * Sets value in properties instance.
989          *
990          * @param key Property key (part) to set
991          * @param value Property value to set
992          */
993         protected void setProperty (final String key, final String value) {
994                 // Trace message
995                 this.getLogger().trace(MessageFormat.format("key={0},value={1} - CALLED!", key, value)); //NOI18N
996
997                 // Both should not be null
998                 if (key == null) {
999                         // key is null
1000                         throw new NullPointerException("key is null"); //NOI18N
1001                 } else if (value == null) {
1002                         // value is null
1003                         throw new NullPointerException("value is null"); //NOI18N
1004                 }
1005
1006                 // Set it
1007                 properties.setProperty(String.format("org.mxchange.%s", key), value); //NOI18N
1008
1009                 // Trace message
1010                 this.getLogger().trace("EXIT!"); //NOI18N
1011         }
1012
1013         /**
1014          * Some getter for properties names (without org.mxchange)
1015          *
1016          * @return An array with property names
1017          */
1018         protected String[] getPropertyNames () {
1019                 // Init array
1020                 String[] names = {
1021                         "database.backend.class", //NOI18N
1022                         "database.backend.storagepath", //NOI18N
1023                         "database.mysql.login", //NOI18N
1024                         "database.mysql.host", //NOI18N
1025                         "database.mysql.password", //NOI18N
1026                         "database.mysql.dbname", //NOI18N
1027                 };
1028
1029                 // Return it
1030                 return names;
1031         }
1032
1033         /**
1034          * Some "setter" for a value in given Storeable instance and target class
1035          * 
1036          * @param instance An instance of a Storeable class
1037          * @param targetClass The target class (where the field resides)
1038          * @param columnName Column name (= field name)
1039          * @param value Value to set
1040          * @throws java.lang.NoSuchMethodException If the setter is not found
1041          * @throws java.lang.IllegalAccessException If the setter cannot be accessed
1042          * @throws java.lang.reflect.InvocationTargetException Any other problem?
1043          */
1044         protected void setValueInStoreableFromColumn (final Storeable instance, final String targetClass, final String columnName, final Object value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
1045                 // Trace message
1046                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2},value={3} - CALLED!", instance, targetClass, columnName, value)); //NOI18N
1047
1048                 // A '$' means not our field
1049                 if (columnName.startsWith("$")) { //NOI18N
1050                         // Don't handle these
1051                         throw new IllegalArgumentException("columnsName contains $"); //NOI18N
1052                 }
1053
1054                 // Determine if the given column is boolean
1055                 if (this.isBooleanField(instance, targetClass, columnName)) {
1056                         // Debug message
1057                         this.getLogger().debug(MessageFormat.format("Column {0} represents a boolean field.", columnName)); //NOI18N
1058
1059                         // Yes, then call other method
1060                         this.setBooleanField(instance, targetClass, this.convertColumnNameToSetterMethod(columnName), columnName, (Boolean) value);
1061                 }
1062
1063                 // Convert column name to field name
1064                 String methodName = this.convertColumnNameToSetterMethod(columnName);
1065
1066                 // Debug message
1067                 this.getLogger().debug(MessageFormat.format("methodName={0}", methodName)); //NOI18N
1068
1069                 // Get field
1070                 this.setField(instance, targetClass, methodName, columnName, value);
1071
1072                 // Trace message
1073                 this.getLogger().trace("EXIT!"); //NOI18N
1074         }
1075
1076         /**
1077          * Some "getter" for a value from given Storeable instance and target class
1078          *
1079          * @param instance An instance of a Storeable class
1080          * @param targetClass The target class (where the field resides)
1081          * @param columnName Column name (= field name)
1082          * @return  value Value to get
1083          * @throws java.lang.NoSuchMethodException If the getter was not found
1084          * @throws java.lang.IllegalAccessException If the getter cannot be accessed
1085          * @throws java.lang.reflect.InvocationTargetException Some other problems?
1086          */
1087         protected Object getValueInStoreableFromColumn (final Storeable instance, final String targetClass, final String columnName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
1088                 // Trace message
1089                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
1090
1091                 // A '$' means not our field
1092                 if (columnName.startsWith("$")) { //NOI18N
1093                         // Don't handle these
1094                         throw new IllegalArgumentException("columnsName contains $"); //NOI18N
1095                 }
1096
1097                 // Determine if the given column is boolean
1098                 if (this.isBooleanField(instance, targetClass, columnName)) {
1099                         // Debug message
1100                         this.getLogger().debug(MessageFormat.format("Column {0} represents a boolean field.", columnName)); //NOI18N
1101
1102                         // Yes, then call other method
1103                         return this.getBooleanField(instance, targetClass, this.convertColumnNameToGetterMethod(columnName, true));
1104                 }
1105
1106                 // Convert column name to field name
1107                 String methodName = this.convertColumnNameToGetterMethod(columnName, false);
1108
1109                 // Debug message
1110                 this.getLogger().debug(MessageFormat.format("methodName={0}", methodName)); //NOI18N
1111
1112                 // Get field
1113                 Object value = this.getField(instance, targetClass, methodName);
1114
1115                 // Trace message
1116                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
1117
1118                 // Return value
1119                 return value;
1120         }
1121
1122         /**
1123          * Some getter for type reflection of given column name
1124          *
1125          * @param instance The instance to check
1126          * @param targetClass Target class to check
1127          * @param columnName Column name
1128          * @return Type reflection of value
1129          */
1130         private Class<?> getType (final FrameworkInterface instance, final String targetClass, final String columnName) {
1131                 // Trace message
1132                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
1133
1134                 // Init field tye
1135                 Class<?> type = null;
1136
1137                 // Get all attributes from given instance
1138                 Field[] fields = this.getClassFromTarget(instance, targetClass).getDeclaredFields();
1139
1140                 // Debug message
1141                 this.getLogger().debug("fields()=" + fields.length); //NOI18N
1142
1143                 // Search for proper field instance
1144                 for (final Field field : fields) {
1145                         // Debug message
1146                         this.getLogger().debug("field=" + field); //NOI18N
1147
1148                         // Does it match?
1149                         if (field.getName().equals(columnName)) {
1150                                 // Found it
1151                                 type = field.getType();
1152                                 break;
1153                         }
1154                 }
1155
1156                 // type should not be null
1157                 if (type == null) {
1158                         // No null allowed
1159                         throw new NullPointerException("type is null"); //NOI18N
1160                 }
1161
1162                 // Trace message
1163                 this.getLogger().debug(MessageFormat.format("type={0} - EXIT!", type)); //NOI18N
1164
1165                 // Return it
1166                 return type;
1167         }
1168 }