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.io.IOException;
20 import java.sql.SQLException;
21 import java.text.MessageFormat;
22 import java.util.Arrays;
23 import java.util.Scanner;
24 import org.mxchange.addressbook.application.AddressbookApplication;
25 import org.mxchange.addressbook.client.AddressbookClient;
26 import org.mxchange.addressbook.client.BaseAddressbookClient;
27 import org.mxchange.addressbook.contact.user.UserContact;
28 import org.mxchange.addressbook.exceptions.ContactAlreadyAddedException;
29 import org.mxchange.addressbook.manager.contact.ManageableAddressbookContact;
30 import org.mxchange.addressbook.menu.Menu;
31 import org.mxchange.addressbook.menu.MenuTools;
32 import org.mxchange.addressbook.menu.console.ConsoleMenu;
33 import org.mxchange.addressbook.menu.item.SelectableMenuItem;
34 import org.mxchange.addressbook.menu.item.console.ConsoleMenuItem;
35 import org.mxchange.jcore.application.Application;
36 import org.mxchange.jcore.contact.Contact;
37 import org.mxchange.jcore.contact.Gender;
38 import org.mxchange.jcore.exceptions.UnhandledUserChoiceException;
39 import org.mxchange.jcore.exceptions.UnsupportedDatabaseBackendException;
42 * A client for the console
44 * @author Roland Haeder
46 public class ConsoleClient extends BaseAddressbookClient implements AddressbookClient {
49 * Scanner instance for reading data from console input
51 private final Scanner scanner;
54 * Parameterless constructor
56 * @param application An instance of an Application class
58 public ConsoleClient (final Application application) {
60 this.getLogger().trace(MessageFormat.format("application={0} - CALLED!", application)); //NOI18N
62 // Set application instance
63 this.setApplication(application);
65 // Init scanner instance
66 this.scanner = new Scanner(System.in, "UTF-8"); //NOI18N
69 this.getLogger().trace("EXIT!"); //NOI18N
73 * Displays a textual address "box" of given contact
75 * @param contact Contact to show address for
78 public void displayAddressBox (final Contact contact) {
80 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
83 if (contact == null) {
85 throw new NullPointerException("contact is null"); //NOI18N
89 this.outputMessage(MessageFormat.format("Strasse, PLZ Ort, Land: {0}\n{1} {2}\n{3}", contact.getStreet(), contact.getZipCode(), contact.getCity(), contact.getCountryCode()));
92 this.getLogger().trace("EXIT!"); //NOI18N
96 * Displays a textual name "box" of given contact
98 * @param contact Contact to show name for
101 public void displayNameBox (final Contact contact) {
103 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
106 if (contact == null) {
108 throw new NullPointerException("contact is null"); //NOI18N
111 // Get translated gender as the user may want to see "Mr.", "Mrs."
112 String gender = contact.getTranslatedGender();
115 String companyName = contact.getCompanyName();
117 // If it is empty/null, then assume private contact
118 if ((companyName == null) || (companyName.isEmpty())) {
119 // Now put all together: gender, surname, family name
121 this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getSurname(), contact.getFamilyName()));
124 this.outputMessage(MessageFormat.format("Firma: {0}\nAnsprechpartner: {1} {2} {3}", companyName, gender, contact.getSurname(), contact.getFamilyName()));
128 this.getLogger().trace("EXIT!"); //NOI18N
132 * Displays a textual other data "box" of given contact
134 * @param contact Contact to show other data for
137 public void displayOtherDataBox (final Contact contact) {
139 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
142 if (contact == null) {
144 throw new NullPointerException("contact is null"); //NOI18N
147 // Cellphone and such ...
148 this.outputMessage(MessageFormat.format("Telefonnumer: {0}\nFaxnummer: {1}\nHandy: {2}\nKommentar:\n{3}", contact.getPhoneNumber(), contact.getFaxNumber(), contact.getCellphoneNumber(), contact.getComment()));
151 this.getLogger().trace("EXIT!"); //NOI18N
155 public void doChangeOwnAddressData (final Contact contact) {
157 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
160 if (contact == null) {
162 throw new NullPointerException("contact is null"); //NOI18N
165 // Make sure it is own contact
166 if (!contact.isOwnContact()) {
168 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
171 // Get manager and cast it
172 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
174 // Own street and number
175 String streetNumber = manager.enterOwnStreet();
178 Long zipCode = (long) manager.enterOwnZipCode();
181 String city = manager.enterOwnCity();
184 String countryCode = manager.enterOwnCountryCode();
186 // Update address data
187 contact.setStreet(streetNumber);
188 contact.setZipCode(zipCode);
189 contact.setCity(city);
190 contact.setCountryCode(countryCode);
193 this.getLogger().trace("EXIT!"); //NOI18N
197 public void doChangeOwnNameData (final Contact contact) {
199 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
202 if (contact == null) {
204 throw new NullPointerException("contact is null"); //NOI18N
207 // Make sure it is own contact
208 if (!contact.isOwnContact()) {
210 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
213 // Get manager and cast it
214 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
217 Gender gender = manager.enterOwnGender();
220 String surname = manager.enterOwnSurname();
223 String familyName = manager.enterOwnFamilyName();
226 String companyName = manager.enterOwnCompanyName();
228 // Update contact instance
229 contact.setGender(gender);
230 contact.setSurname(surname);
231 contact.setFamilyName(familyName);
232 contact.setCompanyName(companyName);
235 this.getLogger().trace("EXIT!"); //NOI18N
239 public void doChangeOwnOtherData (final Contact contact) {
241 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
244 if (contact == null) {
246 throw new NullPointerException("contact is null"); //NOI18N
249 // Make sure it is own contact
250 if (!contact.isOwnContact()) {
252 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
255 // Get manager and cast it
256 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
259 String phoneNumber = manager.enterOwnPhoneNumber();
262 String cellphonePhoneNumber = manager.enterOwnCellNumber();
265 String faxNumber = manager.enterOwnFaxNumber();
268 String email = manager.enterOwnEmailAddress();
271 String comment = manager.enterOwnComment();
273 // Update contact instance
274 contact.setPhoneNumber(phoneNumber);
275 contact.setCellphoneNumber(cellphonePhoneNumber);
276 contact.setFaxNumber(faxNumber);
277 contact.setEmailAddress(email);
278 contact.setComment(comment);
281 this.getLogger().trace("EXIT!"); //NOI18N
285 public Contact doEnterOwnData () {
287 this.getLogger().trace("CALLED!"); //NOI18N
289 // Get manager and cast it
290 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
292 // First ask for gender
293 Gender gender = manager.enterOwnGender();
296 String surname = manager.enterOwnSurname();
298 // And 3rd for family name
299 String familyName = manager.enterOwnFamilyName();
302 String companyName = manager.enterOwnCompanyName();
304 // Construct UserContact instance
305 Contact contact = new UserContact(gender, surname, familyName, companyName);
308 this.getLogger().trace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
315 * Shutdown this client
318 public void doShutdown () throws SQLException, IOException {
320 this.getLogger().trace("CALLED!"); //NOI18N
325 // @TODO Add other shutdown stuff
328 this.getLogger().trace("EXIT!"); //NOI18N
332 public void doUserMenuChoice () throws UnhandledUserChoiceException {
334 this.getLogger().trace("CALLED!"); //NOI18N
336 // Get all access keys from menu
337 char[] accessKeys = MenuTools.getAccessKeysFromMenuMap(this.getMenus(), this.getCurrentMenu());
339 // Output textural message and ask for a char as input
340 char choice = this.enterChar(accessKeys, "Bitte Auswahl eingeben (0=Programm beenden): ");
342 // Get manager and cast it
343 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
345 // @TODO Rewrite this ugly switch() block
349 // Enter/add own data
350 manager.doEnterOwnData();
351 } catch (final ContactAlreadyAddedException ex) {
353 this.outputMessage("Sie haben bereits Ihre eigenen Daten eingegeben.");
357 case '2': // Change own data
358 manager.doChangeOwnData();
361 case '3': // Add new addess
362 manager.doAddOtherAddress();
365 case '4': // List contacts
366 manager.doListContacts();
369 case '5': // Search addresses
370 manager.doSearchContacts();
373 case '6': // Change other addess
374 manager.doChangeOtherAddress();
377 case '7': // Delete other address
378 manager.doDeleteOtherAddress();
381 case '0': // Program exit
382 this.getApplication().doShutdown();
386 // @TODO throw own exception
387 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
391 this.getLogger().trace("EXIT!"); //NOI18N
395 * Asks the the user to enter a single character which must match validChars
397 * @param validChars Valid chars that are accepted
398 * @param message Message to user
399 * @return Allowed character
402 public char enterChar (final char[] validChars, final String message) {
404 this.getLogger().trace(MessageFormat.format("validChars={0},message={1} - CALLED!", Arrays.toString(validChars), message)); //NOI18N
406 // The validChars must not null be null and filled with at least one char
407 if (validChars == null) {
409 throw new NullPointerException("validChars is null"); //NOI18N
410 } else if (validChars.length == 0) {
412 throw new IllegalArgumentException("validChars is not filled."); //NOI18N
417 // Sort array, else binarySearch() won't work
418 Arrays.sort(validChars);
420 // Keep asking until valid char has been entered
421 while (Arrays.binarySearch(validChars, input) < 0) {
423 System.out.print(message);
426 input = this.readChar();
430 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
437 * Asks the user to enter his/her gender
439 * @param message Message to the user
440 * @return Gender enum
443 public Gender enterGender (final String message) {
445 this.getLogger().trace(MessageFormat.format("message={0} - CALLED!", message)); //NOI18N
448 char[] validChars = Gender.validChars();
451 //* NOISY-DEBUG: */ System.out.println(validChars);
453 char gender = this.enterChar(validChars, message);
455 // Now get a Gender instance back
456 Gender g = Gender.fromChar(gender);
458 // g must not be null
459 assert(g instanceof Gender) : "g is not set."; //NOI18N
462 this.getLogger().trace(MessageFormat.format("g={0} - EXIT!", g)); //NOI18N
469 * Reads an integer (int) with a textural message from the user
471 * @param minimum Minimum allowed number
472 * @param maximum Maximum allowed number
473 * @param message Messager to display in console
477 public int enterInt (final int minimum, final int maximum, final String message) {
479 this.getLogger().trace(MessageFormat.format("minimum={0},maximum={1},message={2} - CALLED!", minimum, maximum, message)); //NOI18N
481 // Minimum should not be below zero
482 assert (minimum >= 0);
483 assert (maximum > minimum);
488 while ((input < minimum) || (input > maximum)) {
490 System.out.print(message);
492 // Read integer from user
493 input = this.readInt();
497 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
504 * Reads a string of minimum and maximum length from the user
506 * @param minLength Minimum length of the string to read
507 * @param maxLength Maximum length of the string to read
508 * @param message Message to user
509 * @param allowEmpty Whether to allow empty string
510 * @return Entered string by user or null for empty strings
513 public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
515 this.getLogger().trace(MessageFormat.format("minLength={0},maxLength={1},message={2}allowEmpty={3} - CALLED!", minLength, maxLength, message, allowEmpty)); //NOI18N
517 // Check on length, e.g. country codes are excactly 2 chars long
518 assert (maxLength >= minLength);
523 // Check if it is to short or to long
524 while (((input == null) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
526 System.out.print(message);
529 input = this.readString();
533 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
540 * Returns a console menu item
542 * @param accessKey Key to access the menu
543 * @param text Text to show to user
544 * @return A SelectableMenuItem
545 * @todo Make sure the access key is unique
548 public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
549 // Return a new console menu item
550 return new ConsoleMenuItem(accessKey, text);
554 * Initializes this client
557 public void init () {
559 this.getLogger().trace("CALLED!"); //NOI18N
561 // Init contact manager here
563 this.initContactManager();
564 } catch (final UnsupportedDatabaseBackendException | SQLException ex) {
566 this.abortProgramWithException(ex);
573 this.getLogger().trace("EXIT!"); //NOI18N
577 * Displays textural message to the user
582 public void outputMessage (final String message) {
583 System.out.println(message);
587 * Shows textural menu on console
590 public void showCurrentMenu () {
591 this.showMenu(this.getCurrentMenu());
595 * Shows given menu entry to user
597 * @param item Menu entry
600 public void showEntry (final SelectableMenuItem item) {
601 // Access key then text
602 this.outputMessage(MessageFormat.format("[{0}] {1}", item.getAccessKey(), item.getText()));
606 * Shows a textural message to the user
609 public void showWelcome () {
610 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle()));
611 this.outputMessage("");
612 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software");
615 this.getLogger().debug("Intro shown to user"); //NOI18N
619 public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
621 this.getLogger().trace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
623 // Contact must not be null
624 if (contact == null) {
626 throw new NullPointerException("contact is null"); //NOI18N
629 // Ask the user for editing [name], [a]ddress or [other] data
630 char choice = this.enterChar(new char[] {'n', 'a', 'o', 'x'}, "Welchen Daten möchten Sie ändern? (n=Namensdaten, a=Anschriftsdaten, o=Andere, x=Zurück zur Hauptauswahl) ");
632 // Get manager and cast it
633 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
635 // @TODO Get rid of this ugly switch block, too
637 case 'n': // Name data
638 manager.doChangeNameData(contact);
641 case 'a': // Address data
642 manager.doChangeAddressData(contact);
645 case 'o': // Other data
646 manager.doChangeOtherData(contact);
649 case 'x': // Exit this menu
650 // Ignored as it should go back
654 // @TODO throw own exception
655 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
659 this.getLogger().trace("EXIT!"); //NOI18N
663 * Reads one character
665 * @return A single character
667 private char readChar () {
669 String input = this.readString();
672 this.getLogger().debug(MessageFormat.format("input={0}", input)); //NOI18N
674 // This must be only one character
675 if (input.length() != 1) {
680 // Get char from first (and only) position
681 return input.charAt(0);
685 * Reads an integer (int) from user
687 * @return An integer number
689 private int readInt () {
690 // First read a string
691 String input = this.readString();
694 this.getLogger().debug(MessageFormat.format("input={0}", input)); //NOI18N
696 // Init number with invalid value
699 // Parse number, this can be risky
701 num = Integer.parseInt(input);
702 } catch (final NumberFormatException e) {
703 this.outputMessage("Bitte geben Sie nur Zahlen ein!");
704 this.getLogger().warn(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage())); //NOI18N
708 this.getLogger().trace(MessageFormat.format("num={0} - EXIT!", num)); //NOI18N
710 // Return read number
715 * Reads a string from a scanner until RETURN is pressed
717 * @return Read string from scanner
719 private String readString () {
720 return this.scanner.nextLine();
724 * Fills menu map with menu entries
727 protected final void fillMenuMap () {
729 this.getLogger().trace("CALLED!"); //NOI18N
731 // Initialize first (main) menu
732 Menu menu = new ConsoleMenu("main", this); //NOI18N
735 this.getMenus().put("main", menu); //NOI18N
738 this.getLogger().trace("EXIT!"); //NOI18N