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