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