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