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