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