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