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.exceptions.ContactAlreadyAddedException;
29 import org.mxchange.addressbook.manager.contact.ManageableContactAddressbook;
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.exceptions.UnhandledUserChoiceException;
37 import org.mxchange.jcore.model.contact.Contact;
38 import org.mxchange.jcore.model.contact.UserContact;
39 import org.mxchange.jcore.model.contact.gender.Gender;
40 import org.mxchange.jcore.model.contact.gender.GenderUtils;
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 ManageableContactAddressbook manager = (ManageableContactAddressbook) this.getManager();
160 // Own street and number
161 String streetNumber = manager.enterOwnStreet();
164 Long zipCode = (long) 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 ManageableContactAddressbook manager = (ManageableContactAddressbook) this.getManager();
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 ManageableContactAddressbook manager = (ManageableContactAddressbook) this.getManager();
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 ManageableContactAddressbook manager = (ManageableContactAddressbook) this.getManager();
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 {
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 ManageableContactAddressbook manager = (ManageableContactAddressbook) this.getManager();
329 // TODO Rewrite this ugly switch() block
333 // Enter/add own data
334 manager.doEnterOwnData();
335 } catch (final ContactAlreadyAddedException ex) {
337 this.outputMessage("Sie haben bereits Ihre eigenen Daten eingegeben.");
341 case '2': // Change own data
342 manager.doChangeOwnData();
345 case '3': // Add new addess
346 manager.doAddOtherAddress();
349 case '4': // List contacts
350 manager.doListContacts();
353 case '5': // Search addresses
354 manager.doSearchContacts();
357 case '6': // Change other addess
358 manager.doChangeOtherAddress();
361 case '7': // Delete other address
362 manager.doDeleteOtherAddress();
368 this.getApplication().doShutdown();
369 } catch (final SQLException | IOException ex) {
370 this.abortProgramWithException(ex);
375 // TODO throw own exception
376 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
378 } catch (final IOException | SQLException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
379 // Something bad happened
380 this.abortProgramWithException(ex);
384 this.getLogger().logTrace("EXIT!"); //NOI18N
388 public char enterChar (final char[] validChars, final String message) {
390 this.getLogger().logTrace(MessageFormat.format("validChars={0},message={1} - CALLED!", Arrays.toString(validChars), message)); //NOI18N
392 // The validChars must not null be null and filled with at least one char
393 if (null == validChars) {
395 throw new NullPointerException("validChars is null"); //NOI18N
396 } else if (validChars.length == 0) {
398 throw new IllegalArgumentException("validChars is not filled."); //NOI18N
403 // Sort array, else binarySearch() won't work
404 Arrays.sort(validChars);
406 // Keep asking until valid char has been entered
407 while (Arrays.binarySearch(validChars, input) < 0) {
409 System.out.print(message);
412 input = this.readChar();
416 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
423 public Gender enterGender (final String message) {
425 this.getLogger().logTrace(MessageFormat.format("message={0} - CALLED!", message)); //NOI18N
428 char[] validChars = Gender.validChars();
431 //* NOISY-DEBUG: */ System.out.println(validChars);
433 char gender = this.enterChar(validChars, message);
435 // Now get a Gender instance back
436 Gender g = Gender.fromChar(gender);
438 // g must not be null
439 assert (g instanceof Gender) : "g is not set."; //NOI18N
442 this.getLogger().logTrace(MessageFormat.format("g={0} - EXIT!", g)); //NOI18N
449 public int enterInt (final int minimum, final int maximum, final String message) {
451 this.getLogger().logTrace(MessageFormat.format("minimum={0},maximum={1},message={2} - CALLED!", minimum, maximum, message)); //NOI18N
453 // Minimum should not be below zero
454 assert (minimum >= 0) : MessageFormat.format("minimum={0} is below zero", minimum); //NOI18N
455 assert (maximum > minimum) : MessageFormat.format("maximum {0} is smaller than minimum {1}", maximum, minimum); //NOI18N
460 while ((input < minimum) || (input > maximum)) {
462 System.out.print(message);
464 // Read integer from user
465 input = this.readInt();
469 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
476 public String enterString (final int minLength, final int maxLength, final String message, final boolean allowEmpty) {
478 this.getLogger().logTrace(MessageFormat.format("minLength={0},maxLength={1},message={2}allowEmpty={3} - CALLED!", minLength, maxLength, message, allowEmpty)); //NOI18N
480 // Check on length, e.g. country codes are excactly 2 chars long
481 assert (maxLength >= minLength);
486 // Check if it is to short or to long
487 while (((null == input) || ((input.length() < minLength) && (!allowEmpty))) || ((input.length() > 0) && (input.length() < minLength) && (allowEmpty)) || ((input instanceof String) && (input.length() > maxLength))) {
489 System.out.print(message);
492 input = this.readString();
496 this.getLogger().logTrace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
503 public SelectableMenuItem getMenuItem (final char accessKey, final String text) {
504 // Return a new console menu item
505 return new ConsoleMenuItem(accessKey, text);
509 public void init () {
511 this.getLogger().logTrace("CALLED!"); //NOI18N
513 // Init contact manager here
515 this.initContactManager();
516 } catch (final SQLException ex) {
518 this.abortProgramWithException(ex);
525 this.getLogger().logTrace("EXIT!"); //NOI18N
529 public void outputMessage (final String message) {
530 System.out.println(message);
534 public void showCurrentMenu () {
535 this.showMenu(this.getCurrentMenu());
539 public void showEntry (final SelectableMenuItem item) {
540 // Access key then text
541 this.outputMessage(MessageFormat.format("[{0}] {1}", item.getAccessKey(), item.getText())); //NOI18N
545 public void showWelcome () {
546 this.outputMessage(MessageFormat.format("Welcome to {0}", AddressbookApplication.printableTitle())); //NOI18N
547 this.outputMessage(""); //NOI18N
548 this.outputMessage("Copyright(c) 2015 by Roland Haeder, this is free software"); //NOI18N
551 this.getLogger().logDebug("Intro shown to user"); //NOI18N
555 public void userChooseChangeContactData (final Contact contact) throws UnhandledUserChoiceException {
557 this.getLogger().logTrace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
559 // Contact must not be null
560 if (null == contact) {
562 throw new NullPointerException("contact is null"); //NOI18N
565 // Ask the user for editing [name], [a]ddress or [other] data
566 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) ");
568 // Get manager and cast it
569 ManageableContactAddressbook manager = (ManageableContactAddressbook) this.getManager();
571 // TODO Get rid of this ugly switch block, too
573 case 'n': // Name data
574 manager.doChangeNameData(contact);
577 case 'a': // Address data
578 manager.doChangeAddressData(contact);
581 case 'o': // Other data
582 manager.doChangeOtherData(contact);
585 case 'x': // Exit this menu
586 // Ignored as it should go back
590 // TODO throw own exception
591 throw new UnhandledUserChoiceException(MessageFormat.format("Choice '{0}' not handled yet.", choice)); //NOI18N
595 this.getLogger().logTrace("EXIT!"); //NOI18N
599 * Reads one character
601 * @return A single character
603 private char readChar () {
605 String input = this.readString();
608 this.getLogger().logDebug(MessageFormat.format("input={0}", input)); //NOI18N
610 // This must be only one character
611 if (input.length() != 1) {
616 // Get char from first (and only) position
617 return input.charAt(0);
621 * Reads an integer (int) from user
623 * @return An integer number
625 private int readInt () {
626 // First read a string
627 String input = this.readString();
630 this.getLogger().logDebug(MessageFormat.format("input={0}", input)); //NOI18N
632 // Init number with invalid value
635 // Parse number, this can be risky
637 num = Integer.parseInt(input);
638 } catch (final NumberFormatException e) {
639 this.outputMessage("Bitte geben Sie nur Zahlen ein!");
640 this.getLogger().logWarning(MessageFormat.format("No numbers-only entered. input={0},message={1}", input, e.getMessage())); //NOI18N
644 this.getLogger().logTrace(MessageFormat.format("num={0} - EXIT!", num)); //NOI18N
646 // Return read number
651 * Reads a string from a scanner until RETURN is pressed
653 * @return Read string from scanner
655 private String readString () {
656 return this.scanner.nextLine();
660 protected final void fillMenuMap () {
662 this.getLogger().logTrace("CALLED!"); //NOI18N
664 // Initialize first (main) menu
665 Menu menu = new ConsoleMenu("main", this); //NOI18N
668 this.getMenus().put("main", menu); //NOI18N
671 this.getLogger().logTrace("EXIT!"); //NOI18N