2 * Copyright (C) 2015 Roland Haeder
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.
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.
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/>.
17 package org.mxchange.addressbook.client.console;
19 import java.text.MessageFormat;
20 import java.util.Arrays;
21 import java.util.Scanner;
22 import org.mxchange.addressbook.application.AddressbookApplication;
23 import org.mxchange.addressbook.client.AddressbookClient;
24 import org.mxchange.addressbook.client.BaseAddressbookClient;
25 import org.mxchange.jcore.contact.Contact;
26 import org.mxchange.jcore.contact.Gender;
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.exceptions.UnhandledUserChoiceException;
39 * A client for the console
41 * @author Roland Haeder
43 public class ConsoleClient extends BaseAddressbookClient implements AddressbookClient {
46 * Scanner instance for reading data from console input
48 private final Scanner scanner;
51 * Parameterless constructor
53 * @param application An instance of an Application class
55 public ConsoleClient (final Application application) {
57 this.getLogger().trace(MessageFormat.format("application={0} - CALLED!", application)); //NOI18N
59 // Set application instance
60 this.setApplication(application);
62 // Init scanner instance
63 this.scanner = new Scanner(System.in, "UTF-8"); //NOI18N
66 this.getLogger().trace("EXIT!"); //NOI18N
70 * Displays a textual address "box" of given contact
72 * @param contact Contact to show address for
75 public void displayAddressBox (final Contact contact) {
77 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
80 if (contact == null) {
82 throw new NullPointerException("contact is null"); //NOI18N
86 this.outputMessage(MessageFormat.format("Strasse, PLZ Ort, Land: {0}\n{1} {2}\n{3}", contact.getStreet(), contact.getZipCode(), contact.getCity(), contact.getCountryCode()));
89 this.getLogger().trace("EXIT!"); //NOI18N
93 * Displays a textual name "box" of given contact
95 * @param contact Contact to show name for
98 public void displayNameBox (final Contact contact) {
100 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
103 if (contact == null) {
105 throw new NullPointerException("contact is null"); //NOI18N
108 // Get translated gender as the user may want to see "Mr.", "Mrs."
109 String gender = contact.getTranslatedGender();
112 String companyName = contact.getCompanyName();
114 // If it is empty/null, then assume private contact
115 if ((companyName == null) || (companyName.isEmpty())) {
116 // Now put all together: gender, surname, family name
118 this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getSurname(), contact.getFamilyName()));
121 this.outputMessage(MessageFormat.format("Firma: {0}\nAnsprechpartner: {1} {2} {3}", companyName, gender, contact.getSurname(), contact.getFamilyName()));
125 this.getLogger().trace("EXIT!"); //NOI18N
129 * Displays a textual other data "box" of given contact
131 * @param contact Contact to show other data for
134 public void displayOtherDataBox (final Contact contact) {
136 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
139 if (contact == null) {
141 throw new NullPointerException("contact is null"); //NOI18N
144 // Cellphone and such ...
145 this.outputMessage(MessageFormat.format("Telefonnumer: {0}\nFaxnummer: {1}\nHandy: {2}\nKommentar:\n{3}", contact.getPhoneNumber(), contact.getFaxNumber(), contact.getCellphoneNumber(), contact.getComment()));
148 this.getLogger().trace("EXIT!"); //NOI18N
152 public void doChangeOwnAddressData (final Contact contact) {
154 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
157 if (contact == null) {
159 throw new NullPointerException("contact is null"); //NOI18N
162 // Make sure it is own contact
163 if (!contact.isOwnContact()) {
165 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
168 // Get manager and cast it
169 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
171 // Own street and number
172 String streetNumber = manager.enterOwnStreet();
175 int zipCode = manager.enterOwnZipCode();
178 String city = manager.enterOwnCity();
181 String countryCode = manager.enterOwnCountryCode();
183 // Update address data
184 contact.setStreet(streetNumber);
185 contact.setZipCode(zipCode);
186 contact.setCity(city);
187 contact.setCountryCode(countryCode);
190 this.getLogger().trace("EXIT!"); //NOI18N
194 public void doChangeOwnNameData (final Contact contact) {
196 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
199 if (contact == null) {
201 throw new NullPointerException("contact is null"); //NOI18N
204 // Make sure it is own contact
205 if (!contact.isOwnContact()) {
207 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
210 // Get manager and cast it
211 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
214 Gender gender = manager.enterOwnGender();
217 String surname = manager.enterOwnSurname();
220 String familyName = manager.enterOwnFamilyName();
223 String companyName = manager.enterOwnCompanyName();
225 // Update contact instance
226 contact.setGender(gender);
227 contact.setSurname(surname);
228 contact.setFamilyName(familyName);
229 contact.setCompanyName(companyName);
232 this.getLogger().trace("EXIT!"); //NOI18N
236 public void doChangeOwnOtherData (final Contact contact) {
238 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
241 if (contact == null) {
243 throw new NullPointerException("contact is null"); //NOI18N
246 // Make sure it is own contact
247 if (!contact.isOwnContact()) {
249 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
252 // Get manager and cast it
253 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
256 String phoneNumber = manager.enterOwnPhoneNumber();
259 String cellphonePhoneNumber = manager.enterOwnCellNumber();
262 String faxNumber = manager.enterOwnFaxNumber();
265 String email = manager.enterOwnEmailAddress();
268 String comment = manager.enterOwnComment();
270 // Update contact instance
271 contact.setPhoneNumber(phoneNumber);
272 contact.setCellphoneNumber(cellphonePhoneNumber);
273 contact.setFaxNumber(faxNumber);
274 contact.setEmailAddress(email);
275 contact.setComment(comment);
278 this.getLogger().trace("EXIT!"); //NOI18N
282 public Contact doEnterOwnData () {
284 this.getLogger().trace("CALLED!"); //NOI18N
286 // Get manager and cast it
287 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
289 // First ask for gender
290 Gender gender = manager.enterOwnGender();
293 String surname = manager.enterOwnSurname();
295 // And 3rd for family name
296 String familyName = manager.enterOwnFamilyName();
299 String companyName = manager.enterOwnCompanyName();
301 // Construct UserContact instance
302 Contact contact = new UserContact(gender, surname, familyName, companyName);
305 this.getLogger().trace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
312 * Shutdown this client
315 public void doShutdown () {
317 this.getLogger().trace("CALLED!"); //NOI18N
322 // @TODO Add other shutdown stuff
325 this.getLogger().trace("EXIT!"); //NOI18N
329 public void doUserMenuChoice () throws UnhandledUserChoiceException {
331 this.getLogger().trace("CALLED!"); //NOI18N
333 // Get all access keys from menu
334 char[] accessKeys = MenuTools.getAccessKeysFromMenuMap(this.getMenus(), this.getCurrentMenu());
336 // Output textural message and ask for a char as input
337 char choice = this.enterChar(accessKeys, "Bitte Auswahl eingeben (0=Programm beenden): ");
339 // Get manager and cast it
340 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
342 // @TODO Rewrite this ugly switch() block
346 // Enter/add own data
347 manager.doEnterOwnData();
348 } catch (final ContactAlreadyAddedException ex) {
350 this.outputMessage("Sie haben bereits Ihre eigenen Daten eingegeben.");
354 case '2': // Change own data
355 manager.doChangeOwnData();
358 case '3': // Add new addess
359 manager.doAddOtherAddress();
362 case '4': // List contacts
363 manager.doListContacts();
366 case '5': // Search addresses
367 manager.doSearchContacts();
370 case '6': // Change other addess
371 manager.doChangeOtherAddress();
374 case '7': // Delete other address
375 manager.doDeleteOtherAddress();
378 case '0': // Program exit
379 this.getApplication().doShutdown();
383 // @TODO throw own exception
384 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
388 this.getLogger().trace("EXIT!"); //NOI18N
392 * Asks the the user to enter a single character which must match validChars
394 * @param validChars Valid chars that are accepted
395 * @param message Message to user
396 * @return Allowed character
399 public char enterChar (final char[] validChars, final String message) {
401 this.getLogger().trace(MessageFormat.format("validChars={0},message={1} - CALLED!", Arrays.toString(validChars), message)); //NOI18N
403 // The validChars must not null be null and filled with at least one char
404 if (validChars == null) {
406 throw new NullPointerException("validChars is null"); //NOI18N
407 } else if (validChars.length == 0) {
409 throw new IllegalArgumentException("validChars is not filled."); //NOI18N
414 // Sort array, else binarySearch() won't work
415 Arrays.sort(validChars);
417 // Keep asking until valid char has been entered
418 while (Arrays.binarySearch(validChars, input) < 0) {
420 System.out.print(message);
423 input = this.readChar();
427 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
434 * Asks the user to enter his/her gender
436 * @param message Message to the user
437 * @return Gender enum
440 public Gender enterGender (final String message) {
442 this.getLogger().trace(MessageFormat.format("message={0} - CALLED!", message)); //NOI18N
445 char[] validChars = Gender.validChars();
448 //* NOISY-DEBUG: */ System.out.println(validChars);
450 char gender = this.enterChar(validChars, message);
452 // Now get a Gender instance back
453 Gender g = Gender.fromChar(gender);
455 // g must not be null
456 assert(g instanceof Gender) : "g is not set."; //NOI18N
459 this.getLogger().trace(MessageFormat.format("g={0} - EXIT!", g)); //NOI18N
466 * Reads an integer (int) with a textural message from the user
468 * @param minimum Minimum allowed number
469 * @param maximum Maximum allowed number
470 * @param message Messager to display in console
474 public int enterInt (final int minimum, final int maximum, final String message) {
476 this.getLogger().trace(MessageFormat.format("minimum={0},maximum={1},message={2} - CALLED!", minimum, maximum, message)); //NOI18N
478 // Minimum should not be below zero
479 assert (minimum >= 0);
480 assert (maximum > minimum);
485 while ((input < minimum) || (input > maximum)) {
487 System.out.print(message);
489 // Read integer from user
490 input = this.readInt();
494 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
501 * Reads a string of minimum and maximum length from the user
503 * @param minLength Minimum length of the string to read
504 * @param maxLength Maximum length of the string to read
505 * @param message Message to user
506 * @param allowEmpty Whether to allow empty string
507 * @return Entered string by user or null for empty strings
510 public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
512 this.getLogger().trace(MessageFormat.format("minLength={0},maxLength={1},message={2}allowEmpty={3} - CALLED!", minLength, maxLength, message, allowEmpty)); //NOI18N
514 // Check on length, e.g. country codes are excactly 2 chars long
515 assert (maxLength >= minLength);
520 // Check if it is to short or to long
521 while (((input == null) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
523 System.out.print(message);
526 input = this.readString();
530 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
537 * Returns a console menu item
539 * @param accessKey Key to access the menu
540 * @param text Text to show to user
541 * @return A SelectableMenuItem
542 * @todo Make sure the access key is unique
545 public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
546 // Return a new console menu item
547 return new ConsoleMenuItem(accessKey, text);
551 * Inizializes this client
554 public void init () {
556 this.getLogger().trace("CALLED!"); //NOI18N
558 // Init contact manager here
559 this.initContactManager();
565 this.getLogger().trace("EXIT!"); //NOI18N
569 * Displays textural message to the user
574 public void outputMessage (final String message) {
575 System.out.println(message);
579 * Shows textural menu on console
582 public void showCurrentMenu () {
583 this.showMenu(this.getCurrentMenu());
587 * Shows given menu entry to user
589 * @param item Menu entry
592 public void showEntry (final SelectableMenuItem item) {
593 // Access key then text
594 this.outputMessage(MessageFormat.format("[{0}] {1}", item.getAccessKey(), item.getText()));
598 * Shows a textural message to the user
601 public void showWelcome () {
602 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle()));
603 this.outputMessage("");
604 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software");
607 this.getLogger().debug("Intro shown to user"); //NOI18N
611 public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
613 this.getLogger().trace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
615 // Contact must not be null
616 if (contact == null) {
618 throw new NullPointerException("contact is null"); //NOI18N
621 // Ask the user for editing [name], [a]ddress or [other] data
622 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) ");
624 // Get manager and cast it
625 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
627 // @TODO Get rid of this ugly switch block, too
629 case 'n': // Name data
630 manager.doChangeNameData(contact);
633 case 'a': // Address data
634 manager.doChangeAddressData(contact);
637 case 'o': // Other data
638 manager.doChangeOtherData(contact);
641 case 'x': // Exit this menu
642 // Ignored as it should go back
646 // @TODO throw own exception
647 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
651 this.getLogger().trace("EXIT!"); //NOI18N
655 * Reads one character
657 * @return A single character
659 private char readChar () {
661 String input = this.readString();
664 this.getLogger().debug(MessageFormat.format("input={0}", input)); //NOI18N
666 // This must be only one character
667 if (input.length() != 1) {
672 // Get char from first (and only) position
673 return input.charAt(0);
677 * Reads an integer (int) from user
679 * @return An integer number
681 private int readInt () {
682 // First read a string
683 String input = this.readString();
686 this.getLogger().debug(MessageFormat.format("input={0}", input)); //NOI18N
688 // Init number with invalid value
691 // Parse number, this can be risky
693 num = Integer.parseInt(input);
694 } catch (final NumberFormatException e) {
695 this.outputMessage("Bitte geben Sie nur Zahlen ein!");
696 this.getLogger().warn(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage())); //NOI18N
700 this.getLogger().trace(MessageFormat.format("num={0} - EXIT!", num)); //NOI18N
702 // Return read number
707 * Reads a string from a scanner until RETURN is pressed
709 * @return Read string from scanner
711 private String readString () {
712 return this.scanner.nextLine();
716 * Fills menu map with menu entries
719 protected final void fillMenuMap () {
721 this.getLogger().trace("CALLED!"); //NOI18N
723 // Initialize first (main) menu
724 Menu menu = new ConsoleMenu("main", this); //NOI18N
727 this.getMenus().put("main", menu); //NOI18N
730 this.getLogger().trace("EXIT!"); //NOI18N