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