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;
43 * A client for the console
45 * @author Roland Haeder
47 public class ConsoleClient extends BaseAddressbookClient implements AddressbookClient {
50 * Scanner instance for reading data from console input
52 private final Scanner scanner;
55 * Parameterless constructor
57 * @param application An instance of an Application class
59 public ConsoleClient (final Application application) {
61 this.getLogger().logTrace(MessageFormat.format("application={0} - CALLED!", application)); //NOI18N
63 // Set application instance
64 this.setApplication(application);
66 // Init scanner instance
67 this.scanner = new Scanner(System.in, "UTF-8"); //NOI18N
70 this.getLogger().logTrace("EXIT!"); //NOI18N
74 public void displayAddressBox (final Contact contact) {
76 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
79 if (null == contact) {
81 throw new NullPointerException("contact is null"); //NOI18N
85 this.outputMessage(MessageFormat.format("Strasse, PLZ Ort, Land: {0}\n{1} {2}\n{3}", contact.getStreet(), contact.getZipCode(), contact.getCity(), contact.getCountryCode()));
88 this.getLogger().logTrace("EXIT!"); //NOI18N
92 public void displayNameBox (final Contact contact) {
94 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
97 if (null == contact) {
99 throw new NullPointerException("contact is null"); //NOI18N
102 // Get translated gender as the user may want to see "Mr.", "Mrs."
103 String gender = GenderUtils.getTranslatedGender(contact);
105 // Now put all together: gender, surname, family name
106 this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getFirstName(), contact.getFamilyName()));
109 this.getLogger().logTrace("EXIT!"); //NOI18N
113 public void displayOtherDataBox (final Contact contact) {
115 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
118 if (null == contact) {
120 throw new NullPointerException("contact is null"); //NOI18N
123 // Cellphone and such ...
124 this.outputMessage(MessageFormat.format("Telefonnumer: {0}\nFaxnummer: {1}\nHandy: {2}\nKommentar:\n{3}", contact.getPhoneNumber(), contact.getFaxNumber(), contact.getCellphoneNumber(), contact.getComment()));
127 this.getLogger().logTrace("EXIT!"); //NOI18N
131 public void doChangeOwnAddressData (final Contact contact) {
133 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
136 if (null == contact) {
138 throw new NullPointerException("contact is null"); //NOI18N
141 // Make sure it is own contact
142 if (!contact.isOwnContact()) {
144 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
147 // Get manager and cast it
148 ContactFacade manager = (ContactFacade) this.getFacade();
150 // Own street and number
151 String streetNumber = manager.enterOwnStreet();
154 Integer zipCode = manager.enterOwnZipCode();
157 String city = manager.enterOwnCity();
160 String countryCode = manager.enterOwnCountryCode();
162 // Update address data
163 contact.setStreet(streetNumber);
164 contact.setZipCode(zipCode);
165 contact.setCity(city);
166 contact.setCountryCode(countryCode);
169 this.getLogger().logTrace("EXIT!"); //NOI18N
173 public void doChangeOwnNameData (final Contact contact) {
175 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
178 if (null == contact) {
180 throw new NullPointerException("contact is null"); //NOI18N
183 // Make sure it is own contact
184 if (!contact.isOwnContact()) {
186 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
189 // Get manager and cast it
190 ContactFacade manager = (ContactFacade) this.getFacade();
193 Gender gender = manager.enterOwnGender();
196 String firstName = manager.enterOwnFirstName();
199 String familyName = manager.enterOwnFamilyName();
201 // Update contact instance
202 contact.setGender(gender);
203 contact.setFirstName(firstName);
204 contact.setFamilyName(familyName);
207 this.getLogger().logTrace("EXIT!"); //NOI18N
211 public void doChangeOwnOtherData (final Contact contact) {
213 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
216 if (null == contact) {
218 throw new NullPointerException("contact is null"); //NOI18N
221 // Make sure it is own contact
222 if (!contact.isOwnContact()) {
224 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
227 // Get manager and cast it
228 ContactFacade manager = (ContactFacade) this.getFacade();
231 String phoneNumber = manager.enterOwnPhoneNumber();
234 String cellphonePhoneNumber = manager.enterOwnCellNumber();
237 String faxNumber = manager.enterOwnFaxNumber();
240 String email = manager.enterOwnEmailAddress();
243 String comment = manager.enterOwnComment();
245 // Update contact instance
246 contact.setPhoneNumber(phoneNumber);
247 contact.setCellphoneNumber(cellphonePhoneNumber);
248 contact.setFaxNumber(faxNumber);
249 contact.setEmailAddress(email);
250 contact.setComment(comment);
253 this.getLogger().logTrace("EXIT!"); //NOI18N
257 public Contact doEnterOwnData () {
259 this.getLogger().logTrace("CALLED!"); //NOI18N
261 // Get manager and cast it
262 ContactFacade manager = (ContactFacade) this.getFacade();
264 // First ask for gender
265 Gender gender = manager.enterOwnGender();
267 // 2nd for first name
268 String firstName = manager.enterOwnFirstName();
270 // And 3rd for family name
271 String familyName = manager.enterOwnFamilyName();
273 // Construct UserContact instance
274 Contact contact = new UserContact(gender, firstName, familyName);
277 this.getLogger().logTrace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
284 public void doShutdown () throws SQLException, IOException {
286 this.getLogger().logTrace("CALLED!"); //NOI18N
291 // TODO Add other shutdown stuff
293 this.getLogger().logTrace("EXIT!"); //NOI18N
297 public void doUserMenuChoice () throws UnhandledUserChoiceException, MenuInitializationException {
299 this.getLogger().logTrace("CALLED!"); //NOI18N
301 // Get all access keys from menu
302 char[] accessKeys = MenuTools.getAccessKeysFromMenuMap(this.getMenus(), this.getCurrentMenu());
304 // Output textural message and ask for a char as input
305 char choice = this.enterChar(accessKeys, "Bitte Auswahl eingeben (0=Programm beenden): ");
307 // Get manager and cast it
308 ContactFacade manager = (ContactFacade) this.getFacade();
310 // TODO Rewrite this ugly switch() block
314 // Enter/add own data
315 manager.doEnterOwnData();
316 } catch (final ContactAlreadyAddedException ex) {
318 this.outputMessage("Sie haben bereits Ihre eigenen Daten eingegeben.");
322 case '2': // Change own data
323 manager.doChangeOwnData();
326 case '3': // Add new addess
327 manager.doAddOtherAddress();
330 case '4': // List contacts
331 manager.doListContacts();
334 case '5': // Search addresses
335 manager.doSearchContacts();
338 case '6': // Change other addess
339 manager.doChangeOtherAddress();
342 case '7': // Delete other address
343 manager.doDeleteOtherAddress();
349 this.getApplication().doShutdown();
350 } catch (final SQLException | IOException ex) {
351 this.abortProgramWithException(ex);
356 // TODO throw own exception
357 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
361 this.getLogger().logTrace("EXIT!"); //NOI18N
365 public char enterChar (final char[] validChars, final String message) {
367 this.getLogger().logTrace(MessageFormat.format("validChars={0},message={1} - CALLED!", Arrays.toString(validChars), message)); //NOI18N
369 // The validChars must not null be null and filled with at least one char
370 if (null == validChars) {
372 throw new NullPointerException("validChars is null"); //NOI18N
373 } else if (validChars.length == 0) {
375 throw new IllegalArgumentException("validChars is not filled."); //NOI18N
380 // Sort array, else binarySearch() won't work
381 Arrays.sort(validChars);
383 // Keep asking until valid char has been entered
384 while (Arrays.binarySearch(validChars, input) < 0) {
386 System.out.print(message);
389 input = this.readChar();
393 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
400 public Gender enterGender (final String message) {
402 this.getLogger().logTrace(MessageFormat.format("message={0} - CALLED!", message)); //NOI18N
405 char[] validChars = Gender.validChars();
408 //* NOISY-DEBUG: */ System.out.println(validChars);
410 char gender = this.enterChar(validChars, message);
412 // Now get a Gender instance back
413 Gender g = Gender.fromChar(gender);
415 // g must not be null
416 assert (g instanceof Gender) : "g is not set."; //NOI18N
419 this.getLogger().logTrace(MessageFormat.format("g={0} - EXIT!", g)); //NOI18N
426 public int enterInt (final int minimum, final int maximum, final String message) {
428 this.getLogger().logTrace(MessageFormat.format("minimum={0},maximum={1},message={2} - CALLED!", minimum, maximum, message)); //NOI18N
430 // Minimum should not be below zero
431 assert (minimum >= 0) : MessageFormat.format("minimum={0} is below zero", minimum); //NOI18N
432 assert (maximum > minimum) : MessageFormat.format("maximum {0} is smaller than minimum {1}", maximum, minimum); //NOI18N
437 while ((input < minimum) || (input > maximum)) {
439 System.out.print(message);
441 // Read integer from user
442 input = this.readInt();
446 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
453 public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
455 this.getLogger().logTrace(MessageFormat.format("minLength={0},maxLength={1},message={2}allowEmpty={3} - CALLED!", minLength, maxLength, message, allowEmpty)); //NOI18N
457 // Check on length, e.g. country codes are excactly 2 chars long
458 assert (maxLength >= minLength);
463 // Check if it is to short or to long
464 while (((null == input) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
466 System.out.print(message);
469 input = this.readString();
473 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
480 public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
481 // Return a new console menu item
482 return new ConsoleMenuItem(accessKey, text);
486 public void init () {
488 this.getLogger().logTrace("CALLED!"); //NOI18N
490 // Init contact manager here
492 this.initContactManager();
493 } catch (final SQLException ex) {
495 this.abortProgramWithException(ex);
502 this.getLogger().logTrace("EXIT!"); //NOI18N
506 public void outputMessage (final String message) {
507 System.out.println(message);
511 public void show (final Contact contact) {
512 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
516 public void showCurrentMenu () {
517 this.showMenu(this.getCurrentMenu());
521 public void showEntry (final SelectableMenuItem item) {
522 // Access key then text
523 this.outputMessage(MessageFormat.format("[{0}] {1}", item.getAccessKey(), item.getText())); //NOI18N
527 public void showWelcome () {
528 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle())); //NOI18N
529 this.outputMessage(""); //NOI18N
530 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software"); //NOI18N
533 this.getLogger().logDebug("Intro shown to user"); //NOI18N
537 public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
539 this.getLogger().logTrace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
541 // Contact must not be null
542 if (null == contact) {
544 throw new NullPointerException("contact is null"); //NOI18N
547 // Ask the user for editing [name], [a]ddress or [other] data
548 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) ");
550 // Get manager and cast it
551 ContactFacade manager = (ContactFacade) this.getFacade();
553 // TODO Get rid of this ugly switch block, too
555 case 'n': // Name data
556 manager.doChangeNameData(contact);
559 case 'a': // Address data
560 manager.doChangeAddressData(contact);
563 case 'o': // Other data
564 manager.doChangeOtherData(contact);
567 case 'x': // Exit this menu
568 // Ignored as it should go back
572 // TODO throw own exception
573 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
577 this.getLogger().logTrace("EXIT!"); //NOI18N
581 * Reads one character
583 * @return A single character
585 private char readChar () {
587 String input = this.readString();
590 this.getLogger().logDebug(MessageFormat.format("input={0}", input)); //NOI18N
592 // This must be only one character
593 if (input.length() != 1) {
598 // Get char from first (and only) position
599 return input.charAt(0);
603 * Reads an integer (int) from user
605 * @return An integer number
607 private int readInt () {
608 // First read a string
609 String input = this.readString();
612 this.getLogger().logDebug(MessageFormat.format("input={0}", input)); //NOI18N
614 // Init number with invalid value
617 // Parse number, this can be risky
619 num = Integer.parseInt(input);
620 } catch (final NumberFormatException e) {
621 this.outputMessage("Bitte geben Sie nur Zahlen ein!");
622 this.getLogger().logWarning(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage())); //NOI18N
626 this.getLogger().logTrace(MessageFormat.format("num={0} - EXIT!", num)); //NOI18N
628 // Return read number
633 * Reads a string from a scanner until RETURN is pressed
635 * @return Read string from scanner
637 private String readString () {
638 return this.scanner.nextLine();
642 protected final void fillMenuMap () {
644 this.getLogger().logTrace("CALLED!"); //NOI18N
646 // Initialize first (main) menu
647 Menu menu = new ConsoleMenu("main", this); //NOI18N
650 this.getMenus().put("main", menu); //NOI18N
653 this.getLogger().logTrace("EXIT!"); //NOI18N