]> git.mxchange.org Git - jaddressbook-share-lib.git/blob - Addressbook/src/org/mxchange/addressbook/database/backend/csv/Base64CsvDatabaseBackend.java
Continued with refacturing:
[jaddressbook-share-lib.git] / Addressbook / src / org / mxchange / addressbook / database / backend / csv / Base64CsvDatabaseBackend.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.database.backend.csv;
18
19 import java.io.DataOutput;
20 import java.io.FileNotFoundException;
21 import java.io.IOException;
22 import java.io.RandomAccessFile;
23 import java.sql.SQLException;
24 import java.text.MessageFormat;
25 import java.util.ArrayList;
26 import java.util.Base64;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.StringTokenizer;
30 import org.mxchange.addressbook.FrameworkInterface;
31 import org.mxchange.addressbook.contact.Contact;
32 import org.mxchange.addressbook.contact.Gender;
33 import org.mxchange.addressbook.contact.book.BookContact;
34 import org.mxchange.addressbook.contact.user.UserContact;
35 import org.mxchange.addressbook.database.backend.BaseDatabaseBackend;
36 import org.mxchange.addressbook.database.backend.DatabaseBackend;
37 import org.mxchange.addressbook.database.frontend.DatabaseWrapper;
38 import org.mxchange.addressbook.database.storage.Storeable;
39 import org.mxchange.addressbook.database.storage.csv.StoreableCsv;
40 import org.mxchange.addressbook.exceptions.BadTokenException;
41
42 /**
43  * A database backend with CSV file as storage implementation
44  *
45  * @author Roland Haeder
46  */
47 public class Base64CsvDatabaseBackend extends BaseDatabaseBackend implements DatabaseBackend {
48
49         /**
50          * Output stream for this storage engine
51          */
52         private RandomAccessFile storageFile;
53
54         /**
55          * Constructor with table name
56          *
57          * @param tableName Name of "table"
58          * @param wrapper Wrapper instance to call back
59          */
60         public Base64CsvDatabaseBackend (final String tableName, final DatabaseWrapper wrapper) {
61                 // Trace message
62                 this.getLogger().trace(MessageFormat.format("tableName={0},wrapper={1}", tableName, wrapper)); //NOI18N
63
64                 // Debug message
65                 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName)); //NOI18N
66
67                 // Set table name here, too
68                 this.setTableName(tableName);
69
70                 // Set wrapper here
71                 this.setWrapper(wrapper);
72
73                 // Construct file name
74                 String fileName = String.format("data/table_%s.b64", tableName); //NOI18N
75
76                 // Debug message
77                 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName)); //NOI18N
78
79                 try {
80                         // Try to initialize the storage (file instance)
81                         this.storageFile = new RandomAccessFile(fileName, "rw"); //NOI18N
82                 } catch (final FileNotFoundException ex) {
83                         // Did not work
84                         this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString())); //NOI18N
85                         System.exit(1);
86                 }
87
88                 // Output message
89                 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName)); //NOI18N
90         }
91
92         /**
93          * This database backend does not need to connect
94          */
95         @Override
96         public void connectToDatabase () throws SQLException {
97                 // Empty body
98         }
99
100         /**
101          * Shuts down this backend
102          */
103         @Override
104         public void doShutdown () {
105                 // Trace message
106                 this.getLogger().trace("CALLED!"); //NOI18N
107
108                 try {
109                         // Close file
110                         this.getStorageFile().close();
111                 } catch (final IOException ex) {
112                         // Abort program
113                         this.abortProgramWithException(ex);
114                 }
115
116                 // Trace message
117                 this.getLogger().trace("EXIT!"); //NOI18N
118         }
119
120         /**
121          * Some "getter" for total row count
122          *
123          * @return Total row count
124          */
125         @Override
126         public int getTotalCount () {
127                 // Trace message
128                 this.getLogger().trace("CALLED!"); //NOI18N
129
130                 try {
131                         // Do a deprecated call
132                         // @todo this needs rewrite!
133                         return this.readList().size();
134                 } catch (final BadTokenException ex) {
135                         this.abortProgramWithException(ex);
136                 }
137
138                 // Invalid return
139                 this.getLogger().trace("Returning -1 ... : EXIT!"); //NOI18N
140                 return -1;
141         }
142
143         /**
144          * Checks whether at least one row is found with given boolean value.
145          *
146          * @param columnName Column to check for boolean value
147          * @param bool Boolean value to check
148          * @return Whether boolean value is found and returns at least one row
149          */
150         @Override
151         public boolean isRowFound (final String columnName, final boolean bool) {
152                 // Trace message
153                 this.getLogger().trace(MessageFormat.format("columnName={0},bool={1} - CALLED!", columnName, bool)); //NOI18N
154
155                 // Is at least one entry found?
156                 if (this.getTotalCount() == 0) {
157                         // No entry found at all
158                         return false;
159                 }
160
161                 // Default is not found
162                 boolean isFound = false;
163
164                 // Firsr rewind
165                 this.rewind();
166
167                 // Then loop through all lines
168                 while (!this.isEndOfFile()) {
169                         // Read line
170                         String line = this.readLine();
171
172                         // Debug message
173                         this.getLogger().debug(MessageFormat.format("line={0}", line));
174
175                         try {
176                                 // And parse it to a Contact instance
177                                 Contact contact = this.parseLineToContact(line);
178
179                                 // Debug message
180                                 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
181
182                                 // This should not be null
183                                 if (contact == null) {
184                                         // Throw exception
185                                         throw new NullPointerException("contact is null");
186                                 }
187
188                                 // Now let the contact object check if it has such attribute
189                                 if (contact.isValueEqual(columnName, bool)) {
190                                         // Yes, it is set
191                                         isFound = true;
192                                         break;
193                                 }
194                         } catch (final BadTokenException ex) {
195                                 // Don't continue with bad data
196                                 this.abortProgramWithException(ex);
197                         }
198                 }
199
200                 // Trace message
201                 this.getLogger().trace(MessageFormat.format("isFound={0} - EXIT!", isFound));
202
203                 // Return result
204                 return isFound;
205         }
206
207         /**
208          * Gets an iterator for contacts
209          *
210          * @return Iterator for contacts
211          * @throws org.mxchange.addressbook.exceptions.BadTokenException If the underlaying method has found an invalid token
212          */
213         @Override
214         public Iterator<? extends Storeable> iterator () throws BadTokenException {
215                 // Trace message
216                 this.getLogger().trace("CALLED!"); //NOI18N
217                 
218                 /*
219                  * Then read the file into RAM (yes, not perfect for >1000 entries ...)
220                  * and get a List back.
221                  */
222                 List<? extends Storeable> list = this.readList();
223                 
224                 // List must be set
225                 assert (list instanceof List) : "list has not been set."; //NOI18N
226                 
227                 // Trace message
228                 this.getLogger().trace(MessageFormat.format("list.iterator()={0} - EXIT!", list.iterator())); //NOI18N
229                 
230                 // Get iterator from list and return it
231                 return list.iterator();
232         }
233
234         /**
235          * Get length of underlaying file
236          *
237          * @return Length of underlaying file
238          */
239         @Override
240         public long length () {
241                 long length = 0;
242
243                 try {
244                         length = this.getStorageFile().length();
245                         this.getLogger().debug(MessageFormat.format("length={0}", length)); //NOI18N
246                 } catch (final IOException ex) {
247                         // Length cannot be determined
248                         // Abort program
249                         this.abortProgramWithException(ex);
250                 }
251
252                 // Return result
253                 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length)); //NOI18N
254                 return length;
255         }
256
257         /**
258          * Reads a single row from database.
259          * 
260          * @param rowIndex Row index (or how much to skip)
261          * @return A Storeable instance
262          */
263         @Override
264         public Storeable readRow (final int rowIndex) {
265                 // First rewind
266                 this.rewind();
267
268                 // Intialize variables
269                 int count = 0;
270                 Storeable storeable = null;
271
272                 // Read all rows
273                 do {
274                         // Read row
275                         String line = this.readLine();
276
277                         // Callback the wrapper to handle parsing
278                         storeable = this.getWrapper().parseLineToStoreable(line);
279
280                         // Increment counter
281                         count++;
282                 } while (!this.isEndOfFile() || (count > rowIndex));
283
284                 // Return found element
285                 return storeable;
286         }
287
288         /**
289          * Rewinds backend
290          */
291         @Override
292         public void rewind () {
293                 // Trace message
294                 this.getLogger().trace("CALLED!"); //NOI18N
295
296                 try {
297                         // Rewind underlaying database file
298                         this.getStorageFile().seek(0);
299                 } catch (final IOException ex) {
300                         // Abort program
301                         this.abortProgramWithException(ex);
302                 }
303
304                 // Trace message
305                 this.getLogger().trace("EXIT!"); //NOI18N
306         }
307
308         /**
309          * Stores given object by "visiting" it
310          *
311          * @param object An object implementing Storeable
312          * @throws java.io.IOException From "inner" class
313          */
314         @Override
315         public void store (final Storeable object) throws IOException {
316                 // Trace message
317                 this.getLogger().trace(MessageFormat.format("object={0} - CALLED!", object)); //NOI18N
318
319                 // Object must not be null
320                 if (object == null) {
321                         // Abort here
322                         throw new NullPointerException("object is null"); //NOI18N
323                 }
324
325                 // Make sure the instance is there (DataOutput flawor)
326                 assert (this.storageFile instanceof DataOutput);
327
328                 // Try to cast it, this will fail if the interface is not implemented
329                 StoreableCsv csv = (StoreableCsv) object;
330
331                 // Now get a string from the object that needs to be stored
332                 String str = csv.getCsvStringFromStoreableObject();
333
334                 // Debug message
335                 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str)); //NOI18N
336
337                 // Encode line in BASE-64
338                 byte[] encoded = Base64.getEncoder().encode(str.getBytes());
339
340                 // The string is now a valid CSV string
341                 this.getStorageFile().write(encoded);
342
343                 // Trace message
344                 this.getLogger().trace("EXIT!"); //NOI18N
345         }
346
347         /**
348          * Adds given contact to list
349          *
350          * @param instance An instance of FrameworkInterface to add
351          * @param list List instance
352          */
353         private void addToList (final Storeable instance, final List<Storeable> list) {
354                 // Trace message
355                 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", instance)); //NOI18N
356
357                 // No null here
358                 if (instance == null) {
359                         // Throw exception
360                         throw new NullPointerException("contact is null"); //NOI18N
361                 } else if (list == null) {
362                         // Throw exception
363                         throw new NullPointerException("list is null"); //NOI18N
364                 }
365
366                 // Debug message
367                 this.getLogger().debug(MessageFormat.format("contact={0}", instance)); //NOI18N
368
369                 // Is the contact read?
370                 if (instance instanceof FrameworkInterface) {
371                         // Then add it
372                         boolean added = list.add(instance);
373
374                         // Debug message
375                         this.getLogger().debug(MessageFormat.format("contact={0} added={1}", instance, added)); //NOI18N
376
377                         // Has it been added?
378                         if (!added) {
379                                 // Not added
380                                 this.getLogger().warn("Contact object has not been added."); //NOI18N
381                         }
382                 }
383
384                 // Trace message
385                 this.getLogger().trace("EXIT!"); //NOI18N
386         }
387
388         /**
389          * Returns storage file
390          *
391          * @return Storage file instance
392          */
393         private RandomAccessFile getStorageFile () {
394                 return this.storageFile;
395         }
396
397         /**
398          * Checks whether end of file has been reached
399          *
400          * @return Whether lines are left to read
401          */
402         private boolean isEndOfFile () {
403                 // Default is EOF
404                 boolean isEof = true;
405
406                 try {
407                         isEof = (this.getStorageFile().getFilePointer() >= this.length());
408                 } catch (final IOException ex) {
409                         // Length cannot be determined
410                         this.getLogger().catching(ex);
411                 }
412
413                 // Return status
414                 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof)); //NOI18N
415                 return isEof;
416         }
417
418         /**
419          * Parses given line and creates a Contact instance
420          * 
421          * @param line Raw line to parse
422          *
423          * @return Contact instance
424          */
425         private Contact parseLineToContact (final String line) throws BadTokenException {
426                 // Trace message
427                 this.getLogger().trace(MessageFormat.format("line={0} - CALLED!", line)); //NOI18N
428
429                 // Init A lot variables
430                 Long num = null;
431                 Boolean bool = null;
432                 Gender gender = null;
433                 int count = 0;
434                 Contact contact = null;
435
436                 // Debug message
437                 this.getLogger().debug(MessageFormat.format("line={0}", line)); //NOI18N
438
439                 // Then tokenize it
440                 // @TODO Move this into separate method
441                 StringTokenizer tokenizer = new StringTokenizer(line, ";"); //NOI18N
442
443                 // Reset variables
444                 count = 0;
445                 contact = null;
446
447                 // The tokens are now available, so get all
448                 while (tokenizer.hasMoreElements()) {
449                         // Reset variables
450                         num = null;
451                         bool = null;
452
453                         // Get next token
454                         String token = tokenizer.nextToken();
455
456                         // If char " is at pos 2 (0,1,2), then cut it of there
457                         if ((token.charAt(0) != '"') && (token.charAt(2) == '"')) {
458                                 // UTF-8 writer characters found
459                                 token = token.substring(2);
460                         }
461
462                         // Debug message
463                         this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
464
465                         // Verify token, it must have double-quotes on each side
466                         if ((!token.startsWith("\"")) || (!token.endsWith("\""))) { //NOI18N
467                                 // Something bad was read
468                                 throw new BadTokenException(token, count); //NOI18N
469                         }
470
471                         // All fine, so remove it
472                         String strippedToken = token.substring(1, token.length() - 1);
473
474                         // Is the string's content "null"?
475                         if (strippedToken.equals("null")) { //NOI18N
476                                 // Debug message
477                                 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken)); //NOI18N
478
479                                 // This needs to be set to null
480                                 strippedToken = null;
481                         }
482
483                         // Debug message
484                         this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken)); //NOI18N
485
486                         // Now, let's try a number check, if no null
487                         if (strippedToken != null) {
488                                 // Okay, no null, maybe the string bears a decimal number?
489                                 try {
490                                         num = Long.valueOf(strippedToken);
491
492                                         // Debug message
493                                         this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken)); //NOI18N
494                                 } catch (final NumberFormatException ex) {
495                                         // No number, then set default
496                                         num = null;
497                                 }
498                         }
499
500                         // Now, let's try a boolean check, if no null
501                         if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) { //NOI18N
502                                 // Debug message
503                                 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken)); //NOI18N
504
505                                 // parseBoolean() is relaxed, so no exceptions
506                                 bool = Boolean.valueOf(strippedToken);
507                         }
508
509                         // Debug message
510                         this.getLogger().debug(MessageFormat.format("strippedToken={0},num={1},bool={2}", strippedToken, num, bool)); //NOI18N
511
512                         // Now, let's try a gender check, if no null
513                         if ((strippedToken != null) && (num == null) && (bool == null) && ((strippedToken.equals("M")) || (strippedToken.equals("F")) || (strippedToken.equals("C")))) { //NOI18N
514                                 // Get first character
515                                 gender = Gender.fromChar(strippedToken.charAt(0));
516
517                                 // Debug message
518                                 this.getLogger().debug(MessageFormat.format("strippedToken={0},gender={1}", strippedToken, gender)); //NOI18N
519
520                                 // This instance must be there
521                                 assert (gender instanceof Gender) : MessageFormat.format("gender is not set by Gender.fromChar({0})", strippedToken); //NOI18N
522                         }
523
524                         // Now it depends on the counter which position we need to check
525                         switch (count) {
526                                 case 0: // isOwnContact
527                                         assert ((bool instanceof Boolean));
528
529                                         // Debug message
530                                         this.getLogger().debug(MessageFormat.format("bool={0}", bool)); //NOI18N
531
532                                         // Is it own contact?
533                                         if (true == bool) {
534                                                 // Debug message
535                                                 this.getLogger().debug("Creating UserContact object ..."); //NOI18N
536
537                                                 // Own entry
538                                                 contact = new UserContact();
539                                         } else {
540                                                 // Debug message
541                                                 this.getLogger().debug("Creating BookContact object ..."); //NOI18N
542
543                                                 // Other contact
544                                                 contact = new BookContact();
545                                         }
546                                         break;
547
548                                 case 1: // Gender
549                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
550
551                                         // Update data
552                                         contact.updateNameData(gender, null, null, null);
553                                         break;
554
555                                 case 2: // Surname
556                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
557                                         assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
558
559                                         // Update data
560                                         contact.updateNameData(gender, strippedToken, null, null);
561                                         break;
562
563                                 case 3: // Family name
564                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
565                                         assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
566
567                                         // Update data
568                                         contact.updateNameData(gender, null, strippedToken, null);
569                                         break;
570
571                                 case 4: // Company name
572                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
573                                         assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
574
575                                         // Update data
576                                         contact.updateNameData(gender, null, null, strippedToken);
577                                         break;
578
579                                 case 5: // Street number
580                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
581
582                                         // Update data
583                                         contact.updateAddressData(strippedToken, 0, null, null);
584                                         break;
585
586                                 case 6: // ZIP code
587                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
588
589                                         // Update data
590                                         contact.updateAddressData(null, num, null, null);
591                                         break;
592
593                                 case 7: // City name
594                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
595
596                                         // Update data
597                                         contact.updateAddressData(null, 0, strippedToken, null);
598                                         break;
599
600                                 case 8: // Country code
601                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
602
603                                         // Update data
604                                         contact.updateAddressData(null, 0, null, strippedToken);
605                                         break;
606
607                                 case 9: // Phone number
608                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
609
610                                         // Update data
611                                         contact.updateOtherData(strippedToken, null, null, null, null, null);
612                                         break;
613
614                                 case 10: // Fax number
615                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
616
617                                         // Update data
618                                         contact.updateOtherData(null, strippedToken, null, null, null, null);
619                                         break;
620
621                                 case 11: // Cellphone number
622                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
623
624                                         // Update data
625                                         contact.updateOtherData(null, null, strippedToken, null, null, null);
626                                         break;
627
628                                 case 12: // Email address
629                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
630
631                                         // Update data
632                                         contact.updateOtherData(null, null, null, strippedToken, null, null);
633                                         break;
634
635                                 case 13: // Birthday
636                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
637
638                                         // Update data
639                                         contact.updateOtherData(null, null, null, null, strippedToken, null);
640                                         break;
641
642                                 case 14: // Birthday
643                                         assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
644
645                                         // Update data
646                                         contact.updateOtherData(null, null, null, null, null, strippedToken);
647                                         break;
648
649                                 default: // New data entry
650                                         this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count)); //NOI18N
651                                         break;
652                         }
653
654                         // Increment counter for next round
655                         count++;
656                 }
657
658                 // Trace message
659                 this.getLogger().trace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
660
661                 // Return finished instance
662                 return contact;
663         }
664
665         /**
666          * Reads a line from file base
667          *
668          * @return Read line from file
669          */
670         private String readLine () {
671                 // Trace message
672                 this.getLogger().trace("CALLED!"); //NOI18N
673                 
674                 // Init input
675                 String input = null;
676                 
677                 try {
678                         // Read single line
679                         String base64 = this.getStorageFile().readLine();
680                         
681                         // Decode BASE-64
682                         byte[] decoded = Base64.getDecoder().decode(base64);
683                         
684                         // Convert to string
685                         input = new String(decoded);
686                 } catch (final IOException ex) {
687                         this.getLogger().catching(ex);
688                 }
689                 
690                 // Trace message
691                 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
692                 
693                 // Return read string or null
694                 return input;
695         }
696
697         /**
698          * Reads the database file, if available, and adds all read lines into the
699          * list.
700          *
701          * @return A list with Contact instances
702          */
703         private List<? extends Storeable> readList () throws BadTokenException {
704                 this.getLogger().trace("CALLED!"); //NOI18N
705
706                 // First rewind
707                 this.rewind();
708
709                 // Get file size and divide it by 140 (possible average length of one line)
710                 int lines = Math.round(this.length() / 140 + 0.5f);
711
712                 // Debug message
713                 this.getLogger().debug(MessageFormat.format("lines={0}", lines)); //NOI18N
714
715                 // Instance list
716                 // @TODO The maximum length could be guessed from file size?
717                 List<Storeable> list = new ArrayList<>(lines);
718
719                 // Init variables
720                 String line;
721                 Storeable instance = null;
722
723                 // Read all lines
724                 while (!this.isEndOfFile()) {
725                         // Then read a line
726                         line = this.readLine();
727
728                         // Parse line
729                         instance = (Storeable) this.parseLineToContact(line);
730
731                         // The contact instance should be there now
732                         assert (instance instanceof FrameworkInterface) : MessageFormat.format("instance is not set: {0}", instance); //NOI18N
733
734                         // Add contact
735                         this.addToList(instance, list);
736                 }
737
738                 // Return finished list
739                 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size())); //NOI18N
740                 return list;
741         }
742 }