]> git.mxchange.org Git - jcore.git/blob - src/org/mxchange/jcore/BaseFrameworkSystem.java
New jar for merging arrays added
[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.Storeable;
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                 // First all lower case
451                 String lower = columnName.toLowerCase();
452
453                 // Then split on "_"
454                 StringTokenizer tokenizer = new StringTokenizer(lower, "_"); //NOI18N
455
456                 // Resulting string
457                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
458
459                 // Init counter
460                 int count = 0;
461
462                 // Walk through all
463                 while (tokenizer.hasMoreTokens()) {
464                         // Get token
465                         String token = tokenizer.nextToken();
466
467                         // Is later than first element?
468                         if (count > 0) {
469                                 // Make first character upper-case
470                                 char c = token.charAt(0);
471                                 token = String.valueOf(c).toUpperCase() + token.substring(1);
472                         }
473
474                         // Add token
475                         builder.append(token);
476
477                         // Increment counter
478                         count++;
479                 }
480
481                 // Trace message
482                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
483
484                 // Return result
485                 return builder.toString();
486         }
487
488         /**
489          * Converts a column name like "foo_bar" to a method name like "getFooBar"
490          * for non-booleans and to "isFooBar" for boolean fields.
491          *
492          * @param columnName Column name to convert
493          * @param isBool Whether the parameter is boolean
494          * @return Attribute name
495          */
496         protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
497                 // Trace message
498                 this.getLogger().trace(MessageFormat.format("columnName={0},isBool={1} - CALLED!", columnName, isBool)); //NOI18N
499
500                 // Then split on "_"
501                 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
502
503                 // Resulting string
504                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
505
506                 // Is it boolean?
507                 if (isBool) {
508                         // Append "is"
509                         builder.append("is"); //NOI18N
510                 } else {
511                         // Append "get"
512                         builder.append("get"); //NOI18N
513                 }
514
515                 // Walk through all
516                 while (tokenizer.hasMoreTokens()) {
517                         // Get token
518                         String token = tokenizer.nextToken();
519
520                         // Debug message
521                         this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
522
523                         // Make it upper-case
524                         char c = token.charAt(0);
525                         token = String.valueOf(c).toUpperCase() + token.substring(1);
526
527                         // Add token
528                         builder.append(token);
529                 }
530
531                 // Trace message
532                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
533
534                 // Return result
535                 return builder.toString();
536         }
537
538         /**
539          * Converts a column name like "foo_bar" to a method name like "getFooBar"
540          * for non-booleans and to "isFooBar" for boolean fields.
541          *
542          * @param columnName Column name to convert
543          * @return Attribute name
544          */
545         protected String convertColumnNameToSetterMethod (final String columnName) {
546                 // Trace message
547                 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
548
549                 // Then split on "_"
550                 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
551
552                 // Resulting string
553                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
554
555                 // Append "set"
556                 builder.append("set"); //NOI18N
557
558                 // Walk through all
559                 while (tokenizer.hasMoreTokens()) {
560                         // Get token
561                         String token = tokenizer.nextToken();
562
563                         // Debug message
564                         this.getLogger().debug(MessageFormat.format("token={0} - BEFORE", token)); //NOI18N
565
566                         // Make it upper-case
567                         char c = token.charAt(0);
568                         token = String.valueOf(c).toUpperCase() + token.substring(1);
569
570                         // Debug message
571                         this.getLogger().debug(MessageFormat.format("token={0} - AFTER", token)); //NOI18N
572
573                         // Add token
574                         builder.append(token);
575                 }
576
577                 // Trace message
578                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
579
580                 // Return result
581                 return builder.toString();
582         }
583
584         /**
585          * Some "getter" for an array from given string and tokenizer
586          *
587          * @param str String to tokenize and get array from
588          * @param delimiter Delimiter
589          * @param size Size of array
590          * @return Array from tokenized string
591          * @todo Get rid of size parameter
592          */
593         protected String[] getArrayFromString (final String str, final String delimiter, final int size) {
594                 // Trace message
595                 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1},size={2} - CALLED!", str, delimiter, size)); //NOI18N
596
597                 // Get tokenizer
598                 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
599
600                 // Init array and index
601                 String[] tokens = new String[size];
602                 int index = 0;
603
604                 // Run through all tokens
605                 while (tokenizer.hasMoreTokens()) {
606                         // Get current token and add it
607                         tokens[index] = tokenizer.nextToken();
608
609                         // Debug message
610                         this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
611
612                         // Increment index
613                         index++;
614                 }
615
616                 // Trace message
617                 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
618
619                 // Return it
620                 return tokens;
621         }
622
623         /**
624          * Returns boolean field value from given method name by invoking it
625          *
626          * @param instance The instance to call
627          * @param targetClass Target class to look in
628          * @param methodName Method name to look for
629          * @return Boolean value from field
630          * @throws java.lang.NoSuchMethodException If the method was not found
631          * @throws java.lang.IllegalAccessException If the method cannot be accessed
632          * @throws java.lang.reflect.InvocationTargetException Some other problems?
633          */
634         protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
635                 // Trace messahe
636                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
637
638                 // Get method instance
639                 Method method = this.getMethodFromName(instance, targetClass, methodName);
640
641                 // Get value from field
642                 Boolean value = (Boolean) method.invoke(instance);
643
644                 // Trace message
645                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
646
647                 // Return value
648                 return value;
649         }
650
651         /**
652          * Sets boolean field value with given method name by invoking it
653          *
654          * @param instance The instance to call
655          * @param targetClass Target class to look in
656          * @param methodName Method name to look for
657          * @param columnName Column name
658          * @param value Boolean value from field
659          * @throws java.lang.NoSuchMethodException If the method was not found
660          * @throws java.lang.IllegalAccessException If the method cannot be accessed
661          * @throws java.lang.reflect.InvocationTargetException Some other problems?
662          */
663         protected void setBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName, final String columnName, final Boolean value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
664                 // Trace messahe
665                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
666
667                 // Get field type
668                 Class<?> type = this.getType(instance, targetClass, columnName);
669
670                 // Get method instance
671                 Method method = this.getMethodFromName(instance, targetClass, methodName, type);
672
673                 // Try to get the value by invoking the method
674                 method.invoke(instance, value);
675
676                 // Trace message
677                 this.getLogger().trace("EXIT!"); //NOI18N
678         }
679
680         /**
681          * Manager instance
682          *
683          * @param manager the manager instance to set
684          */
685         protected final void setContactManager (final Manageable manager) {
686                 this.manager = manager;
687         }
688
689         /**
690          * Returns any field value from given method name by invoking it
691          *
692          * @param instance The instance to call
693          * @param targetClass Target class to look in
694          * @param methodName Method name to look for
695          * @return Any value from field
696          * @throws java.lang.NoSuchMethodException If the method was not found
697          * @throws java.lang.IllegalAccessException If the method cannot be accessed
698          * @throws java.lang.reflect.InvocationTargetException Some other problems?
699          */
700         protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
701                 // Trace messahe
702                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},methodName={2}", instance, targetClass, methodName)); //NOI18N
703
704                 // Get method to call
705                 Method method = this.getMethodFromName(instance, targetClass, methodName);
706
707                 // Debug message
708                 this.getLogger().debug(MessageFormat.format("method={0},instance={1}", method, instance)); //NOI18N
709
710                 // Get value from field
711                 Object value = method.invoke(instance);
712
713                 // Trace messahe
714                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
715
716                 // Return value
717                 return value;
718         }
719
720         /**
721          * Sets any field value with given method name by invoking it
722          *
723          * @param instance The instance to call
724          * @param targetClass Target class to look in
725          * @param methodName Method name to look for
726          * @param columnName Column name
727          * @param value Any value from field
728          * @throws java.lang.NoSuchMethodException If the method was not found
729          * @throws java.lang.IllegalAccessException If the method cannot be accessed
730          * @throws java.lang.reflect.InvocationTargetException Some other problems?
731          */
732         protected void setField (final FrameworkInterface instance, final String targetClass, final String methodName, final String columnName, final Object value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
733                 // Trace messahe
734                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},methodName={2},value={3}", instance, targetClass, methodName, value)); //NOI18N
735
736                 // Get field type
737                 Class<?> type = this.getType(instance, targetClass, columnName);
738
739                 // Debug message
740                 this.getLogger().debug(MessageFormat.format("type={0}", type)); //NOI18N
741
742                 // Init object
743                 Object object = value;
744
745                 // Is the value null?
746                 if ("null".equals(value)) { //NOI18N
747                         // Warning message
748                         this.getLogger().warn(MessageFormat.format("columnName={0} has null value.", columnName)); //NOI18N
749
750                         // Set null
751                         object = null;
752                 } else {
753                         // Hard-coded "cast" again ... :-(
754                         // @TODO Can't we get rid of this???
755                         switch (type.getSimpleName()) {
756                                 case "Long": // Long object //NOI18N
757                                         object = Long.parseLong((String) value);
758                                         break;
759
760                                 case "Float": // Float object //NOI18N
761                                         object = Float.parseFloat((String) value);
762                                         break;
763
764                                 case "Boolean": // Boolean object //NOI18N
765                                         object = Boolean.parseBoolean((String) value);
766                                         break;
767
768                                 case "String": // String object //NOI18N
769                                         break;
770
771                                 default: // Unsupported type
772                                         throw new IllegalArgumentException(MessageFormat.format("value {0} has unsupported type {1}", value, type.getSimpleName())); //NOI18N
773                         }
774                 }
775
776                 // Debug message
777                 this.getLogger().debug(MessageFormat.format("object={0}", object)); //NOI18N
778
779                 // Get method to call
780                 Method method = this.getMethodFromName(instance, targetClass, methodName, type);
781
782                 // Debug message
783                 this.getLogger().debug(MessageFormat.format("method={0},instance={1},value[{2}]={3}", method, instance, value.getClass().getSimpleName(), value)); //NOI18N
784
785                 // Get value from field
786                 method.invoke(instance, object);
787
788                 // Trace messahe
789                 this.getLogger().trace("EXIT!"); //NOI18N
790         }
791
792         /**
793          * Getter for property which must exist
794          *
795          * @param key Key to get
796          * @return Propety value
797          */
798         protected final String getProperty (final String key) {
799                 return BaseFrameworkSystem.properties.getProperty(String.format("org.mxchange.%s", key)); //NOI18N
800         }
801
802         /**
803          * Name of used database table, handled over to backend
804          *
805          * @param tableName the tableName to set
806          */
807         protected final void setTableName (final String tableName) {
808                 this.tableName = tableName;
809         }
810
811         /**
812          * Converts null to empty string or leaves original string.
813          *
814          * @param str Any string
815          * @return Empty string if null or original string
816          */
817         protected Object convertNullToEmpty (final Object str) {
818                 // Trace message
819                 this.getLogger().trace(MessageFormat.format("str={0}", str)); //NOI18N
820
821                 // Is it null?
822                 if (null == str) {
823                         // Return empty string
824                         return ""; //NOI18N
825                 }
826
827                 // Trace message
828                 this.getLogger().trace(MessageFormat.format("str={0} - EXIT!", str)); //NOI18N
829
830                 // Return it
831                 return str;
832         }
833
834         /**
835          * Creates an iterator from given instance and class name.
836          *
837          * @param instance Instance to run getter calls on
838          * @param className Class name to iterate over
839          * @return An iterator over all object's fields
840          * @throws java.lang.NoSuchMethodException If the called method does not exist
841          * @throws java.lang.IllegalAccessException If the method cannot be accessed
842          * @throws java.lang.reflect.InvocationTargetException Any other problems?
843          */
844         protected Iterator<Map.Entry<Field, Object>> fieldIterator (final Storeable instance, final String className) throws IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
845                 // Trace message
846                 this.getLogger().trace(MessageFormat.format("instance={0},className={1} - CALLED!", instance, className)); //NOI18N
847
848                 // Get all attributes from given instance
849                 Field[] fields = this.getClassFromTarget(instance, className).getDeclaredFields();
850
851                 // Debug message
852                 this.getLogger().debug(MessageFormat.format("Found {0} fields.", fields.length)); //NOI18N
853
854                 // A simple map with K=fieldName and V=Value is fine
855                 Map<Field, Object> map = new HashMap<>(fields.length);
856
857                 // Walk through all
858                 for (final Field field : fields) {
859                         // Debug log
860                         this.getLogger().debug(MessageFormat.format("field={0}", field.getName())); //NOI18N
861
862                         // Does the field start with "$"?
863                         if (field.getName().startsWith("$")) { //NOI18N
864                                 // Debug message
865                                 this.getLogger().debug(MessageFormat.format("Skipping field={0} as it starts with a dollar character.", field.getName())); //NOI18N
866
867                                 // Skip it silently
868                                 continue;
869                         }
870
871                         // Debug message
872                         this.getLogger().debug(MessageFormat.format("Calling getValueFromColumn({0}) on instance {1} ...", field.getName(), instance)); //NOI18N
873
874                         // Get value from it
875                         Object value = instance.getValueFromColumn(field.getName());
876
877                         // Debug message
878                         this.getLogger().debug(MessageFormat.format("Adding field={0},value={1}", field.getName(), value)); //NOI18N
879
880                         // Add it to list
881                         map.put(field, value);
882                 }
883
884                 // Debug message
885                 this.getLogger().debug(MessageFormat.format("Returning iterator for {0} entries ...", map.size())); //NOI18N
886
887                 // Return list iterator
888                 return map.entrySet().iterator();
889         }
890
891         /**
892          * Instance for database backend
893          *
894          * @return the backend
895          */
896         protected final DatabaseBackend getBackend () {
897                 return this.backend;
898         }
899
900         /**
901          * Instance for database backend
902          *
903          * @param backend the backend to set
904          */
905         protected final void setBackend (final DatabaseBackend backend) {
906                 this.backend = backend;
907         }
908
909         /**
910          * Getter for Contact instance
911          *
912          * @return Contact instance
913          */
914         protected final Contact getContact () {
915                 return this.contact;
916         }
917
918         /**
919          * Setter for Contact instance
920          *
921          * @param contact A Contact instance
922          */
923         protected final void setContact (final Contact contact) {
924                 this.contact = contact;
925         }
926
927         /**
928          * Getter for DatabaseFrontend instance
929          *
930          * @return DatabaseFrontend instance
931          */
932         protected final DatabaseFrontend getFrontend () {
933                 return this.frontend;
934         }
935
936         /**
937          * Setter for wrapper instance
938          *
939          * @param frontend A DatabaseFrontend instance
940          */
941         protected final void setFrontend (final DatabaseFrontend frontend) {
942                 this.frontend = frontend;
943         }
944
945         /**
946          * Setter for session id
947          *
948          * @param sessionId Session id
949          */
950         @Override
951         public final void setSessionId (final String sessionId) {
952                 this.sessionId = sessionId;
953         }
954
955         /**
956          * Getter for session id
957          *
958          * @return Session id
959          */
960         @Override
961         public final String getSessionId () {
962                 return this.sessionId;
963         }
964
965         /**
966          * Checks if the bundle is initialized
967          *
968          * @return Whether the bundle has been initialized
969          */
970         protected boolean isBundledInitialized () {
971                 // Check it
972                 return (bundle instanceof ResourceBundle);
973         }
974
975         /**
976          * Initializes i18n bundles
977          */
978         protected void initBundle () {
979                 // Trace message
980                 this.getLogger().trace("CALLED!"); //NOI18N
981
982                 // Is the bundle set?
983                 if (this.isBundledInitialized()) {
984                         // Is already set
985                         throw new IllegalStateException("called twice"); //NOI18N
986                 }
987
988                 // Set instance
989                 setBundle(ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE)); // NOI18N
990
991                 // Trace message
992                 this.getLogger().trace("EXIT!"); //NOI18N
993         }
994
995         /**
996          * Prepares all properties, the file is written if it is not found
997          *
998          * @throws java.io.IOException If any IO problem occurs
999          */
1000         protected void initProperties () throws IOException {
1001                 // Trace message
1002                 this.getLogger().trace("CALLED!"); //NOI18N
1003
1004                 // Debug message
1005                 this.getLogger().debug(MessageFormat.format("{0} properties are loaded already.", BaseFrameworkSystem.properties.size())); //NOI18N
1006
1007                 // Are some properties loaded?
1008                 if (!BaseFrameworkSystem.properties.isEmpty()) {
1009                         // Some are already loaded, abort here
1010                         return;
1011                 }
1012
1013                 try {
1014                         // Try to read it
1015                         BaseFrameworkSystem.properties.load(new BufferedReader(new InputStreamReader(new FileInputStream(FrameworkInterface.PROPERTIES_CONFIG_FILE))));
1016
1017                         // Debug message
1018                         this.getLogger().debug(MessageFormat.format("{0} properties has been loaded.", BaseFrameworkSystem.properties.size())); //NOI18N
1019                 } catch (final FileNotFoundException ex) {
1020                         // Debug message
1021                         this.getLogger().debug(MessageFormat.format("Properties file {0} not found: {1}", FrameworkInterface.PROPERTIES_CONFIG_FILE, ex)); //NOI18N
1022
1023                         /*
1024                          * The file is not found which is normal for first run, so
1025                          * initialize default values.
1026                          */
1027                         this.initPropertiesWithDefault();
1028
1029                         // Write file
1030                         this.writePropertiesFile();
1031                 }
1032
1033                 // Trace message
1034                 this.getLogger().trace("EXIT!"); //NOI18N
1035         }
1036
1037         /**
1038          * Checks whether the given field is a boolean field by probing it.
1039          *
1040          * @param instance Instance to call
1041          * @param targetClass Target class
1042          * @param columnName Column name to check
1043          * @return Whether the given column name represents a boolean field
1044          */
1045         protected boolean isBooleanField (final FrameworkInterface instance, final String targetClass, final String columnName) {
1046                 // Trace message
1047                 this.getLogger().trace(MessageFormat.format("instance={0},targetCLass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
1048
1049                 // Convert column name to getter name (boolean)
1050                 String methodName = this.convertColumnNameToGetterMethod(columnName, true);
1051
1052                 // Get class instance
1053                 Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
1054
1055                 // Defauzlt is boolean
1056                 boolean isBool = true;
1057
1058                 try {
1059                         // Now try to instance the method
1060                         Method method = c.getDeclaredMethod(methodName, new Class<?>[0]);
1061                 } catch (final NoSuchMethodException ex) {
1062                         // Debug message
1063                         this.getLogger().debug(MessageFormat.format("Method {0} does not exist, field {1} cannot be boolean: {2}", methodName, columnName, ex)); //NOI18N
1064
1065                         // Not found
1066                         isBool = false;
1067                 }
1068
1069                 // Trace message
1070                 this.getLogger().trace(MessageFormat.format("isBool={0} - EXIT!", isBool)); //NOI18N
1071
1072                 // Return result
1073                 return isBool;
1074         }
1075
1076         /**
1077          * Sets value in properties instance.
1078          *
1079          * @param key Property key (part) to set
1080          * @param value Property value to set
1081          */
1082         protected void setProperty (final String key, final String value) {
1083                 // Trace message
1084                 this.getLogger().trace(MessageFormat.format("key={0},value={1} - CALLED!", key, value)); //NOI18N
1085
1086                 // Both should not be null
1087                 if (null == key) {
1088                         // key is null
1089                         throw new NullPointerException("key is null"); //NOI18N
1090                 } else if (null == value) {
1091                         // value is null
1092                         throw new NullPointerException("value is null"); //NOI18N
1093                 }
1094
1095                 // Set it
1096                 properties.setProperty(String.format("org.mxchange.%s", key), value); //NOI18N
1097
1098                 // Trace message
1099                 this.getLogger().trace("EXIT!"); //NOI18N
1100         }
1101
1102         /**
1103          * Some getter for properties names (without org.mxchange)
1104          *
1105          * @return An array with property names
1106          */
1107         protected String[] getPropertyNames () {
1108                 // Init array
1109                 String[] names = {
1110                         "database.backend.class", //NOI18N
1111                         "database.backend.storagepath", //NOI18N
1112                         "database.mysql.login", //NOI18N
1113                         "database.mysql.host", //NOI18N
1114                         "database.mysql.password", //NOI18N
1115                         "database.mysql.dbname", //NOI18N
1116                 };
1117
1118                 // Return it
1119                 return names;
1120         }
1121
1122         /**
1123          * Some "setter" for a value in given Storeable instance and target class
1124          * 
1125          * @param instance An instance of a Storeable class
1126          * @param targetClass The target class (where the field resides)
1127          * @param columnName Column name (= field name)
1128          * @param value Value to set
1129          * @throws java.lang.NoSuchMethodException If the setter is not found
1130          * @throws java.lang.IllegalAccessException If the setter cannot be accessed
1131          * @throws java.lang.reflect.InvocationTargetException Any other problem?
1132          */
1133         protected void setValueInStoreableFromColumn (final Storeable instance, final String targetClass, final String columnName, final Object value) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
1134                 // Trace message
1135                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2},value={3} - CALLED!", instance, targetClass, columnName, value)); //NOI18N
1136
1137                 // A '$' means not our field
1138                 if (columnName.startsWith("$")) { //NOI18N
1139                         // Don't handle these
1140                         throw new IllegalArgumentException("columnsName contains $"); //NOI18N
1141                 }
1142
1143                 // Determine if the given column is boolean
1144                 if (this.isBooleanField(instance, targetClass, columnName)) {
1145                         // Debug message
1146                         this.getLogger().debug(MessageFormat.format("Column {0} represents a boolean field.", columnName)); //NOI18N
1147
1148                         // Yes, then call other method
1149                         this.setBooleanField(instance, targetClass, this.convertColumnNameToSetterMethod(columnName), columnName, (Boolean) value);
1150                 }
1151
1152                 // Convert column name to field name
1153                 String methodName = this.convertColumnNameToSetterMethod(columnName);
1154
1155                 // Debug message
1156                 this.getLogger().debug(MessageFormat.format("methodName={0}", methodName)); //NOI18N
1157
1158                 // Get field
1159                 this.setField(instance, targetClass, methodName, columnName, value);
1160
1161                 // Trace message
1162                 this.getLogger().trace("EXIT!"); //NOI18N
1163         }
1164
1165         /**
1166          * Some "getter" for a value from given Storeable instance and target class
1167          *
1168          * @param instance An instance of a Storeable class
1169          * @param targetClass The target class (where the field resides)
1170          * @param columnName Column name (= field name)
1171          * @return  value Value to get
1172          * @throws java.lang.NoSuchMethodException If the getter was not found
1173          * @throws java.lang.IllegalAccessException If the getter cannot be accessed
1174          * @throws java.lang.reflect.InvocationTargetException Some other problems?
1175          */
1176         protected Object getValueInStoreableFromColumn (final Storeable instance, final String targetClass, final String columnName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
1177                 // Trace message
1178                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
1179
1180                 // A '$' means not our field
1181                 if (columnName.startsWith("$")) { //NOI18N
1182                         // Don't handle these
1183                         throw new IllegalArgumentException("columnsName contains $"); //NOI18N
1184                 }
1185
1186                 // Determine if the given column is boolean
1187                 if (this.isBooleanField(instance, targetClass, columnName)) {
1188                         // Debug message
1189                         this.getLogger().debug(MessageFormat.format("Column {0} represents a boolean field.", columnName)); //NOI18N
1190
1191                         // Yes, then call other method
1192                         return this.getBooleanField(instance, targetClass, this.convertColumnNameToGetterMethod(columnName, true));
1193                 }
1194
1195                 // Convert column name to field name
1196                 String methodName = this.convertColumnNameToGetterMethod(columnName, false);
1197
1198                 // Debug message
1199                 this.getLogger().debug(MessageFormat.format("methodName={0}", methodName)); //NOI18N
1200
1201                 // Get field
1202                 Object value = this.getField(instance, targetClass, methodName);
1203
1204                 // Trace message
1205                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
1206
1207                 // Return value
1208                 return value;
1209         }
1210
1211         /**
1212          * Some getter for type reflection of given column name
1213          *
1214          * @param instance The instance to check
1215          * @param targetClass Target class to check
1216          * @param columnName Column name
1217          * @return Type reflection of value
1218          */
1219         private Class<?> getType (final FrameworkInterface instance, final String targetClass, final String columnName) {
1220                 // Trace message
1221                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},columnName={2} - CALLED!", instance, targetClass, columnName)); //NOI18N
1222
1223                 // Init field tye
1224                 Class<?> type = null;
1225
1226                 // Get super class fields
1227                 Field[] superFields = this.getClassFromTarget(instance, "BaseFrameworkSystem").getDeclaredFields(); //NOI18N
1228
1229                 // Get all attributes from given instance
1230                 Field[] fields = ArrayUtils.addAll(superFields, this.getClassFromTarget(instance, targetClass).getDeclaredFields());
1231
1232                 // Debug message
1233                 this.getLogger().debug(MessageFormat.format("fields()={0}", fields.length)); //NOI18N
1234
1235                 // Convert column_name to fieldName ;-)
1236                 String fieldName = this.convertColumnNameToFieldName(columnName);
1237
1238                 // Debug message
1239                 this.getLogger().debug(MessageFormat.format("fieldName={0}", fieldName)); //NOI18N
1240
1241                 // Search for proper field instance
1242                 for (final Field field : fields) {
1243                         // Debug message
1244                         this.getLogger().debug(MessageFormat.format("field.getName()={0},fieldName={1}", field.getName(), fieldName)); //NOI18N
1245
1246                         // Does it match?
1247                         if (field.getName().equals(fieldName)) {
1248                                 // Found it
1249                                 type = field.getType();
1250
1251                                 // Debug message
1252                                 this.getLogger().debug(MessageFormat.format("Found fieldName={0}: setting type={1}", fieldName, type.getSimpleName())); //NOI18N
1253
1254                                 // Don't continue with searching
1255                                 break;
1256                         }
1257                 }
1258
1259                 // Debug message
1260                 this.getLogger().debug(MessageFormat.format("type={0}", type)); //NOI18N
1261
1262                 // type should not be null
1263                 if (null == type) {
1264                         // No null allowed
1265                         throw new NullPointerException("type is null"); //NOI18N
1266                 }
1267
1268                 // Trace message
1269                 this.getLogger().debug(MessageFormat.format("type={0} - EXIT!", type)); //NOI18N
1270
1271                 // Return it
1272                 return type;
1273         }
1274 }