]> git.mxchange.org Git - addressbook-lib.git/blob - src/org/mxchange/addressbook/facade/contact/AddressbookContactFacade.java
Continued:
[addressbook-lib.git] / src / org / mxchange / addressbook / facade / contact / AddressbookContactFacade.java
1 /*
2  * Copyright (C) 2015 Roland Haeder
3  *
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.
8  *
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.
13  *
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/>.
16  */
17 package org.mxchange.addressbook.facade.contact;
18
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.ArrayList;
24 import java.util.Arrays;
25 import java.util.Iterator;
26 import java.util.List;
27 import javax.persistence.EntityManager;
28 import javax.persistence.PersistenceContext;
29 import org.mxchange.addressbook.client.AddressbookClient;
30 import org.mxchange.addressbook.exceptions.ContactAlreadyAddedException;
31 import org.mxchange.jcontacts.contact.Contact;
32 import org.mxchange.jcontacts.contact.gender.Gender;
33 import org.mxchange.jcore.client.Client;
34 import org.mxchange.jcore.exceptions.UnhandledUserChoiceException;
35 import org.mxchange.jcore.facade.BaseFacade;
36 import org.mxchange.jcoreeelogger.beans.local.logger.Log;
37 import org.mxchange.jcoreeelogger.beans.local.logger.LoggerBeanLocal;
38
39 /**
40  * A facade for contacts.
41  * <p>
42  * @author Roland Haeder
43  * @version 0.0
44  */
45 public class AddressbookContactFacade extends BaseFacade implements ContactFacade {
46
47         /**
48          * Column name list
49          */
50         private final List<String> columnNames;
51
52         /**
53          * Entity manager
54          */
55         @PersistenceContext
56         private EntityManager entityManager;
57
58         /**
59          * Logger instance
60          */
61         @Log
62         private LoggerBeanLocal logger;
63
64         /**
65          * Translated column name list
66          */
67         private final List<String> translatedColumnNames;
68
69         /**
70          * Constructor which accepts maxContacts for maximum (initial) contacts and
71          * a client instance.
72          * <p>
73          * @param client Client instance to use
74          * @throws java.sql.SQLException If an SQL error occurs
75          */
76         public AddressbookContactFacade (final Client client) throws SQLException {
77                 // Trace message
78                 this.getLogger().logTrace(MessageFormat.format("client={1} - CALLED!", client)); //NOI18N
79
80                 // Make sure all parameters are set correctly
81                 if (null == client) {
82                         // Abort here
83                         throw new NullPointerException("client is null"); //NOI18N
84                 }
85
86                 // Set client instance
87                 this.setClient(client);
88
89                 // Initialize list
90                 this.columnNames = new ArrayList<>(15);
91                 this.translatedColumnNames = new ArrayList<>(15);
92
93                 // And fill it
94                 this.fillColumnNamesFromBundle();
95
96                 // Debug message
97                 //* NOISY-DEBUG: */ this.getLogger().logDebug("client=" + client);
98         }
99
100         @Override
101         public void addContact (final Contact contact) throws ContactAlreadyAddedException {
102                 // Trace message
103                 this.getLogger().logTrace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
104
105                 // Contact instance must not be null
106                 if (null == contact) {
107                         // Abort here
108                         throw new NullPointerException("contact is null"); //NOI18N
109                 }
110
111                 // Add it
112                 this.entityManager.persist(contact);
113
114                 // Trace message
115                 this.getLogger().logTrace("EXIT!"); //NOI18N
116         }
117
118         @Override
119         public void doAddOtherAddress () {
120                 throw new UnsupportedOperationException("Not supported yet."); //NOI18N
121         }
122
123         @Override
124         public void doChangeAddressData (final Contact contact) {
125                 // Trace message
126                 this.getLogger().logTrace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
127
128                 // Contact must not be null
129                 if (null == contact) {
130                         // Abort here
131                         throw new NullPointerException("contact is null"); //NOI18N
132                 }
133                 if (!(this.getClient() instanceof AddressbookClient)) {
134                         // Cannot cast
135                         throw new IllegalArgumentException(MessageFormat.format("this.getClient()={0} does not implement AddressbookClient", this.getClient())); //NOI18N
136                 }
137
138                 // Get and cast client instance
139                 AddressbookClient client = (AddressbookClient) this.getClient();
140
141                 // First display it again
142                 client.displayAddressBox(contact);
143
144                 // Is it own data?
145                 if (contact.isOwnContact()) {
146                         // Deligate to client
147                         client.doChangeOwnAddressData(contact);
148                 } else {
149                         // Other contact's address data to change
150                         throw new UnsupportedOperationException("Changing contact entries not finished."); //NOI18N
151                 }
152
153                 // Trace message
154                 this.getLogger().logTrace("EXIT!"); //NOI18N
155         }
156
157         @Override
158         public void doChangeNameData (final Contact contact) {
159                 // Trace message
160                 this.getLogger().logTrace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
161
162                 // Contact must not be null
163                 if (null == contact) {
164                         // Abort here
165                         throw new NullPointerException("contact is null"); //NOI18N
166                 }
167
168                 // Get and cast client instance
169                 AddressbookClient client = (AddressbookClient) this.getClient();
170
171                 // First display them again
172                 client.displayNameBox(contact);
173
174                 // Is this own data?
175                 if (contact.isOwnContact()) {
176                         // Re-ask own data
177                         client.doChangeOwnNameData(contact);
178                 } else {
179                         // Then re-ask them ...
180                         throw new UnsupportedOperationException("Changing contact entries not finished."); //NOI18N
181                 }
182
183                 // Trace message
184                 this.getLogger().logTrace("EXIT!"); //NOI18N
185         }
186
187         @Override
188         public void doChangeOtherAddress () {
189                 throw new UnsupportedOperationException("Not supported yet."); //NOI18N
190         }
191
192         @Override
193         public void doChangeOtherData (final Contact contact) {
194                 // Trace message
195                 this.getLogger().logTrace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
196
197                 // Contact must not be null
198                 if (null == contact) {
199                         // Abort here
200                         throw new NullPointerException("contact is null"); //NOI18N
201                 }
202
203                 // Get and cast client instance
204                 AddressbookClient client = (AddressbookClient) this.getClient();
205
206                 // First display them again
207                 client.displayOtherDataBox(contact);
208
209                 // Is this own data?
210                 if (contact.isOwnContact()) {
211                         // Re-ask own data
212                         client.doChangeOwnOtherData(contact);
213                 } else {
214                         // Then re-ask them ...
215                         throw new UnsupportedOperationException("Changing contact entries not finished."); //NOI18N
216                 }
217
218                 // Trace message
219                 this.getLogger().logTrace("EXIT!"); //NOI18N
220         }
221
222         @Override
223         public void doChangeOwnData () throws IOException, SQLException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
224                 // Trace message
225                 this.getLogger().logTrace("CALLED!"); //NOI18N
226
227                 /*
228                  * First check if the user has registered own contact, before that
229                  * nothing can be changed.
230                  */
231                 if (!this.isOwnContactAdded()) {
232                         // Not added
233                         this.getClient().outputMessage("Sie haben noch nicht Ihre Daten eingegeben."); //NOI18N
234
235                         // Skip any below code
236                         return;
237                 }
238
239                 // Instance
240                 Contact contact = this.getOwnContact();
241
242                 // It must be found
243                 assert (contact instanceof Contact) : ": contact is not implementing Contact: " + contact;
244
245                 // Get and cast client instance
246                 AddressbookClient client = (AddressbookClient) this.getClient();
247
248                 // Display contact
249                 client.show(contact);
250
251                 try {
252                         // Ask user what to change
253                         client.userChooseChangeContactData(contact);
254                 } catch (final UnhandledUserChoiceException ex) {
255                         this.getLogger().logException(ex);
256                 }
257
258                 // Trace message
259                 this.getLogger().logTrace("EXIT!"); //NOI18N
260         }
261
262         @Override
263         public void doDeleteOtherAddress () {
264                 throw new UnsupportedOperationException("Not supported yet."); //NOI18N
265         }
266
267         @Override
268         public void doEnterOwnData () throws ContactAlreadyAddedException, IOException {
269                 // Trace message
270                 this.getLogger().logTrace("CALLED!"); //NOI18N
271
272                 // Is own contact already added?
273                 if (this.isOwnContactAdded()) {
274                         // Don't continue here
275                         throw new ContactAlreadyAddedException();
276                 }
277
278                 // Get and cast client instance
279                 AddressbookClient client = (AddressbookClient) this.getClient();
280
281                 // Deligate this call to the client
282                 Contact contact = client.doEnterOwnData();
283
284                 // Is it set?
285                 if (contact instanceof Contact) {
286                         // Add it to contact "book"
287                         this.registerContact(contact);
288                 }
289
290                 // Trace message
291                 this.getLogger().logTrace("EXIT!"); //NOI18N
292         }
293
294         @Override
295         public void doListContacts () {
296                 throw new UnsupportedOperationException("Not supported yet."); //NOI18N
297         }
298
299         @Override
300         public void doSearchContacts () {
301                 throw new UnsupportedOperationException("Not supported yet."); //NOI18N
302         }
303
304         @Override
305         public void doShutdown () throws SQLException, IOException {
306                 // Trace message
307                 this.getLogger().logTrace("CALLED!"); //NOI18N
308
309                 // Shut down the database layer
310                 this.entityManager.close();
311
312                 // Trace message
313                 this.getLogger().logTrace("EXIT!"); //NOI18N
314         }
315
316         @Override
317         public String enterOwnCellNumber () {
318                 // Trace message
319                 this.getLogger().logTrace("CALLED!"); //NOI18N
320
321                 // Get and cast client instance
322                 AddressbookClient client = (AddressbookClient) this.getClient();
323
324                 return client.enterString(5, 30, "Bitte geben Sie Ihre Handynummer an: ", true);
325         }
326
327         @Override
328         public String enterOwnCity () {
329                 // Trace message
330                 this.getLogger().logTrace("CALLED!"); //NOI18N
331
332                 // Get and cast client instance
333                 AddressbookClient client = (AddressbookClient) this.getClient();
334
335                 return client.enterString(3, 50, "Bitte geben Sie Ihren Wohnort ein: ", false);
336         }
337
338         @Override
339         public String enterOwnComment () {
340                 // Trace message
341                 this.getLogger().logTrace("CALLED!"); //NOI18N
342
343                 // Get and cast client instance
344                 AddressbookClient client = (AddressbookClient) this.getClient();
345
346                 return client.enterString(0, 100, "Kommentar zu Ihrem Eintrag: ", true);
347         }
348
349         @Override
350         public String enterOwnCompanyName () {
351                 // Trace message
352                 this.getLogger().logTrace("CALLED!"); //NOI18N
353
354                 // Get and cast client instance
355                 AddressbookClient client = (AddressbookClient) this.getClient();
356
357                 return client.enterString(5, 50, "Bitte geben Sie Ihre Firmenbezeichnung ein: ", true);
358         }
359
360         @Override
361         public String enterOwnCountryCode () {
362                 // Trace message
363                 this.getLogger().logTrace("CALLED!"); //NOI18N
364
365                 // Get and cast client instance
366                 AddressbookClient client = (AddressbookClient) this.getClient();
367
368                 return client.enterString(2, 2, "Bitte geben Sie den zweistelligen Ländercode von Ihrem Land ein: ", false).toUpperCase();
369         }
370
371         @Override
372         public String enterOwnEmailAddress () {
373                 // Trace message
374                 this.getLogger().logTrace("CALLED!"); //NOI18N
375
376                 // Get and cast client instance
377                 AddressbookClient client = (AddressbookClient) this.getClient();
378
379                 return client.enterString(10, 50, "Bitte geben Sie Ihre Email-Adresse ein: ", true);
380         }
381
382         @Override
383         public String enterOwnFamilyName () {
384                 // Trace message
385                 this.getLogger().logTrace("CALLED!"); //NOI18N
386
387                 // Get and cast client instance
388                 AddressbookClient client = (AddressbookClient) this.getClient();
389
390                 return client.enterString(2, 50, "Bitte geben Sie Ihren Nachnamen ein: ", false);
391         }
392
393         @Override
394         public String enterOwnFaxNumber () {
395                 // Trace message
396                 this.getLogger().logTrace("CALLED!"); //NOI18N
397
398                 // Get and cast client instance
399                 AddressbookClient client = (AddressbookClient) this.getClient();
400
401                 return client.enterString(5, 30, "Bitte geben Sie Ihre Faxnummer an: ", true);
402         }
403
404         @Override
405         public String enterOwnFirstName () {
406                 // Trace message
407                 this.getLogger().logTrace("CALLED!"); //NOI18N
408
409                 // Get and cast client instance
410                 AddressbookClient client = (AddressbookClient) this.getClient();
411
412                 return client.enterString(2, 50, "Bitte geben Sie Ihren Vornamen ein: ", false);
413         }
414
415         @Override
416         public Gender enterOwnGender () {
417                 // Trace message
418                 this.getLogger().logTrace("CALLED!"); //NOI18N
419
420                 // Get and cast client instance
421                 AddressbookClient client = (AddressbookClient) this.getClient();
422
423                 return client.enterGender("Bitte geben Sie die Anrede ein: (M=Herr, F=Frau, C=Firma): ");
424         }
425
426         @Override
427         public String enterOwnPhoneNumber () {
428                 // Trace message
429                 this.getLogger().logTrace("CALLED!"); //NOI18N
430
431                 // Get and cast client instance
432                 AddressbookClient client = (AddressbookClient) this.getClient();
433
434                 return client.enterString(5, 30, "Bitte geben Sie Ihre Telefonnummer an: ", true);
435         }
436
437         @Override
438         public String enterOwnStreet () {
439                 // Trace message
440                 this.getLogger().logTrace("CALLED!"); //NOI18N
441
442                 // Get and cast client instance
443                 AddressbookClient client = (AddressbookClient) this.getClient();
444
445                 return client.enterString(5, 50, "Bitte geben Sie Ihre Strasse und Hausnummer ein: ", false);
446         }
447
448         @Override
449         public int enterOwnZipCode () {
450                 // Trace message
451                 this.getLogger().logTrace("CALLED!"); //NOI18N
452
453                 // Get and cast client instance
454                 AddressbookClient client = (AddressbookClient) this.getClient();
455
456                 return client.enterInt(0, 99_999, "Bitte geben Sie Ihre Postleitzahl ein: ");
457         }
458
459         @Override
460         public final int getColumnCount () {
461                 assert (this.columnNames instanceof List) : "this.columnNames is not initialized"; //NOI18N
462
463                 return this.columnNames.size();
464         }
465
466         @Override
467         public String getColumnName (final int columnIndex) {
468                 assert (this.columnNames instanceof List) : "this.columnNames is not initialized"; //NOI18N
469
470                 // Get column name at index
471                 return this.columnNames.get(columnIndex);
472         }
473
474         @Override
475         public String getTranslatedColumnName (final int columnIndex) {
476                 assert (this.translatedColumnNames instanceof List) : "this.translatedColumnNames is not initialized"; //NOI18N
477
478                 // Get column name at index
479                 return this.translatedColumnNames.get(columnIndex);
480         }
481
482         @Override
483         public Object getValueFromRowColumn (final int rowIndex, final int columnIndex) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
484                 // Trace message
485                 this.getLogger().logTrace(MessageFormat.format("rowIndex={0},columnIndex={1} CALLED!", rowIndex, columnIndex)); //NOI18N
486
487                 // Then get specific row from database which is a Contact instance
488                 Storable storable = this.getFrontend().getStorableAtRow(rowIndex);
489
490                 // Debug message
491                 this.getLogger().logDebug(MessageFormat.format("storable={0}", storable)); //NOI18N
492
493                 // It may return null
494                 if (null == storable) {
495                         // Nothing found
496                         this.getLogger().logWarning("contact is null - returning null ..."); //NOI18N
497                         return null;
498                 }
499
500                 // Convert column index -> name
501                 String columnName = this.getColumnName(columnIndex);
502
503                 // Debug message
504                 this.getLogger().logDebug(MessageFormat.format("columnName={0}", columnName)); //NOI18N
505
506                 // Now get that column
507                 Object value = null;
508                 try {
509                         value = storable.getValueFromColumn(columnName);
510                 } catch (final IllegalArgumentException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
511                         this.abortProgramWithException(ex);
512                 }
513
514                 // Trace message
515                 this.getLogger().logTrace(MessageFormat.format("value={0} - EXIT!", value)); //NOI18N
516
517                 // Return it
518                 return value;
519         }
520
521         @Override
522         public boolean isOwnContactAdded () throws IOException {
523                 // Trace message
524                 this.getLogger().logTrace("CALLED!"); //NOI18N
525
526                 // Init variable
527                 boolean isAdded = false;
528
529                 try {
530                         // Deligate this call to frontend
531                         isAdded = ((AddressbookContactFrontend) this.getFrontend()).isOwnContactFound();
532                 } catch (final SQLException | IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
533                         // Something bad happened
534                         this.abortProgramWithException(ex);
535                 }
536
537                 // Trace message
538                 this.getLogger().logTrace(MessageFormat.format("isAdded={0} : EXIT!", isAdded)); //NOI18N
539
540                 // Return result
541                 return isAdded;
542         }
543
544         @Override
545         public void registerContact (final Contact contact) {
546                 // Trace message
547                 this.getLogger().logTrace(MessageFormat.format("contact={0} CALLED!", contact)); //NOI18N
548
549                 // Sanity check
550                 if (null == contact) {
551                         // Abort here
552                         throw new NullPointerException("contact is null"); //NOI18N
553                 }
554                 try {
555                         // Check if contact is found
556                         if (this.entityManager.contains(contact)) {
557                                 // Contact already added
558                                 // TODO Do something here
559                         } else if ((contact.isOwnContact()) && (this.isOwnContactAdded())) {
560                                 // Own contact already added
561                                 // TODO Do something
562                         }
563
564                         // Add contact to internal list
565                         this.addContact(contact);
566                 } catch (final ContactAlreadyAddedException | IOException ex) {
567                         // Abort here
568                         this.abortProgramWithException(ex);
569                 }
570
571                 // Trace message
572                 this.getLogger().logTrace("EXIT!"); //NOI18N
573         }
574
575         /**
576          * Logs given exception and exits program
577          * <p>
578          * @param throwable Throwable
579          */
580         private void abortProgramWithException (Throwable throwable) {
581                 // Log exception
582                 this.logException(throwable);
583
584                 // Abort here
585                 System.exit(1);
586         }
587
588         /**
589          * Fills the column names array with strings from bundle
590          */
591         private void fillColumnNamesFromBundle () {
592                 assert (this.columnNames instanceof List) : "this.columnNames is not initialized"; //NOI18N
593                 assert (this.translatedColumnNames instanceof List) : "this.translatedColumnNames is not initialized"; //NOI18N
594
595                 // Debug message
596                 this.getLogger().logTrace("CALLED!"); //NOI18N
597
598                 // First get an iterator from key set to iterate over
599                 Iterator<String> iterator = this.getBundle().keySet().iterator();
600
601                 // Then iterate over all
602                 while (iterator.hasNext()) {
603                         // Get next element
604                         String key = iterator.next().toLowerCase();
605
606                         // Does the key start with AddressbookContactFacade.columnName ?
607                         if (key.startsWith("ContactManager.columnName")) { //NOI18N
608                                 // This is the wanted entry.
609                                 this.getLogger().logDebug(MessageFormat.format("key={0}", key)); //NOI18N
610
611                                 // Convert string to array based on delimiter '.'
612                                 String[] tokens = this.getArrayFromString(key, "."); //NOI18N
613
614                                 // Token array must contain 4 elements (AddressbookContactFacade.columnName.foo.text)
615                                 assert (tokens.length == 4) : MessageFormat.format("Array tokens contains not 4 elements: {0}", Arrays.toString(tokens)); //NOI18N
616
617                                 // Get pre-last element
618                                 String columnName = tokens[tokens.length - 2];
619
620                                 // Debug message
621                                 this.getLogger().logDebug(MessageFormat.format("columnName={0} - adding ...", columnName)); //NOI18N
622
623                                 // So add it
624                                 this.columnNames.add(columnName);
625                                 this.translatedColumnNames.add(this.getBundle().getString(key));
626                         }
627                 }
628
629                 // Debug message
630                 this.getLogger().logTrace(MessageFormat.format("getColumnCount()={0}: EXIT!", this.getColumnCount())); //NOI18N
631         }
632
633         /**
634          * Getter for logger instance
635          * <p>
636          * @return Logger instance
637          */
638         private LoggerBeanLocal getLogger () {
639                 return this.logger;
640         }
641
642         /**
643          * "Getter" for own contact instance or null if not found
644          * <p>
645          * @return Contact instance or null
646          */
647         private Contact getOwnContact () {
648                 // Trace message
649                 this.getLogger().logTrace("CALLED!"); //NOI18N
650
651                 // Deligate this call to database frontend
652                 Contact contact = null;
653                 //Contact contact = ((AddressbookContactFrontend) this.getFrontend()).getOwnContact();
654
655                 // Trace message
656                 this.getLogger().logTrace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
657
658                 // Return instance or null
659                 return contact;
660         }
661
662         /**
663          * Logs given exception
664          * <p>
665          * @param exception Throwable
666          */
667         protected void logException (final Throwable exception) {
668                 this.getLogger().logException(exception);
669         }
670 }