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.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;
47 * A client for the console
49 * @author Roland Haeder
51 public class ConsoleClient extends BaseAddressbookClient implements AddressbookClient {
54 * Scanner instance for reading data from console input
56 private final Scanner scanner;
59 * Parameterless constructor
61 * @param application An instance of an Application class
63 public ConsoleClient (final Application application) {
65 this.getLogger().logTrace(MessageFormat.format("application={0} - CALLED!", application)); //NOI18N
67 // Set application instance
68 this.setApplication(application);
70 // Init scanner instance
71 this.scanner = new Scanner(System.in, "UTF-8"); //NOI18N
74 this.getLogger().logTrace("EXIT!"); //NOI18N
78 public void displayAddressBox (final Contact contact) {
80 this.getLogger().logTrace(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.getCountry()));
92 this.getLogger().logTrace("EXIT!"); //NOI18N
96 public void displayNameBox (final Contact contact) {
98 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
101 if (null == contact) {
103 throw new NullPointerException("contact is null"); //NOI18N
106 // Get translated gender as the user may want to see "Mr.", "Mrs."
107 String gender = GenderUtils.getTranslatedGender(contact);
109 // Now put all together: gender, surname, family name
110 this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getFirstName(), contact.getFamilyName()));
113 this.getLogger().logTrace("EXIT!"); //NOI18N
117 public void displayOtherDataBox (final Contact contact) {
119 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
122 if (null == contact) {
124 throw new NullPointerException("contact is null"); //NOI18N
127 // Cellphone and such ...
128 this.outputMessage(MessageFormat.format("Telefonnumer: {0}\nFaxnummer: {1}\nHandy: {2}\nKommentar:\n{3}", contact.getPhoneNumber(), contact.getFaxNumber(), contact.getCellphoneNumber(), contact.getComment()));
131 this.getLogger().logTrace("EXIT!"); //NOI18N
135 public void doChangeOwnAddressData (final Contact contact) {
137 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
140 if (null == contact) {
142 throw new NullPointerException("contact is null"); //NOI18N
145 // Make sure it is own contact
146 if (!contact.isOwnContact()) {
148 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
151 // Get manager and cast it
152 ContactFacade manager = (ContactFacade) this.getFacade();
154 // Own street and number
155 String streetNumber = manager.enterOwnStreet();
158 Integer zipCode = manager.enterOwnZipCode();
161 String city = manager.enterOwnCity();
164 Country country = manager.enterOwnCountryCode();
166 // Update address data
167 contact.setStreet(streetNumber);
168 contact.setZipCode(zipCode);
169 contact.setCity(city);
170 contact.setCountry(country);
173 this.getLogger().logTrace("EXIT!"); //NOI18N
177 public void doChangeOwnNameData (final Contact contact) {
179 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
182 if (null == contact) {
184 throw new NullPointerException("contact is null"); //NOI18N
187 // Make sure it is own contact
188 if (!contact.isOwnContact()) {
190 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
193 // Get manager and cast it
194 ContactFacade manager = (ContactFacade) this.getFacade();
197 Gender gender = manager.enterOwnGender();
200 String firstName = manager.enterOwnFirstName();
203 String familyName = manager.enterOwnFamilyName();
205 // Update contact instance
206 contact.setGender(gender);
207 contact.setFirstName(firstName);
208 contact.setFamilyName(familyName);
211 this.getLogger().logTrace("EXIT!"); //NOI18N
215 public void doChangeOwnOtherData (final Contact contact) {
217 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
220 if (null == contact) {
222 throw new NullPointerException("contact is null"); //NOI18N
225 // Make sure it is own contact
226 if (!contact.isOwnContact()) {
228 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
231 // Get manager and cast it
232 ContactFacade manager = (ContactFacade) this.getFacade();
235 DialableLandLineNumber phoneNumber = manager.enterOwnPhoneNumber();
238 DialableCellphoneNumber cellphonePhoneNumber = manager.enterOwnCellNumber();
241 DialableFaxNumber faxNumber = manager.enterOwnFaxNumber();
244 String email = manager.enterOwnEmailAddress();
247 String comment = manager.enterOwnComment();
249 // Update contact instance
250 contact.setPhoneNumber(phoneNumber);
251 contact.setCellphoneNumber(cellphonePhoneNumber);
252 contact.setFaxNumber(faxNumber);
253 contact.setEmailAddress(email);
254 contact.setComment(comment);
257 this.getLogger().logTrace("EXIT!"); //NOI18N
261 public Contact doEnterOwnData () {
263 this.getLogger().logTrace("CALLED!"); //NOI18N
265 // Get manager and cast it
266 ContactFacade manager = (ContactFacade) this.getFacade();
268 // First ask for gender
269 Gender gender = manager.enterOwnGender();
271 // 2nd for first name
272 String firstName = manager.enterOwnFirstName();
274 // And 3rd for family name
275 String familyName = manager.enterOwnFamilyName();
277 // Construct UserContact instance
278 Contact contact = new UserContact(gender, firstName, familyName);
281 this.getLogger().logTrace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
288 public void doShutdown () throws SQLException, IOException {
290 this.getLogger().logTrace("CALLED!"); //NOI18N
295 // TODO Add other shutdown stuff
297 this.getLogger().logTrace("EXIT!"); //NOI18N
301 public void doUserMenuChoice () throws UnhandledUserChoiceException, MenuInitializationException {
303 this.getLogger().logTrace("CALLED!"); //NOI18N
305 // Get all access keys from menu
306 char[] accessKeys = MenuTools.getAccessKeysFromMenuMap(this.getMenus(), this.getCurrentMenu());
308 // Output textural message and ask for a char as input
309 char choice = this.enterChar(accessKeys, "Bitte Auswahl eingeben (0=Programm beenden): ");
311 // Get manager and cast it
312 ContactFacade manager = (ContactFacade) this.getFacade();
314 // TODO Rewrite this ugly switch() block
318 // Enter/add own data
319 manager.doEnterOwnData();
320 } catch (final ContactAlreadyAddedException ex) {
322 this.outputMessage("Sie haben bereits Ihre eigenen Daten eingegeben.");
326 case '2': // Change own data
327 manager.doChangeOwnData();
330 case '3': // Add new addess
331 manager.doAddOtherAddress();
334 case '4': // List contacts
335 manager.doListContacts();
338 case '5': // Search addresses
339 manager.doSearchContacts();
342 case '6': // Change other addess
343 manager.doChangeOtherAddress();
346 case '7': // Delete other address
347 manager.doDeleteOtherAddress();
353 this.getApplication().doShutdown();
354 } catch (final SQLException | IOException ex) {
355 this.abortProgramWithException(ex);
360 // TODO throw own exception
361 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
365 this.getLogger().logTrace("EXIT!"); //NOI18N
369 public char enterChar (final char[] validChars, final String message) {
371 this.getLogger().logTrace(MessageFormat.format("validChars={0},message={1} - CALLED!", Arrays.toString(validChars), message)); //NOI18N
373 // The validChars must not null be null and filled with at least one char
374 if (null == validChars) {
376 throw new NullPointerException("validChars is null"); //NOI18N
377 } else if (validChars.length == 0) {
379 throw new IllegalArgumentException("validChars is not filled."); //NOI18N
384 // Sort array, else binarySearch() won't work
385 Arrays.sort(validChars);
387 // Keep asking until valid char has been entered
388 while (Arrays.binarySearch(validChars, input) < 0) {
390 System.out.print(message);
393 input = this.readChar();
397 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
404 public Gender enterGender (final String message) {
406 this.getLogger().logTrace(MessageFormat.format("message={0} - CALLED!", message)); //NOI18N
409 char[] validChars = Gender.validChars();
412 //* NOISY-DEBUG: */ System.out.println(validChars);
414 char gender = this.enterChar(validChars, message);
416 // Now get a Gender instance back
417 Gender g = Gender.fromChar(gender);
419 // g must not be null
420 assert (g instanceof Gender) : "g is not set."; //NOI18N
423 this.getLogger().logTrace(MessageFormat.format("g={0} - EXIT!", g)); //NOI18N
430 public int enterInt (final int minimum, final int maximum, final String message) {
432 this.getLogger().logTrace(MessageFormat.format("minimum={0},maximum={1},message={2} - CALLED!", minimum, maximum, message)); //NOI18N
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
441 while ((input < minimum) || (input > maximum)) {
443 System.out.print(message);
445 // Read integer from user
446 input = this.readInt();
450 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
457 public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
459 this.getLogger().logTrace(MessageFormat.format("minLength={0},maxLength={1},message={2}allowEmpty={3} - CALLED!", minLength, maxLength, message, allowEmpty)); //NOI18N
461 // Check on length, e.g. country codes are excactly 2 chars long
462 assert (maxLength >= minLength);
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))) {
470 System.out.print(message);
473 input = this.readString();
477 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
484 public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
485 // Return a new console menu item
486 return new ConsoleMenuItem(accessKey, text);
490 public void init () {
492 this.getLogger().logTrace("CALLED!"); //NOI18N
494 // Init contact manager here
496 this.initContactManager();
497 } catch (final SQLException ex) {
499 this.abortProgramWithException(ex);
506 this.getLogger().logTrace("EXIT!"); //NOI18N
510 public void outputMessage (final String message) {
511 System.out.println(message);
515 public void show (final Contact contact) {
516 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
520 public void showCurrentMenu () {
521 this.showMenu(this.getCurrentMenu());
525 public void showEntry (final SelectableMenuItem item) {
526 // Access key then text
527 this.outputMessage(MessageFormat.format("[{0}] {1}", item.getAccessKey(), item.getText())); //NOI18N
531 public void showWelcome () {
532 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle())); //NOI18N
533 this.outputMessage(""); //NOI18N
534 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software"); //NOI18N
537 this.getLogger().logDebug("Intro shown to user"); //NOI18N
541 public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
543 this.getLogger().logTrace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
545 // Contact must not be null
546 if (null == contact) {
548 throw new NullPointerException("contact is null"); //NOI18N
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) ");
554 // Get manager and cast it
555 ContactFacade manager = (ContactFacade) this.getFacade();
557 // TODO Get rid of this ugly switch block, too
559 case 'n': // Name data
560 manager.doChangeNameData(contact);
563 case 'a': // Address data
564 manager.doChangeAddressData(contact);
567 case 'o': // Other data
568 manager.doChangeOtherData(contact);
571 case 'x': // Exit this menu
572 // Ignored as it should go back
576 // TODO throw own exception
577 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
581 this.getLogger().logTrace("EXIT!"); //NOI18N
585 * Reads one character
587 * @return A single character
589 private char readChar () {
591 String input = this.readString();
594 this.getLogger().logDebug(MessageFormat.format("input={0}", input)); //NOI18N
596 // This must be only one character
597 if (input.length() != 1) {
602 // Get char from first (and only) position
603 return input.charAt(0);
607 * Reads an integer (int) from user
609 * @return An integer number
611 private int readInt () {
612 // First read a string
613 String input = this.readString();
616 this.getLogger().logDebug(MessageFormat.format("input={0}", input)); //NOI18N
618 // Init number with invalid value
621 // Parse number, this can be risky
623 num = Integer.parseInt(input);
624 } catch (final NumberFormatException e) {
625 this.outputMessage("Bitte geben Sie nur Zahlen ein!");
626 this.getLogger().logWarning(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage())); //NOI18N
630 this.getLogger().logTrace(MessageFormat.format("num={0} - EXIT!", num)); //NOI18N
632 // Return read number
637 * Reads a string from a scanner until RETURN is pressed
639 * @return Read string from scanner
641 private String readString () {
642 return this.scanner.nextLine();
646 protected final void fillMenuMap () {
648 this.getLogger().logTrace("CALLED!"); //NOI18N
650 // Initialize first (main) menu
651 Menu menu = new ConsoleMenu("main", this); //NOI18N
654 this.getMenus().put("main", menu); //NOI18N
657 this.getLogger().logTrace("EXIT!"); //NOI18N