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