]> git.mxchange.org Git - jcore.git/blob - src/org/mxchange/jcore/BaseFrameworkSystem.java
Also this came from old TDGP times
[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.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.text.MessageFormat;
22 import java.util.Arrays;
23 import java.util.ResourceBundle;
24 import java.util.StringTokenizer;
25 import org.apache.logging.log4j.LogManager;
26 import org.apache.logging.log4j.Logger;
27 import org.mxchange.jcore.application.Application;
28 import org.mxchange.jcore.client.Client;
29 import org.mxchange.jcore.contact.Contact;
30 import org.mxchange.jcore.manager.Manageable;
31
32 /**
33  * General class
34  *
35  * @author Roland Haeder
36  */
37 public class BaseFrameworkSystem implements FrameworkInterface {
38
39         /**
40          * Bundle instance
41          */
42         private static ResourceBundle bundle;
43
44         /**
45          * Self instance
46          */
47         private static FrameworkInterface selfInstance;
48
49         /**
50          * Class' logger
51          */
52         private final Logger LOG;
53
54         /**
55          * Application instance
56          */
57         private Application application;
58
59         /**
60          * Client instance
61          */
62         private Client client;
63
64         /**
65          * Contact instance
66          */
67         private Contact contact;
68
69         /**
70          * Manager instance
71          */
72         private Manageable manager;
73
74         /**
75          * Name of used database table, handled over to backend
76          */
77         private String tableName;
78
79         /**
80          * Initialize object
81          */
82         {
83                 // Init logger
84                 this.LOG = LogManager.getLogger(this);
85
86                 // Need to set it here
87                 selfInstance = this;
88         }
89
90         /**
91          * No instances can be created of this class
92          */
93         protected BaseFrameworkSystem () {
94         }
95
96         /**
97          * Getter for this application
98          *
99          * @return Instance from this application
100          */
101         public static final FrameworkInterface getInstance () {
102                 // Return it
103                 return selfInstance;
104         }
105
106         @Override
107         public final Application getApplication () {
108                 return this.application;
109         }
110
111         @Override
112         public final Logger getLogger () {
113                 return this.LOG;
114         }
115
116         @Override
117         public final Manageable getManager () {
118                 return this.manager;
119         }
120
121         @Override
122         public final String getMessageStringFromKey (final String key) {
123                 // Return message
124                 return this.getBundle().getString(key);
125         }
126
127         /**
128          * Some "getter" for target class instance from given name.
129          *
130          * @param instance Instance to iterate on
131          * @param targetClass Class name to look for
132          * @return Class instance
133          */
134         @SuppressWarnings ("unchecked")
135         private Class<? extends FrameworkInterface> getClassFromTarget (final FrameworkInterface instance, final String targetClass) {
136                 // Trace message
137                 this.getLogger().debug(MessageFormat.format("instance={0},targetClass={1}", instance, targetClass)); //NOI18N
138
139                 // Instance reflaction of this class
140                 Class<? extends FrameworkInterface> c = instance.getClass();
141
142                 // Analyze class
143                 while (!targetClass.equals(c.getSimpleName())) {
144                         // Debug message
145                         this.getLogger().debug(MessageFormat.format("c={0}", c.getSimpleName())); //NOI18N
146
147                         // Get super class (causes unchecked warning)
148                         c = (Class<? extends FrameworkInterface>) c.getSuperclass();
149                 }
150
151                 // Trace message
152                 this.getLogger().trace(MessageFormat.format("c={0} - EXIT!", c)); //NOI18N
153
154                 // Return it
155                 return c;
156         }
157
158         /**
159          * Some "getter" for a Method instance from given method name
160          *
161          * @param instance Actual instance to call
162          * @param targetClass Target class name
163          * @param methodName Method name
164          * @return A Method instance
165          */
166         private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException {
167                 // Trace messahe
168                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
169
170                 // Init method instance
171                 Method method = null;
172
173                 // Try it from target class
174                 try {
175                         // Get target class instance
176                         Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
177
178                         // Init field instance
179                         method = c.getDeclaredMethod(methodName, new Class<?>[0]);
180                 } catch (final NoSuchMethodException e) {
181                         // Didn't found it
182                         this.getLogger().debug(e);
183
184                         // So try it from super class
185                         Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, "BaseFrameworkSystem"); //NOI18N
186
187                         // Init field instance
188                         method = c.getDeclaredMethod(methodName, new Class<?>[0]);
189                 }
190
191                 // Assert on field
192                 assert (method instanceof Method) : "method is not a Method instance"; //NOI18N
193
194                 // Trace message
195                 this.getLogger().trace(MessageFormat.format("method={0} - EXIT!", method)); //NOI18N
196
197                 // Return it
198                 return method;
199         }
200
201         /**
202          * Some "getter" for a Method instance from given method name
203          *
204          * @param instance Actual instance to call
205          * @param targetClass Target class name
206          * @param methodName Method name
207          * @param type Type reflection to check type from
208          * @return A Method instance
209          */
210         private Method getMethodFromName (final FrameworkInterface instance, final String targetClass, final String methodName, final Class<?> type) throws NoSuchMethodException {
211                 // Trace messahe
212                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1},type={2}", targetClass, methodName, type)); //NOI18N
213
214                 // Init method instance
215                 Method method = null;
216
217                 // Try it from target class
218                 try {
219                         // Get target class instance
220                         Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, targetClass);
221
222                         // Init field instance
223                         method = c.getDeclaredMethod(methodName, type);
224                 } catch (final NoSuchMethodException e) {
225                         // Didn't found it
226                         this.getLogger().debug(e);
227
228                         // So try it from super class
229                         Class<? extends FrameworkInterface> c = this.getClassFromTarget(instance, "BaseFrameworkSystem"); //NOI18N
230
231                         // Init field instance
232                         method = c.getDeclaredMethod(methodName, type);
233                 }
234
235                 // Assert on field
236                 assert (method instanceof Method) : "method is not a Method instance"; //NOI18N
237
238                 // Trace message
239                 this.getLogger().trace(MessageFormat.format("method={0} - EXIT!", method)); //NOI18N
240
241                 // Return it
242                 return method;
243         }
244
245         /**
246          * Aborts program with given exception
247          *
248          * @param throwable Any type of Throwable
249          */
250         protected final void abortProgramWithException (final Throwable throwable) {
251                 // Log exception ...
252                 this.logException(throwable);
253
254                 // .. and exit
255                 System.exit(1);
256         }
257
258         /**
259          * Application instance
260          *
261          * @param application the application to set
262          */
263         protected final void setApplication (final Application application) {
264                 this.application = application;
265         }
266
267         @Override
268         public final Client getClient () {
269                 return this.client;
270         }
271
272         /**
273          * Getter for bundle instance
274          *
275          * @return Resource bundle
276          */
277         protected final ResourceBundle getBundle () {
278                 return BaseFrameworkSystem.bundle;
279         }
280
281         /**
282          * Setter for bundle instance
283          *
284          * @param bundle the bundle to set
285          */
286         protected static void setBundle (final ResourceBundle bundle) {
287                 BaseFrameworkSystem.bundle = bundle;
288         }
289
290         /**
291          * Client instance
292          *
293          * @param client the client to set
294          */
295         protected final void setClient (final Client client) {
296                 this.client = client;
297         }
298
299         /**
300          * Name of used database table, handled over to backend
301          *
302          * @return the tableName
303          */
304         public final String getTableName () {
305                 return this.tableName;
306         }
307
308         @Override
309         public boolean isFieldValueEqual (final String columnName, final boolean bool) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
310                 // Not implemented
311                 throw new UnsupportedOperationException(MessageFormat.format("Not implemented. columnName={0},bool={1}", columnName, bool)); //NOI18N
312         }
313
314         @Override
315         public final void logException (final Throwable exception) {
316                 // Log this exception
317                 this.getLogger().catching(exception);
318         }
319
320         /**
321          * Converts a column name like "foo_bar" to an attribute name like "fooBar"
322          *
323          * @param columnName Column name to convert
324          * @return Attribute name
325          */
326         protected String convertColumnNameToFieldName (final String columnName) {
327                 // Trace message
328                 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
329
330                 // Split on "_"
331                 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
332
333                 // Resulting string
334                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
335
336                 // Init counter
337                 int count = 0;
338
339                 // Walk through all
340                 while (tokenizer.hasMoreTokens()) {
341                         // Get token
342                         String token = tokenizer.nextToken();
343
344                         // Is later than first element?
345                         if (count > 0) {
346                                 // Make first character upper-case
347                                 char c = token.charAt(0);
348                                 token = String.valueOf(c).toUpperCase() + token.substring(1);
349                         }
350
351                         // Add token
352                         builder.append(token);
353
354                         // Increment counter
355                         count++;
356                 }
357
358                 // Trace message
359                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
360
361                 // Return result
362                 return builder.toString();
363         }
364
365         /**
366          * Converts a column name like "foo_bar" to a method name like "getFooBar"
367          * for non-booleans and to "isFooBar" for boolean fields.
368          *
369          * @param columnName Column name to convert
370          * @param isBool Whether the parameter is boolean
371          * @return Attribute name
372          */
373         protected String convertColumnNameToGetterMethod (final String columnName, boolean isBool) {
374                 // Trace message
375                 this.getLogger().trace(MessageFormat.format("columnName={0},isBool={1} - CALLED!", columnName, isBool)); //NOI18N
376
377                 // Then split on "_"
378                 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
379
380                 // Resulting string
381                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
382
383                 // Is it boolean?
384                 if (isBool) {
385                         // Append "is"
386                         builder.append("is"); //NOI18N
387                 } else {
388                         // Append "get"
389                         builder.append("get"); //NOI18N
390                 }
391
392                 // Walk through all
393                 while (tokenizer.hasMoreTokens()) {
394                         // Get token
395                         String token = tokenizer.nextToken();
396
397                         // Debug message
398                         this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
399
400                         // Make it upper-case
401                         char c = token.charAt(0);
402                         token = String.valueOf(c).toUpperCase() + token.substring(1);
403
404                         // Add token
405                         builder.append(token);
406                 }
407
408                 // Trace message
409                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
410
411                 // Return result
412                 return builder.toString();
413         }
414
415         /**
416          * Converts a column name like "foo_bar" to a method name like "getFooBar"
417          * for non-booleans and to "isFooBar" for boolean fields.
418          *
419          * @param columnName Column name to convert
420          * @return Attribute name
421          */
422         protected String convertColumnNameToSetterMethod (final String columnName) {
423                 // Trace message
424                 this.getLogger().trace(MessageFormat.format("columnName={0} - CALLED!", columnName)); //NOI18N
425
426                 // Then split on "_"
427                 StringTokenizer tokenizer = new StringTokenizer(columnName, "_"); //NOI18N
428
429                 // Resulting string
430                 StringBuilder builder = new StringBuilder(tokenizer.countTokens());
431
432                 // Append "set"
433                 builder.append("set"); //NOI18N
434
435                 // Walk through all
436                 while (tokenizer.hasMoreTokens()) {
437                         // Get token
438                         String token = tokenizer.nextToken();
439
440                         // Debug message
441                         this.getLogger().debug(MessageFormat.format("token={0} - BEFORE", token)); //NOI18N
442
443                         // Make it upper-case
444                         char c = token.charAt(0);
445                         token = String.valueOf(c).toUpperCase() + token.substring(1);
446
447                         // Debug message
448                         this.getLogger().debug(MessageFormat.format("token={0} - AFTER", token)); //NOI18N
449
450                         // Add token
451                         builder.append(token);
452                 }
453
454                 // Trace message
455                 this.getLogger().trace(MessageFormat.format("builder={0} - EXIT!", builder)); //NOI18N
456
457                 // Return result
458                 return builder.toString();
459         }
460
461         /**
462          * Some "getter" for an array from given string and tokenizer
463          *
464          * @param str String to tokenize and get array from
465          * @param delimiter Delimiter
466          * @return Array from tokenized string TODO Get rid of size parameter
467          */
468         protected String[] getArrayFromString (final String str, final String delimiter) {
469                 // Trace message
470                 this.getLogger().trace(MessageFormat.format("str={0},delimiter={1} - CALLED!", str, delimiter)); //NOI18N
471
472                 // Get tokenizer
473                 StringTokenizer tokenizer = new StringTokenizer(str, delimiter);
474
475                 // Init array and index
476                 String[] tokens = new String[tokenizer.countTokens()];
477                 int index = 0;
478
479                 // Run through all tokens
480                 while (tokenizer.hasMoreTokens()) {
481                         // Get current token and add it
482                         tokens[index] = tokenizer.nextToken();
483
484                         // Debug message
485                         this.getLogger().debug(MessageFormat.format("Token at index{0}: {1}", index, tokens[1])); //NOI18N
486
487                         // Increment index
488                         index++;
489                 }
490
491                 // Trace message
492                 this.getLogger().trace(MessageFormat.format("tokens({0})={1} - EXIT!", tokens.length, Arrays.toString(tokens))); //NOI18N
493
494                 // Return it
495                 return tokens;
496         }
497
498         /**
499          * Returns boolean field value from given method name by invoking it
500          *
501          * @param instance The instance to call
502          * @param targetClass Target class to look in
503          * @param methodName Method name to look for
504          * @return Boolean value from field
505          * @throws java.lang.NoSuchMethodException If the method was not found
506          * @throws java.lang.IllegalAccessException If the method cannot be accessed
507          * @throws java.lang.reflect.InvocationTargetException Some other problems?
508          */
509         protected boolean getBooleanField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
510                 // Trace messahe
511                 this.getLogger().trace(MessageFormat.format("targetClass={0},methodName={1}", targetClass, methodName)); //NOI18N
512
513                 // Get method instance
514                 Method method = this.getMethodFromName(instance, targetClass, methodName);
515
516                 // Get value from field
517                 Boolean value = (Boolean) method.invoke(instance);
518
519                 // Trace message
520                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
521
522                 // Return value
523                 return value;
524         }
525
526         /**
527          * Manager instance
528          *
529          * @param manager the manager instance to set
530          */
531         protected final void setContactManager (final Manageable manager) {
532                 this.manager = manager;
533         }
534
535         /**
536          * Returns any field value from given method name by invoking it
537          *
538          * @param instance The instance to call
539          * @param targetClass Target class to look in
540          * @param methodName Method name to look for
541          * @return Any value from field
542          * @throws java.lang.NoSuchMethodException If the method was not found
543          * @throws java.lang.IllegalAccessException If the method cannot be accessed
544          * @throws java.lang.reflect.InvocationTargetException Some other problems?
545          */
546         protected Object getField (final FrameworkInterface instance, final String targetClass, final String methodName) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
547                 // Trace messahe
548                 this.getLogger().trace(MessageFormat.format("instance={0},targetClass={1},methodName={2}", instance, targetClass, methodName)); //NOI18N
549
550                 // Get method to call
551                 Method method = this.getMethodFromName(instance, targetClass, methodName);
552
553                 // Debug message
554                 this.getLogger().debug(MessageFormat.format("method={0},instance={1}", method, instance)); //NOI18N
555
556                 // Get value from field
557                 Object value = method.invoke(instance);
558
559                 // Trace messahe
560                 this.getLogger().trace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
561
562                 // Return value
563                 return value;
564         }
565
566         /**
567          * Name of used database table, handled over to backend
568          *
569          * @param tableName the tableName to set
570          */
571         protected final void setTableName (final String tableName) {
572                 this.tableName = tableName;
573         }
574
575         /**
576          * Converts null to empty string or leaves original string.
577          *
578          * @param str Any string
579          * @return Empty string if null or original string
580          */
581         protected Object convertNullToEmpty (final Object str) {
582                 // Trace message
583                 this.getLogger().trace(MessageFormat.format("str={0}", str)); //NOI18N
584
585                 // Is it null?
586                 if (null == str) {
587                         // Return empty string
588                         return ""; //NOI18N
589                 }
590
591                 // Trace message
592                 this.getLogger().trace(MessageFormat.format("str={0} - EXIT!", str)); //NOI18N
593
594                 // Return it
595                 return str;
596         }
597
598         /**
599          * Getter for Contact instance
600          *
601          * @return Contact instance
602          */
603         protected final Contact getContact () {
604                 return this.contact;
605         }
606
607         /**
608          * Setter for Contact instance
609          *
610          * @param contact A Contact instance
611          */
612         protected final void setContact (final Contact contact) {
613                 this.contact = contact;
614         }
615
616         /**
617          * Initializes i18n bundles
618          */
619         protected void initBundle () {
620                 // Trace message
621                 this.getLogger().trace("CALLED!"); //NOI18N
622
623                 // Is the bundle set?
624                 if (isBundledInitialized()) {
625                         // Is already set
626                         throw new IllegalStateException("called twice"); //NOI18N
627                 }
628
629                 // Set instance
630                 setBundle(ResourceBundle.getBundle(FrameworkInterface.I18N_BUNDLE_FILE)); // NOI18N
631
632                 // Trace message
633                 this.getLogger().trace("EXIT!"); //NOI18N
634         }
635
636         /**
637          * Checks if the bundle is initialized
638          *
639          * @return Whether the bundle has been initialized
640          */
641         protected static boolean isBundledInitialized () {
642                 // Check it
643                 return (bundle instanceof ResourceBundle);
644         }
645 }