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.lang.reflect.InvocationTargetException;
21 import java.sql.SQLException;
22 import java.text.MessageFormat;
23 import java.util.Arrays;
24 import java.util.Scanner;
25 import org.mxchange.addressbook.application.AddressbookApplication;
26 import org.mxchange.addressbook.client.AddressbookClient;
27 import org.mxchange.addressbook.client.BaseAddressbookClient;
28 import org.mxchange.addressbook.contact.user.UserContact;
29 import org.mxchange.addressbook.exceptions.ContactAlreadyAddedException;
30 import org.mxchange.addressbook.manager.contact.ManageableAddressbookContact;
31 import org.mxchange.addressbook.menu.Menu;
32 import org.mxchange.addressbook.menu.MenuTools;
33 import org.mxchange.addressbook.menu.console.ConsoleMenu;
34 import org.mxchange.addressbook.menu.item.SelectableMenuItem;
35 import org.mxchange.addressbook.menu.item.console.ConsoleMenuItem;
36 import org.mxchange.jcore.application.Application;
37 import org.mxchange.jcore.contact.Contact;
38 import org.mxchange.jcore.contact.gender.Gender;
39 import org.mxchange.jcore.exceptions.UnhandledUserChoiceException;
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 (null == contact) {
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 (null == contact) {
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 ((null == companyName) || (companyName.isEmpty())) {
119 // Now put all together: gender, surname, family name
121 this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getFirstName(), contact.getFamilyName()));
124 this.outputMessage(MessageFormat.format("Firma: {0}\nAnsprechpartner: {1} {2} {3}", companyName, gender, contact.getFirstName(), 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 (null == contact) {
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 (null == contact) {
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 (null == contact) {
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 firstName = manager.enterOwnFirstName();
223 String familyName = manager.enterOwnFamilyName();
226 String companyName = manager.enterOwnCompanyName();
228 // Update contact instance
229 contact.setGender(gender);
230 contact.setFirstName(firstName);
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 (null == contact) {
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.enterOwnFirstName();
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();
347 // TODO Rewrite this ugly switch() block
351 // Enter/add own data
352 manager.doEnterOwnData();
353 } catch (final ContactAlreadyAddedException ex) {
355 this.outputMessage("Sie haben bereits Ihre eigenen Daten eingegeben.");
359 case '2': // Change own data
360 manager.doChangeOwnData();
363 case '3': // Add new addess
364 manager.doAddOtherAddress();
367 case '4': // List contacts
368 manager.doListContacts();
371 case '5': // Search addresses
372 manager.doSearchContacts();
375 case '6': // Change other addess
376 manager.doChangeOtherAddress();
379 case '7': // Delete other address
380 manager.doDeleteOtherAddress();
386 this.getApplication().doShutdown();
387 } catch (final SQLException | IOException ex) {
388 this.abortProgramWithException(ex);
393 // TODO throw own exception
394 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
396 } catch (final IOException | SQLException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
397 // Something bad happened
398 this.abortProgramWithException(ex);
402 this.getLogger().trace("EXIT!"); //NOI18N
406 * Asks the the user to enter a single character which must match validChars
408 * @param validChars Valid chars that are accepted
409 * @param message Message to user
410 * @return Allowed character
413 public char enterChar (final char[] validChars, final String message) {
415 this.getLogger().trace(MessageFormat.format("validChars={0},message={1} - CALLED!", Arrays.toString(validChars), message)); //NOI18N
417 // The validChars must not null be null and filled with at least one char
418 if (null == validChars) {
420 throw new NullPointerException("validChars is null"); //NOI18N
421 } else if (validChars.length == 0) {
423 throw new IllegalArgumentException("validChars is not filled."); //NOI18N
428 // Sort array, else binarySearch() won't work
429 Arrays.sort(validChars);
431 // Keep asking until valid char has been entered
432 while (Arrays.binarySearch(validChars, input) < 0) {
434 System.out.print(message);
437 input = this.readChar();
441 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
448 * Asks the user to enter his/her gender
450 * @param message Message to the user
451 * @return Gender enum
454 public Gender enterGender (final String message) {
456 this.getLogger().trace(MessageFormat.format("message={0} - CALLED!", message)); //NOI18N
459 char[] validChars = Gender.validChars();
462 //* NOISY-DEBUG: */ System.out.println(validChars);
464 char gender = this.enterChar(validChars, message);
466 // Now get a Gender instance back
467 Gender g = Gender.fromChar(gender);
469 // g must not be null
470 assert(g instanceof Gender) : "g is not set."; //NOI18N
473 this.getLogger().trace(MessageFormat.format("g={0} - EXIT!", g)); //NOI18N
480 * Reads an integer (int) with a textural message from the user
482 * @param minimum Minimum allowed number
483 * @param maximum Maximum allowed number
484 * @param message Messager to display in console
488 public int enterInt (final int minimum, final int maximum, final String message) {
490 this.getLogger().trace(MessageFormat.format("minimum={0},maximum={1},message={2} - CALLED!", minimum, maximum, message)); //NOI18N
492 // Minimum should not be below zero
493 assert (minimum >= 0);
494 assert (maximum > minimum);
499 while ((input < minimum) || (input > maximum)) {
501 System.out.print(message);
503 // Read integer from user
504 input = this.readInt();
508 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
515 * Reads a string of minimum and maximum length from the user
517 * @param minLength Minimum length of the string to read
518 * @param maxLength Maximum length of the string to read
519 * @param message Message to user
520 * @param allowEmpty Whether to allow empty string
521 * @return Entered string by user or null for empty strings
524 public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
526 this.getLogger().trace(MessageFormat.format("minLength={0},maxLength={1},message={2}allowEmpty={3} - CALLED!", minLength, maxLength, message, allowEmpty)); //NOI18N
528 // Check on length, e.g. country codes are excactly 2 chars long
529 assert (maxLength >= minLength);
534 // Check if it is to short or to long
535 while (((null == input) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
537 System.out.print(message);
540 input = this.readString();
544 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
551 * Returns a console menu item
553 * @param accessKey Key to access the menu
554 * @param text Text to show to user
555 * @return A SelectableMenuItem
556 * TODO Make sure the access key is unique
559 public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
560 // Return a new console menu item
561 return new ConsoleMenuItem(accessKey, text);
565 * Initializes this client
568 public void init () {
570 this.getLogger().trace("CALLED!"); //NOI18N
572 // Init contact manager here
574 this.initContactManager();
575 } catch (final SQLException ex) {
577 this.abortProgramWithException(ex);
584 this.getLogger().trace("EXIT!"); //NOI18N
588 * Displays textural message to the user
593 public void outputMessage (final String message) {
594 System.out.println(message);
598 * Shows textural menu on console
601 public void showCurrentMenu () {
602 this.showMenu(this.getCurrentMenu());
606 * Shows given menu entry to user
608 * @param item Menu entry
611 public void showEntry (final SelectableMenuItem item) {
612 // Access key then text
613 this.outputMessage(MessageFormat.format("[{0}] {1}", item.getAccessKey(), item.getText()));
617 * Shows a textural message to the user
620 public void showWelcome () {
621 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle()));
622 this.outputMessage("");
623 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software");
626 this.getLogger().debug("Intro shown to user"); //NOI18N
630 public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
632 this.getLogger().trace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
634 // Contact must not be null
635 if (null == contact) {
637 throw new NullPointerException("contact is null"); //NOI18N
640 // Ask the user for editing [name], [a]ddress or [other] data
641 char choice = this.enterChar(new char[] {'n', 'a', 'o', 'x'}, "Welchen Daten möchten Sie ändern? (n=Namensdaten, a=Anschriftsdaten, o=Andere, x=Zurück zur Hauptauswahl) ");
643 // Get manager and cast it
644 ManageableAddressbookContact manager = (ManageableAddressbookContact) this.getManager();
646 // TODO Get rid of this ugly switch block, too
648 case 'n': // Name data
649 manager.doChangeNameData(contact);
652 case 'a': // Address data
653 manager.doChangeAddressData(contact);
656 case 'o': // Other data
657 manager.doChangeOtherData(contact);
660 case 'x': // Exit this menu
661 // Ignored as it should go back
665 // TODO throw own exception
666 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
670 this.getLogger().trace("EXIT!"); //NOI18N
674 * Reads one character
676 * @return A single character
678 private char readChar () {
680 String input = this.readString();
683 this.getLogger().debug(MessageFormat.format("input={0}", input)); //NOI18N
685 // This must be only one character
686 if (input.length() != 1) {
691 // Get char from first (and only) position
692 return input.charAt(0);
696 * Reads an integer (int) from user
698 * @return An integer number
700 private int readInt () {
701 // First read a string
702 String input = this.readString();
705 this.getLogger().debug(MessageFormat.format("input={0}", input)); //NOI18N
707 // Init number with invalid value
710 // Parse number, this can be risky
712 num = Integer.parseInt(input);
713 } catch (final NumberFormatException e) {
714 this.outputMessage("Bitte geben Sie nur Zahlen ein!");
715 this.getLogger().warn(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage())); //NOI18N
719 this.getLogger().trace(MessageFormat.format("num={0} - EXIT!", num)); //NOI18N
721 // Return read number
726 * Reads a string from a scanner until RETURN is pressed
728 * @return Read string from scanner
730 private String readString () {
731 return this.scanner.nextLine();
735 * Fills menu map with menu entries
738 protected final void fillMenuMap () {
740 this.getLogger().trace("CALLED!"); //NOI18N
742 // Initialize first (main) menu
743 Menu menu = new ConsoleMenu("main", this); //NOI18N
746 this.getMenus().put("main", menu); //NOI18N
749 this.getLogger().trace("EXIT!"); //NOI18N