]> git.mxchange.org Git - addressbook-swing.git/blob - src/org/mxchange/addressbook/client/console/ConsoleClient.java
Updated copyright year
[addressbook-swing.git] / src / org / mxchange / addressbook / client / console / ConsoleClient.java
1 /*
2  * Copyright (C) 2016 Roland Haeder
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 package org.mxchange.addressbook.client.console;
18
19 import java.io.IOException;
20 import java.sql.SQLException;
21 import java.text.MessageFormat;
22 import java.util.Arrays;
23 import java.util.Scanner;
24 import org.mxchange.addressbook.application.AddressbookApplication;
25 import org.mxchange.addressbook.client.AddressbookClient;
26 import org.mxchange.addressbook.client.BaseAddressbookClient;
27 import org.mxchange.addressbook.facade.contact.ContactFacade;
28 import org.mxchange.addressbook.menu.Menu;
29 import org.mxchange.addressbook.menu.MenuTools;
30 import org.mxchange.addressbook.menu.console.ConsoleMenu;
31 import org.mxchange.addressbook.menu.item.SelectableMenuItem;
32 import org.mxchange.addressbook.menu.item.console.ConsoleMenuItem;
33 import org.mxchange.jcontacts.contact.Contact;
34 import org.mxchange.jcontacts.contact.UserContact;
35 import org.mxchange.jcontacts.contact.gender.Gender;
36 import org.mxchange.jcontacts.contact.gender.GenderUtils;
37 import org.mxchange.jcontacts.exceptions.ContactAlreadyAddedException;
38 import org.mxchange.jcore.application.Application;
39 import org.mxchange.jcore.exceptions.MenuInitializationException;
40 import org.mxchange.jcore.exceptions.UnhandledUserChoiceException;
41 import org.mxchange.jcountry.data.Country;
42 import org.mxchange.jphone.phonenumbers.cellphone.DialableCellphoneNumber;
43 import org.mxchange.jphone.phonenumbers.fax.DialableFaxNumber;
44 import org.mxchange.jphone.phonenumbers.landline.DialableLandLineNumber;
45
46 /**
47  * A client for the console
48  * <p>
49  * @author Roland Haeder
50  */
51 public class ConsoleClient extends BaseAddressbookClient implements AddressbookClient {
52
53         /**
54          * Scanner instance for reading data from console input
55          */
56         private final Scanner scanner;
57
58         /**
59          * Parameterless constructor
60          * <p>
61          * @param application An instance of an Application class
62          */
63         public ConsoleClient (final Application application) {
64                 // Trace message
65                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("application={0} - CALLED!", application)); //NOI18N
66
67                 // Set application instance
68                 this.setApplication(application);
69
70                 // Init scanner instance
71                 this.scanner = new Scanner(System.in, "UTF-8"); //NOI18N
72
73                 // Trace message
74                 this.getLoggerBeanLocal().logTrace("EXIT!"); //NOI18N
75         }
76
77         @Override
78         public void displayAddressBox (final Contact contact) {
79                 // Trace message
80                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
81
82                 // Is it null?
83                 if (null == contact) {
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.getContactStreet(), contact.getContactZipCode(), contact.getContactCity(), contact.getContactCountry()));
90
91                 // Trace message
92                 this.getLoggerBeanLocal().logTrace("EXIT!"); //NOI18N
93         }
94
95         @Override
96         public void displayNameBox (final Contact contact) {
97                 // Trace message
98                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
99
100                 // Is it null?
101                 if (null == contact) {
102                         // Abort here
103                         throw new NullPointerException("contact is null"); //NOI18N
104                 }
105
106                 // Get translated gender as the user may want to see "Mr.", "Mrs."
107                 String gender = GenderUtils.getTranslatedGender(contact);
108
109                 // Now put all together: gender, surname, family name
110                 this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getContactFirstName(), contact.getContactFamilyName()));
111
112                 // Trace message
113                 this.getLoggerBeanLocal().logTrace("EXIT!"); //NOI18N
114         }
115
116         @Override
117         public void displayOtherDataBox (final Contact contact) {
118                 // Trace message
119                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
120
121                 // Is it null?
122                 if (null == contact) {
123                         // Abort here
124                         throw new NullPointerException("contact is null"); //NOI18N
125                 }
126
127                 // Cellphone and such ...
128                 this.outputMessage(MessageFormat.format("Telefonnumer: {0}\nFaxnummer: {1}\nHandy: {2}\nKommentar:\n{3}", contact.getContactPhoneNumber(), contact.getContactFaxNumber(), contact.getContactCellphoneNumber(), contact.getContactComment()));
129
130                 // Trace message
131                 this.getLoggerBeanLocal().logTrace("EXIT!"); //NOI18N
132         }
133
134         @Override
135         public void doChangeOwnAddressData (final Contact contact) {
136                 // Trace message
137                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
138
139                 // Is it null?
140                 if (null == contact) {
141                         // Abort here
142                         throw new NullPointerException("contact is null"); //NOI18N
143                 }
144
145                 // Make sure it is own contact
146                 if (!contact.isOwnContact()) {
147                         // Not own contact
148                         throw new IllegalArgumentException("Contact is not own data."); //NOI18N
149                 }
150
151                 // Get manager and cast it
152                 ContactFacade manager = (ContactFacade) this.getFacade();
153
154                 // Own street and number
155                 String streetNumber = manager.enterOwnStreet();
156
157                 // Get zip code
158                 Integer zipCode = manager.enterOwnZipCode();
159
160                 // Get city name
161                 String city = manager.enterOwnCity();
162
163                 // Get country code
164                 Country country = manager.enterOwnCountryCode();
165
166                 // Update address data
167                 contact.setContactStreet(streetNumber);
168                 contact.setContactZipCode(zipCode);
169                 contact.setContactCity(city);
170                 contact.setContactCountry(country);
171
172                 // Trace message
173                 this.getLoggerBeanLocal().logTrace("EXIT!"); //NOI18N
174         }
175
176         @Override
177         public void doChangeOwnNameData (final Contact contact) {
178                 // Trace message
179                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
180
181                 // Is it null?
182                 if (null == contact) {
183                         // Abort here
184                         throw new NullPointerException("contact is null"); //NOI18N
185                 }
186
187                 // Make sure it is own contact
188                 if (!contact.isOwnContact()) {
189                         // Not own contact
190                         throw new IllegalArgumentException("Contact is not own data."); //NOI18N
191                 }
192
193                 // Get manager and cast it
194                 ContactFacade manager = (ContactFacade) this.getFacade();
195
196                 // Gender:
197                 Gender gender = manager.enterOwnGender();
198
199                 // Surname
200                 String firstName = manager.enterOwnFirstName();
201
202                 // Family name
203                 String familyName = manager.enterOwnFamilyName();
204
205                 // Update contact instance
206                 contact.setContactGender(gender);
207                 contact.setContactFirstName(firstName);
208                 contact.setContactFamilyName(familyName);
209
210                 // Trace message
211                 this.getLoggerBeanLocal().logTrace("EXIT!"); //NOI18N
212         }
213
214         @Override
215         public void doChangeOwnOtherData (final Contact contact) {
216                 // Trace message
217                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
218
219                 // Is it null?
220                 if (null == contact) {
221                         // Abort here
222                         throw new NullPointerException("contact is null"); //NOI18N
223                 }
224
225                 // Make sure it is own contact
226                 if (!contact.isOwnContact()) {
227                         // Not own contact
228                         throw new IllegalArgumentException("Contact is not own data."); //NOI18N
229                 }
230
231                 // Get manager and cast it
232                 ContactFacade manager = (ContactFacade) this.getFacade();
233
234                 // Phone number
235                 DialableLandLineNumber phoneNumber = manager.enterOwnPhoneNumber();
236
237                 // Phone number
238                 DialableCellphoneNumber cellphonePhoneNumber = manager.enterOwnCellNumber();
239
240                 // Fax number
241                 DialableFaxNumber faxNumber = manager.enterOwnFaxNumber();
242
243                 // Email address
244                 String email = manager.enterOwnEmailAddress();
245
246                 // Comment
247                 String comment = manager.enterOwnComment();
248
249                 // Update contact instance
250                 contact.setContactPhoneNumber(phoneNumber);
251                 contact.setContactCellphoneNumber(cellphonePhoneNumber);
252                 contact.setContactFaxNumber(faxNumber);
253                 contact.setContactEmailAddress(email);
254                 contact.setContactComment(comment);
255
256                 // Trace message
257                 this.getLoggerBeanLocal().logTrace("EXIT!"); //NOI18N
258         }
259
260         @Override
261         public Contact doEnterOwnData () {
262                 // Trace message
263                 this.getLoggerBeanLocal().logTrace("CALLED!"); //NOI18N
264
265                 // Get manager and cast it
266                 ContactFacade manager = (ContactFacade) this.getFacade();
267
268                 // First ask for gender
269                 Gender gender = manager.enterOwnGender();
270
271                 // 2nd for first name
272                 String firstName = manager.enterOwnFirstName();
273
274                 // And 3rd for family name
275                 String familyName = manager.enterOwnFamilyName();
276
277                 // Construct UserContact instance
278                 Contact contact = new UserContact(gender, firstName, familyName);
279
280                 // Trace message
281                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
282
283                 // And return object
284                 return contact;
285         }
286
287         @Override
288         public void doShutdown () throws SQLException, IOException {
289                 // Trace message
290                 this.getLoggerBeanLocal().logTrace("CALLED!"); //NOI18N
291
292                 // Parent call
293                 super.doShutdown();
294
295                 // TODO Add other shutdown stuff
296                 // Trace message
297                 this.getLoggerBeanLocal().logTrace("EXIT!"); //NOI18N
298         }
299
300         @Override
301         public void doUserMenuChoice () throws UnhandledUserChoiceException, MenuInitializationException {
302                 // Trace message
303                 this.getLoggerBeanLocal().logTrace("CALLED!"); //NOI18N
304
305                 // Get all access keys from menu
306                 char[] accessKeys = MenuTools.getAccessKeysFromMenuMap(this.getMenus(), this.getCurrentMenu());
307
308                 // Output textural message and ask for a char as input
309                 char choice = this.enterChar(accessKeys, "Bitte Auswahl eingeben (0=Programm beenden): ");
310
311                 // Get manager and cast it
312                 ContactFacade manager = (ContactFacade) this.getFacade();
313
314                 // TODO Rewrite this ugly switch() block
315                 switch (choice) {
316                         case '1':
317                                 try {
318                                         // Enter/add own data
319                                         manager.doEnterOwnData();
320                                 } catch (final ContactAlreadyAddedException ex) {
321                                         // Already added
322                                         this.outputMessage("Sie haben bereits Ihre eigenen Daten eingegeben.");
323                                 }
324                                 break;
325
326                         case '2': // Change own data
327                                 manager.doChangeOwnData();
328                                 break;
329
330                         case '3': // Add new addess
331                                 manager.doAddOtherAddress();
332                                 break;
333
334                         case '4': // List contacts
335                                 manager.doListContacts();
336                                 break;
337
338                         case '5': // Search addresses
339                                 manager.doSearchContacts();
340                                 break;
341
342                         case '6': // Change other addess
343                                 manager.doChangeOtherAddress();
344                                 break;
345
346                         case '7': // Delete other address
347                                 manager.doDeleteOtherAddress();
348                                 break;
349
350                         case '0':
351                                 try {
352                                         // Program exit
353                                         this.getApplication().doShutdown();
354                                 } catch (final SQLException | IOException ex) {
355                                         this.abortProgramWithException(ex);
356                                 }
357                                 break;
358
359                         default:
360                                 // TODO throw own exception
361                                 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
362                 }
363
364                 // Trace message
365                 this.getLoggerBeanLocal().logTrace("EXIT!"); //NOI18N
366         }
367
368         @Override
369         public char enterChar (final char[] validChars, final String message) {
370                 // Trace message
371                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("validChars={0},message={1} - CALLED!", Arrays.toString(validChars), message)); //NOI18N
372
373                 // The validChars must not null be null and filled with at least one char
374                 if (null == validChars) {
375                         // Is null
376                         throw new NullPointerException("validChars is null"); //NOI18N
377                 } else if (validChars.length == 0) {
378                         // Is not filled
379                         throw new IllegalArgumentException("validChars is not filled."); //NOI18N
380                 }
381
382                 char input = 0;
383
384                 // Sort array, else binarySearch() won't work
385                 Arrays.sort(validChars);
386
387                 // Keep asking until valid char has been entered
388                 while (Arrays.binarySearch(validChars, input) < 0) {
389                         // Output message
390                         System.out.print(message);
391
392                         // Read char
393                         input = this.readChar();
394                 }
395
396                 // Trace message
397                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
398
399                 // Return read char
400                 return input;
401         }
402
403         @Override
404         public Gender enterGender (final String message) {
405                 // Trace message
406                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("message={0} - CALLED!", message)); //NOI18N
407
408                 // Get valid chars
409                 char[] validChars = Gender.validChars();
410
411                 // Debug message
412                 //* NOISY-DEBUG: */ System.out.println(validChars);
413                 // Call inner method
414                 char gender = this.enterChar(validChars, message);
415
416                 // Now get a Gender instance back
417                 Gender g = Gender.fromChar(gender);
418
419                 // g must not be null
420                 assert (g instanceof Gender) : "g is not set."; //NOI18N
421
422                 // Trace message
423                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("g={0} - EXIT!", g)); //NOI18N
424
425                 // Return it
426                 return g;
427         }
428
429         @Override
430         public int enterInt (final int minimum, final int maximum, final String message) {
431                 // Trace message
432                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("minimum={0},maximum={1},message={2} - CALLED!", minimum, maximum, message)); //NOI18N
433
434                 // Minimum should not be below zero
435                 assert (minimum >= 0) : MessageFormat.format("minimum={0} is below zero", minimum); //NOI18N
436                 assert (maximum > minimum) : MessageFormat.format("maximum {0} is smaller than minimum {1}", maximum, minimum); //NOI18N
437
438                 // Init input
439                 int input = -1;
440
441                 while ((input < minimum) || (input > maximum)) {
442                         // Output message
443                         System.out.print(message);
444
445                         // Read integer from user
446                         input = this.readInt();
447                 }
448
449                 // Trace message
450                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
451
452                 // Return it
453                 return input;
454         }
455
456         @Override
457         public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
458                 // Trace message
459                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("minLength={0},maxLength={1},message={2}allowEmpty={3} - CALLED!", minLength, maxLength, message, allowEmpty)); //NOI18N
460
461                 // Check on length, e.g. country codes are excactly 2 chars long
462                 assert (maxLength >= minLength);
463
464                 // Init input
465                 String input = null;
466
467                 // Check if it is to short or to long
468                 while (((null == input) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
469                         // Output message
470                         System.out.print(message);
471
472                         // Read line
473                         input = this.readString();
474                 }
475
476                 // Trace message
477                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
478
479                 // Return it
480                 return input;
481         }
482
483         @Override
484         public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
485                 // Return a new console menu item
486                 return new ConsoleMenuItem(accessKey, text);
487         }
488
489         @Override
490         public void init () {
491                 // Trace message
492                 this.getLoggerBeanLocal().logTrace("CALLED!"); //NOI18N
493
494                 // Init contact manager here
495                 try {
496                         this.initContactManager();
497                 } catch (final SQLException ex) {
498                         // End here
499                         this.abortProgramWithException(ex);
500                 }
501
502                 // Fill menu map
503                 this.fillMenuMap();
504
505                 // Trace message
506                 this.getLoggerBeanLocal().logTrace("EXIT!"); //NOI18N
507         }
508
509         @Override
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 Haeder, 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 }