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);
106 String companyName = contact.getCompanyName();
108 // If it is empty/null, then assume private contact
109 if ((null == companyName) || (companyName.isEmpty())) {
110 // Now put all together: gender, surname, family name
112 this.outputMessage(MessageFormat.format("Anrede, Vorname, Name: {0} {1} {2}", gender, contact.getFirstName(), contact.getFamilyName()));
115 this.outputMessage(MessageFormat.format("Firma: {0}\nAnsprechpartner: {1} {2} {3}", companyName, gender, contact.getFirstName(), contact.getFamilyName()));
119 this.getLogger().logTrace("EXIT!"); //NOI18N
123 public void displayOtherDataBox (final Contact contact) {
125 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
128 if (null == contact) {
130 throw new NullPointerException("contact is null"); //NOI18N
133 // Cellphone and such ...
134 this.outputMessage(MessageFormat.format("Telefonnumer: {0}\nFaxnummer: {1}\nHandy: {2}\nKommentar:\n{3}", contact.getPhoneNumber(), contact.getFaxNumber(), contact.getCellphoneNumber(), contact.getComment()));
137 this.getLogger().logTrace("EXIT!"); //NOI18N
141 public void doChangeOwnAddressData (final Contact contact) {
143 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
146 if (null == contact) {
148 throw new NullPointerException("contact is null"); //NOI18N
151 // Make sure it is own contact
152 if (!contact.isOwnContact()) {
154 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
157 // Get manager and cast it
158 ContactFacade manager = (ContactFacade) this.getFacade();
160 // Own street and number
161 String streetNumber = manager.enterOwnStreet();
164 Integer zipCode = manager.enterOwnZipCode();
167 String city = manager.enterOwnCity();
170 String countryCode = manager.enterOwnCountryCode();
172 // Update address data
173 contact.setStreet(streetNumber);
174 contact.setZipCode(zipCode);
175 contact.setCity(city);
176 contact.setCountryCode(countryCode);
179 this.getLogger().logTrace("EXIT!"); //NOI18N
183 public void doChangeOwnNameData (final Contact contact) {
185 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
188 if (null == contact) {
190 throw new NullPointerException("contact is null"); //NOI18N
193 // Make sure it is own contact
194 if (!contact.isOwnContact()) {
196 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
199 // Get manager and cast it
200 ContactFacade manager = (ContactFacade) this.getFacade();
203 Gender gender = manager.enterOwnGender();
206 String firstName = manager.enterOwnFirstName();
209 String familyName = manager.enterOwnFamilyName();
212 String companyName = manager.enterOwnCompanyName();
214 // Update contact instance
215 contact.setGender(gender);
216 contact.setFirstName(firstName);
217 contact.setFamilyName(familyName);
218 contact.setCompanyName(companyName);
221 this.getLogger().logTrace("EXIT!"); //NOI18N
225 public void doChangeOwnOtherData (final Contact contact) {
227 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
230 if (null == contact) {
232 throw new NullPointerException("contact is null"); //NOI18N
235 // Make sure it is own contact
236 if (!contact.isOwnContact()) {
238 throw new IllegalArgumentException("Contact is not own data."); //NOI18N
241 // Get manager and cast it
242 ContactFacade manager = (ContactFacade) this.getFacade();
245 String phoneNumber = manager.enterOwnPhoneNumber();
248 String cellphonePhoneNumber = manager.enterOwnCellNumber();
251 String faxNumber = manager.enterOwnFaxNumber();
254 String email = manager.enterOwnEmailAddress();
257 String comment = manager.enterOwnComment();
259 // Update contact instance
260 contact.setPhoneNumber(phoneNumber);
261 contact.setCellphoneNumber(cellphonePhoneNumber);
262 contact.setFaxNumber(faxNumber);
263 contact.setEmailAddress(email);
264 contact.setComment(comment);
267 this.getLogger().logTrace("EXIT!"); //NOI18N
271 public Contact doEnterOwnData () {
273 this.getLogger().logTrace("CALLED!"); //NOI18N
275 // Get manager and cast it
276 ContactFacade manager = (ContactFacade) this.getFacade();
278 // First ask for gender
279 Gender gender = manager.enterOwnGender();
281 // 2nd for first name
282 String firstName = manager.enterOwnFirstName();
284 // And 3rd for family name
285 String familyName = manager.enterOwnFamilyName();
288 String companyName = manager.enterOwnCompanyName();
290 // Construct UserContact instance
291 Contact contact = new UserContact(gender, firstName, familyName, companyName);
294 this.getLogger().logTrace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
301 public void doShutdown () throws SQLException, IOException {
303 this.getLogger().logTrace("CALLED!"); //NOI18N
308 // TODO Add other shutdown stuff
310 this.getLogger().logTrace("EXIT!"); //NOI18N
314 public void doUserMenuChoice () throws UnhandledUserChoiceException, MenuInitializationException {
316 this.getLogger().logTrace("CALLED!"); //NOI18N
318 // Get all access keys from menu
319 char[] accessKeys = MenuTools.getAccessKeysFromMenuMap(this.getMenus(), this.getCurrentMenu());
321 // Output textural message and ask for a char as input
322 char choice = this.enterChar(accessKeys, "Bitte Auswahl eingeben (0=Programm beenden): ");
324 // Get manager and cast it
325 ContactFacade manager = (ContactFacade) this.getFacade();
327 // TODO Rewrite this ugly switch() block
331 // Enter/add own data
332 manager.doEnterOwnData();
333 } catch (final ContactAlreadyAddedException ex) {
335 this.outputMessage("Sie haben bereits Ihre eigenen Daten eingegeben.");
339 case '2': // Change own data
340 manager.doChangeOwnData();
343 case '3': // Add new addess
344 manager.doAddOtherAddress();
347 case '4': // List contacts
348 manager.doListContacts();
351 case '5': // Search addresses
352 manager.doSearchContacts();
355 case '6': // Change other addess
356 manager.doChangeOtherAddress();
359 case '7': // Delete other address
360 manager.doDeleteOtherAddress();
366 this.getApplication().doShutdown();
367 } catch (final SQLException | IOException ex) {
368 this.abortProgramWithException(ex);
373 // TODO throw own exception
374 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
378 this.getLogger().logTrace("EXIT!"); //NOI18N
382 public char enterChar (final char[] validChars, final String message) {
384 this.getLogger().logTrace(MessageFormat.format("validChars={0},message={1} - CALLED!", Arrays.toString(validChars), message)); //NOI18N
386 // The validChars must not null be null and filled with at least one char
387 if (null == validChars) {
389 throw new NullPointerException("validChars is null"); //NOI18N
390 } else if (validChars.length == 0) {
392 throw new IllegalArgumentException("validChars is not filled."); //NOI18N
397 // Sort array, else binarySearch() won't work
398 Arrays.sort(validChars);
400 // Keep asking until valid char has been entered
401 while (Arrays.binarySearch(validChars, input) < 0) {
403 System.out.print(message);
406 input = this.readChar();
410 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
417 public Gender enterGender (final String message) {
419 this.getLogger().logTrace(MessageFormat.format("message={0} - CALLED!", message)); //NOI18N
422 char[] validChars = Gender.validChars();
425 //* NOISY-DEBUG: */ System.out.println(validChars);
427 char gender = this.enterChar(validChars, message);
429 // Now get a Gender instance back
430 Gender g = Gender.fromChar(gender);
432 // g must not be null
433 assert (g instanceof Gender) : "g is not set."; //NOI18N
436 this.getLogger().logTrace(MessageFormat.format("g={0} - EXIT!", g)); //NOI18N
443 public int enterInt (final int minimum, final int maximum, final String message) {
445 this.getLogger().logTrace(MessageFormat.format("minimum={0},maximum={1},message={2} - CALLED!", minimum, maximum, message)); //NOI18N
447 // Minimum should not be below zero
448 assert (minimum >= 0) : MessageFormat.format("minimum={0} is below zero", minimum); //NOI18N
449 assert (maximum > minimum) : MessageFormat.format("maximum {0} is smaller than minimum {1}", maximum, minimum); //NOI18N
454 while ((input < minimum) || (input > maximum)) {
456 System.out.print(message);
458 // Read integer from user
459 input = this.readInt();
463 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
470 public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
472 this.getLogger().logTrace(MessageFormat.format("minLength={0},maxLength={1},message={2}allowEmpty={3} - CALLED!", minLength, maxLength, message, allowEmpty)); //NOI18N
474 // Check on length, e.g. country codes are excactly 2 chars long
475 assert (maxLength >= minLength);
480 // Check if it is to short or to long
481 while (((null == input) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
483 System.out.print(message);
486 input = this.readString();
490 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
497 public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
498 // Return a new console menu item
499 return new ConsoleMenuItem(accessKey, text);
503 public void init () {
505 this.getLogger().logTrace("CALLED!"); //NOI18N
507 // Init contact manager here
509 this.initContactManager();
510 } catch (final SQLException ex) {
512 this.abortProgramWithException(ex);
519 this.getLogger().logTrace("EXIT!"); //NOI18N
523 public void outputMessage (final String message) {
524 System.out.println(message);
528 public void show (final Contact contact) {
529 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
533 public void showCurrentMenu () {
534 this.showMenu(this.getCurrentMenu());
538 public void showEntry (final SelectableMenuItem item) {
539 // Access key then text
540 this.outputMessage(MessageFormat.format("[{0}] {1}", item.getAccessKey(), item.getText())); //NOI18N
544 public void showWelcome () {
545 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle())); //NOI18N
546 this.outputMessage(""); //NOI18N
547 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software"); //NOI18N
550 this.getLogger().logDebug("Intro shown to user"); //NOI18N
554 public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
556 this.getLogger().logTrace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
558 // Contact must not be null
559 if (null == contact) {
561 throw new NullPointerException("contact is null"); //NOI18N
564 // Ask the user for editing [name], [a]ddress or [other] data
565 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) ");
567 // Get manager and cast it
568 ContactFacade manager = (ContactFacade) this.getFacade();
570 // TODO Get rid of this ugly switch block, too
572 case 'n': // Name data
573 manager.doChangeNameData(contact);
576 case 'a': // Address data
577 manager.doChangeAddressData(contact);
580 case 'o': // Other data
581 manager.doChangeOtherData(contact);
584 case 'x': // Exit this menu
585 // Ignored as it should go back
589 // TODO throw own exception
590 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
594 this.getLogger().logTrace("EXIT!"); //NOI18N
598 * Reads one character
600 * @return A single character
602 private char readChar () {
604 String input = this.readString();
607 this.getLogger().logDebug(MessageFormat.format("input={0}", input)); //NOI18N
609 // This must be only one character
610 if (input.length() != 1) {
615 // Get char from first (and only) position
616 return input.charAt(0);
620 * Reads an integer (int) from user
622 * @return An integer number
624 private int readInt () {
625 // First read a string
626 String input = this.readString();
629 this.getLogger().logDebug(MessageFormat.format("input={0}", input)); //NOI18N
631 // Init number with invalid value
634 // Parse number, this can be risky
636 num = Integer.parseInt(input);
637 } catch (final NumberFormatException e) {
638 this.outputMessage("Bitte geben Sie nur Zahlen ein!");
639 this.getLogger().logWarning(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage())); //NOI18N
643 this.getLogger().logTrace(MessageFormat.format("num={0} - EXIT!", num)); //NOI18N
645 // Return read number
650 * Reads a string from a scanner until RETURN is pressed
652 * @return Read string from scanner
654 private String readString () {
655 return this.scanner.nextLine();
659 protected final void fillMenuMap () {
661 this.getLogger().logTrace("CALLED!"); //NOI18N
663 // Initialize first (main) menu
664 Menu menu = new ConsoleMenu("main", this); //NOI18N
667 this.getMenus().put("main", menu); //NOI18N
670 this.getLogger().logTrace("EXIT!"); //NOI18N