]> git.mxchange.org Git - jfinancials-swing.git/blob - src/org/mxchange/addressbook/client/console/ConsoleClient.java
f8cad4b2fce430d437638ec4b273d0bebd2d943b
[jfinancials-swing.git] / src / org / mxchange / addressbook / client / console / ConsoleClient.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.addressbook.client.console;
18
19 import java.io.IOException;
20 import java.sql.SQLException;
21 import java.text.MessageFormat;
22 import java.util.Arrays;
23 import java.util.Scanner;
24 import org.mxchange.addressbook.application.AddressbookApplication;
25 import org.mxchange.addressbook.client.AddressbookClient;
26 import org.mxchange.addressbook.client.BaseAddressbookClient;
27 import org.mxchange.addressbook.facade.contact.ContactFacade;
28 import org.mxchange.addressbook.menu.Menu;
29 import org.mxchange.addressbook.menu.MenuTools;
30 import org.mxchange.addressbook.menu.console.ConsoleMenu;
31 import org.mxchange.addressbook.menu.item.SelectableMenuItem;
32 import org.mxchange.addressbook.menu.item.console.ConsoleMenuItem;
33 import org.mxchange.jcontacts.contact.Contact;
34 import org.mxchange.jcontacts.contact.UserContact;
35 import org.mxchange.jcontacts.contact.gender.Gender;
36 import org.mxchange.jcontacts.contact.gender.GenderUtils;
37 import org.mxchange.jcontacts.exceptions.ContactAlreadyAddedException;
38 import org.mxchange.jcore.application.Application;
39 import org.mxchange.jcore.exceptions.MenuInitializationException;
40 import org.mxchange.jcore.exceptions.UnhandledUserChoiceException;
41
42 /**
43  * A client for the console
44  * <p>
45  * @author Roland Haeder
46  */
47 public class ConsoleClient extends BaseAddressbookClient implements AddressbookClient {
48
49         /**
50          * Scanner instance for reading data from console input
51          */
52         private final Scanner scanner;
53
54         /**
55          * Parameterless constructor
56          * <p>
57          * @param application An instance of an Application class
58          */
59         public ConsoleClient (final Application application) {
60                 // Trace message
61                 this.getLogger().logTrace(MessageFormat.format("application={0} - CALLED!", application)); //NOI18N
62
63                 // Set application instance
64                 this.setApplication(application);
65
66                 // Init scanner instance
67                 this.scanner = new Scanner(System.in, "UTF-8"); //NOI18N
68
69                 // Trace message
70                 this.getLogger().logTrace("EXIT!"); //NOI18N
71         }
72
73         @Override
74         public void displayAddressBox (final Contact contact) {
75                 // Trace message
76                 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
77
78                 // Is it null?
79                 if (null == contact) {
80                         // Abort here
81                         throw new NullPointerException("contact is null"); //NOI18N
82                 }
83
84                 // Simple display ...
85                 this.outputMessage(MessageFormat.format("Strasse, PLZ Ort, Land: {0}\n{1} {2}\n{3}", contact.getStreet(), contact.getZipCode(), contact.getCity(), contact.getCountryCode()));
86
87                 // Trace message
88                 this.getLogger().logTrace("EXIT!"); //NOI18N
89         }
90
91         @Override
92         public void displayNameBox (final Contact contact) {
93                 // Trace message
94                 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
95
96                 // Is it null?
97                 if (null == contact) {
98                         // Abort here
99                         throw new NullPointerException("contact is null"); //NOI18N
100                 }
101
102                 // Get translated gender as the user may want to see "Mr.", "Mrs."
103                 String gender = GenderUtils.getTranslatedGender(contact);
104
105                 // Get company name
106                 String companyName = contact.getCompanyName();
107
108                 // If it is empty/null, then assume private contact
109                 if ((null == companyName) || (companyName.isEmpty())) {
110                         // Now put all together: gender, surname, family name
111                         // TODO Use mask
112                         this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getFirstName(), contact.getFamilyName()));
113                 } else {
114                         // Company contact
115                         this.outputMessage(MessageFormat.format("Firma: {0}\nAnsprechpartner: {1} {2} {3}", companyName, gender, contact.getFirstName(), contact.getFamilyName()));
116                 }
117
118                 // Trace message
119                 this.getLogger().logTrace("EXIT!"); //NOI18N
120         }
121
122         @Override
123         public void displayOtherDataBox (final Contact contact) {
124                 // Trace message
125                 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
126
127                 // Is it null?
128                 if (null == contact) {
129                         // Abort here
130                         throw new NullPointerException("contact is null"); //NOI18N
131                 }
132
133                 // Cellphone and such ...
134                 this.outputMessage(MessageFormat.format("Telefonnumer: {0}\nFaxnummer: {1}\nHandy: {2}\nKommentar:\n{3}", contact.getPhoneNumber(), contact.getFaxNumber(), contact.getCellphoneNumber(), contact.getComment()));
135
136                 // Trace message
137                 this.getLogger().logTrace("EXIT!"); //NOI18N
138         }
139
140         @Override
141         public void doChangeOwnAddressData (final Contact contact) {
142                 // Trace message
143                 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
144
145                 // Is it null?
146                 if (null == contact) {
147                         // Abort here
148                         throw new NullPointerException("contact is null"); //NOI18N
149                 }
150
151                 // Make sure it is own contact
152                 if (!contact.isOwnContact()) {
153                         // Not own contact
154                         throw new IllegalArgumentException("Contact is not own data."); //NOI18N
155                 }
156
157                 // Get manager and cast it
158                 ContactFacade manager = (ContactFacade) this.getFacade();
159
160                 // Own street and number
161                 String streetNumber = manager.enterOwnStreet();
162
163                 // Get zip code
164                 Integer zipCode = manager.enterOwnZipCode();
165
166                 // Get city name
167                 String city = manager.enterOwnCity();
168
169                 // Get country code
170                 String countryCode = manager.enterOwnCountryCode();
171
172                 // Update address data
173                 contact.setStreet(streetNumber);
174                 contact.setZipCode(zipCode);
175                 contact.setCity(city);
176                 contact.setCountryCode(countryCode);
177
178                 // Trace message
179                 this.getLogger().logTrace("EXIT!"); //NOI18N
180         }
181
182         @Override
183         public void doChangeOwnNameData (final Contact contact) {
184                 // Trace message
185                 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
186
187                 // Is it null?
188                 if (null == contact) {
189                         // Abort here
190                         throw new NullPointerException("contact is null"); //NOI18N
191                 }
192
193                 // Make sure it is own contact
194                 if (!contact.isOwnContact()) {
195                         // Not own contact
196                         throw new IllegalArgumentException("Contact is not own data."); //NOI18N
197                 }
198
199                 // Get manager and cast it
200                 ContactFacade manager = (ContactFacade) this.getFacade();
201
202                 // Gender:
203                 Gender gender = manager.enterOwnGender();
204
205                 // Surname
206                 String firstName = manager.enterOwnFirstName();
207
208                 // Family name
209                 String familyName = manager.enterOwnFamilyName();
210
211                 // And company
212                 String companyName = manager.enterOwnCompanyName();
213
214                 // Update contact instance
215                 contact.setGender(gender);
216                 contact.setFirstName(firstName);
217                 contact.setFamilyName(familyName);
218                 contact.setCompanyName(companyName);
219
220                 // Trace message
221                 this.getLogger().logTrace("EXIT!"); //NOI18N
222         }
223
224         @Override
225         public void doChangeOwnOtherData (final Contact contact) {
226                 // Trace message
227                 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
228
229                 // Is it null?
230                 if (null == contact) {
231                         // Abort here
232                         throw new NullPointerException("contact is null"); //NOI18N
233                 }
234
235                 // Make sure it is own contact
236                 if (!contact.isOwnContact()) {
237                         // Not own contact
238                         throw new IllegalArgumentException("Contact is not own data."); //NOI18N
239                 }
240
241                 // Get manager and cast it
242                 ContactFacade manager = (ContactFacade) this.getFacade();
243
244                 // Phone number
245                 String phoneNumber = manager.enterOwnPhoneNumber();
246
247                 // Phone number
248                 String cellphonePhoneNumber = manager.enterOwnCellNumber();
249
250                 // Fax number
251                 String faxNumber = manager.enterOwnFaxNumber();
252
253                 // Email address
254                 String email = manager.enterOwnEmailAddress();
255
256                 // Comment
257                 String comment = manager.enterOwnComment();
258
259                 // Update contact instance
260                 contact.setPhoneNumber(phoneNumber);
261                 contact.setCellphoneNumber(cellphonePhoneNumber);
262                 contact.setFaxNumber(faxNumber);
263                 contact.setEmailAddress(email);
264                 contact.setComment(comment);
265
266                 // Trace message
267                 this.getLogger().logTrace("EXIT!"); //NOI18N
268         }
269
270         @Override
271         public Contact doEnterOwnData () {
272                 // Trace message
273                 this.getLogger().logTrace("CALLED!"); //NOI18N
274
275                 // Get manager and cast it
276                 ContactFacade manager = (ContactFacade) this.getFacade();
277
278                 // First ask for gender
279                 Gender gender = manager.enterOwnGender();
280
281                 // 2nd for first name
282                 String firstName = manager.enterOwnFirstName();
283
284                 // And 3rd for family name
285                 String familyName = manager.enterOwnFamilyName();
286
287                 // Company name ...
288                 String companyName = manager.enterOwnCompanyName();
289
290                 // Construct UserContact instance
291                 Contact contact = new UserContact(gender, firstName, familyName, companyName);
292
293                 // Trace message
294                 this.getLogger().logTrace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
295
296                 // And return object
297                 return contact;
298         }
299
300         @Override
301         public void doShutdown () throws SQLException, IOException {
302                 // Trace message
303                 this.getLogger().logTrace("CALLED!"); //NOI18N
304
305                 // Parent call
306                 super.doShutdown();
307
308                 // TODO Add other shutdown stuff
309                 // Trace message
310                 this.getLogger().logTrace("EXIT!"); //NOI18N
311         }
312
313         @Override
314         public void doUserMenuChoice () throws UnhandledUserChoiceException, MenuInitializationException {
315                 // Trace message
316                 this.getLogger().logTrace("CALLED!"); //NOI18N
317
318                 // Get all access keys from menu
319                 char[] accessKeys = MenuTools.getAccessKeysFromMenuMap(this.getMenus(), this.getCurrentMenu());
320
321                 // Output textural message and ask for a char as input
322                 char choice = this.enterChar(accessKeys, "Bitte Auswahl eingeben (0=Programm beenden): ");
323
324                 // Get manager and cast it
325                 ContactFacade manager = (ContactFacade) this.getFacade();
326
327                 // TODO Rewrite this ugly switch() block
328                 switch (choice) {
329                         case '1':
330                                 try {
331                                         // Enter/add own data
332                                         manager.doEnterOwnData();
333                                 } catch (final ContactAlreadyAddedException ex) {
334                                         // Already added
335                                         this.outputMessage("Sie haben bereits Ihre eigenen Daten eingegeben.");
336                                 }
337                                 break;
338
339                         case '2': // Change own data
340                                 manager.doChangeOwnData();
341                                 break;
342
343                         case '3': // Add new addess
344                                 manager.doAddOtherAddress();
345                                 break;
346
347                         case '4': // List contacts
348                                 manager.doListContacts();
349                                 break;
350
351                         case '5': // Search addresses
352                                 manager.doSearchContacts();
353                                 break;
354
355                         case '6': // Change other addess
356                                 manager.doChangeOtherAddress();
357                                 break;
358
359                         case '7': // Delete other address
360                                 manager.doDeleteOtherAddress();
361                                 break;
362
363                         case '0':
364                                 try {
365                                         // Program exit
366                                         this.getApplication().doShutdown();
367                                 } catch (final SQLException | IOException ex) {
368                                         this.abortProgramWithException(ex);
369                                 }
370                                 break;
371
372                         default:
373                                 // TODO throw own exception
374                                 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
375                 }
376
377                 // Trace message
378                 this.getLogger().logTrace("EXIT!"); //NOI18N
379         }
380
381         @Override
382         public char enterChar (final char[] validChars, final String message) {
383                 // Trace message
384                 this.getLogger().logTrace(MessageFormat.format("validChars={0},message={1} - CALLED!", Arrays.toString(validChars), message)); //NOI18N
385
386                 // The validChars must not null be null and filled with at least one char
387                 if (null == validChars) {
388                         // Is null
389                         throw new NullPointerException("validChars is null"); //NOI18N
390                 } else if (validChars.length == 0) {
391                         // Is not filled
392                         throw new IllegalArgumentException("validChars is not filled."); //NOI18N
393                 }
394
395                 char input = 0;
396
397                 // Sort array, else binarySearch() won't work
398                 Arrays.sort(validChars);
399
400                 // Keep asking until valid char has been entered
401                 while (Arrays.binarySearch(validChars, input) < 0) {
402                         // Output message
403                         System.out.print(message);
404
405                         // Read char
406                         input = this.readChar();
407                 }
408
409                 // Trace message
410                 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
411
412                 // Return read char
413                 return input;
414         }
415
416         @Override
417         public Gender enterGender (final String message) {
418                 // Trace message
419                 this.getLogger().logTrace(MessageFormat.format("message={0} - CALLED!", message)); //NOI18N
420
421                 // Get valid chars
422                 char[] validChars = Gender.validChars();
423
424                 // Debug message
425                 //* NOISY-DEBUG: */ System.out.println(validChars);
426                 // Call inner method
427                 char gender = this.enterChar(validChars, message);
428
429                 // Now get a Gender instance back
430                 Gender g = Gender.fromChar(gender);
431
432                 // g must not be null
433                 assert (g instanceof Gender) : "g is not set."; //NOI18N
434
435                 // Trace message
436                 this.getLogger().logTrace(MessageFormat.format("g={0} - EXIT!", g)); //NOI18N
437
438                 // Return it
439                 return g;
440         }
441
442         @Override
443         public int enterInt (final int minimum, final int maximum, final String message) {
444                 // Trace message
445                 this.getLogger().logTrace(MessageFormat.format("minimum={0},maximum={1},message={2} - CALLED!", minimum, maximum, message)); //NOI18N
446
447                 // Minimum should not be below zero
448                 assert (minimum >= 0) : MessageFormat.format("minimum={0} is below zero", minimum); //NOI18N
449                 assert (maximum > minimum) : MessageFormat.format("maximum {0} is smaller than minimum {1}", maximum, minimum); //NOI18N
450
451                 // Init input
452                 int input = -1;
453
454                 while ((input < minimum) || (input > maximum)) {
455                         // Output message
456                         System.out.print(message);
457
458                         // Read integer from user
459                         input = this.readInt();
460                 }
461
462                 // Trace message
463                 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
464
465                 // Return it
466                 return input;
467         }
468
469         @Override
470         public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
471                 // Trace message
472                 this.getLogger().logTrace(MessageFormat.format("minLength={0},maxLength={1},message={2}allowEmpty={3} - CALLED!", minLength, maxLength, message, allowEmpty)); //NOI18N
473
474                 // Check on length, e.g. country codes are excactly 2 chars long
475                 assert (maxLength >= minLength);
476
477                 // Init input
478                 String input = null;
479
480                 // Check if it is to short or to long
481                 while (((null == input) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
482                         // Output message
483                         System.out.print(message);
484
485                         // Read line
486                         input = this.readString();
487                 }
488
489                 // Trace message
490                 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
491
492                 // Return it
493                 return input;
494         }
495
496         @Override
497         public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
498                 // Return a new console menu item
499                 return new ConsoleMenuItem(accessKey, text);
500         }
501
502         @Override
503         public void init () {
504                 // Trace message
505                 this.getLogger().logTrace("CALLED!"); //NOI18N
506
507                 // Init contact manager here
508                 try {
509                         this.initContactManager();
510                 } catch (final SQLException ex) {
511                         // End here
512                         this.abortProgramWithException(ex);
513                 }
514
515                 // Fill menu map
516                 this.fillMenuMap();
517
518                 // Trace message
519                 this.getLogger().logTrace("EXIT!"); //NOI18N
520         }
521
522         @Override
523         public void outputMessage (final String message) {
524                 System.out.println(message);
525         }
526
527         @Override
528         public void show (final Contact contact) {
529                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
530         }
531
532         @Override
533         public void showCurrentMenu () {
534                 this.showMenu(this.getCurrentMenu());
535         }
536
537         @Override
538         public void showEntry (final SelectableMenuItem item) {
539                 // Access key then text
540                 this.outputMessage(MessageFormat.format("[{0}] {1}", item.getAccessKey(), item.getText())); //NOI18N
541         }
542
543         @Override
544         public void showWelcome () {
545                 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle())); //NOI18N
546                 this.outputMessage(""); //NOI18N
547                 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software"); //NOI18N
548
549                 // Debug message
550                 this.getLogger().logDebug("Intro shown to user"); //NOI18N
551         }
552
553         @Override
554         public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
555                 // Trace message
556                 this.getLogger().logTrace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
557
558                 // Contact must not be null
559                 if (null == contact) {
560                         // Abort here
561                         throw new NullPointerException("contact is null"); //NOI18N
562                 }
563
564                 // Ask the user for editing [name], [a]ddress or [other] data
565                 char choice = this.enterChar(new char[] {'n', 'a', 'o', 'x'}, "Welchen Daten möchten Sie ändern? (n=Namensdaten, a=Anschriftsdaten, o=Andere, x=Zurück zur Hauptauswahl) ");
566
567                 // Get manager and cast it
568                 ContactFacade manager = (ContactFacade) this.getFacade();
569
570                 // TODO Get rid of this ugly switch block, too
571                 switch (choice) {
572                         case 'n': // Name data
573                                 manager.doChangeNameData(contact);
574                                 break;
575
576                         case 'a': // Address data
577                                 manager.doChangeAddressData(contact);
578                                 break;
579
580                         case 'o': // Other data
581                                 manager.doChangeOtherData(contact);
582                                 break;
583
584                         case 'x': // Exit this menu
585                                 // Ignored as it should go back
586                                 break;
587
588                         default:
589                                 // TODO throw own exception
590                                 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
591                 }
592
593                 // Trace message
594                 this.getLogger().logTrace("EXIT!"); //NOI18N
595         }
596
597         /**
598          * Reads one character
599          * <p>
600          * @return A single character
601          */
602         private char readChar () {
603                 // Read line
604                 String input = this.readString();
605
606                 // Debug message
607                 this.getLogger().logDebug(MessageFormat.format("input={0}", input)); //NOI18N
608
609                 // This must be only one character
610                 if (input.length() != 1) {
611                         // Return zero
612                         return 0;
613                 }
614
615                 // Get char from first (and only) position
616                 return input.charAt(0);
617         }
618
619         /**
620          * Reads an integer (int) from user
621          * <p>
622          * @return An integer number
623          */
624         private int readInt () {
625                 // First read a string
626                 String input = this.readString();
627
628                 // Debug message
629                 this.getLogger().logDebug(MessageFormat.format("input={0}", input)); //NOI18N
630
631                 // Init number with invalid value
632                 int num = -1;
633
634                 // Parse number, this can be risky
635                 try {
636                         num = Integer.parseInt(input);
637                 } catch (final NumberFormatException e) {
638                         this.outputMessage("Bitte geben Sie nur Zahlen ein!");
639                         this.getLogger().logWarning(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage())); //NOI18N
640                 }
641
642                 // Trace message
643                 this.getLogger().logTrace(MessageFormat.format("num={0} - EXIT!", num)); //NOI18N
644
645                 // Return read number
646                 return num;
647         }
648
649         /**
650          * Reads a string from a scanner until RETURN is pressed
651          * <p>
652          * @return Read string from scanner
653          */
654         private String readString () {
655                 return this.scanner.nextLine();
656         }
657
658         @Override
659         protected final void fillMenuMap () {
660                 // Trace message
661                 this.getLogger().logTrace("CALLED!"); //NOI18N
662
663                 // Initialize first (main) menu
664                 Menu menu = new ConsoleMenu("main", this); //NOI18N
665
666                 // Add it
667                 this.getMenus().put("main", menu); //NOI18N
668
669                 // Trace message
670                 this.getLogger().logTrace("EXIT!"); //NOI18N
671         }
672 }