]> git.mxchange.org Git - jfinancials-swing.git/blob - Addressbook/src/org/mxchange/addressbook/database/backend/csv/CsvDatabaseBackend.java
b09fe8fed8648f6a72e3003497805e2d5007c31c
[jfinancials-swing.git] / Addressbook / src / org / mxchange / addressbook / database / backend / csv / CsvDatabaseBackend.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.text.MessageFormat;
24 import java.util.ArrayList;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.StringTokenizer;
28 import org.mxchange.addressbook.contact.Contact;
29 import org.mxchange.addressbook.contact.Gender;
30 import org.mxchange.addressbook.contact.book.BookContact;
31 import org.mxchange.addressbook.contact.user.UserContact;
32 import org.mxchange.addressbook.database.backend.BaseDatabaseBackend;
33 import org.mxchange.addressbook.database.storage.Storeable;
34 import org.mxchange.addressbook.database.storage.csv.StoreableCsv;
35 import org.mxchange.addressbook.exceptions.BadTokenException;
36
37 /**
38  * A database backend with CSV file as storage implementation
39  *
40  * @author Roland Haeder
41  */
42 public class CsvDatabaseBackend extends BaseDatabaseBackend implements CsvBackend {
43
44         /**
45          * Output stream for this storage engine
46          */
47         private RandomAccessFile storageFile;
48
49         /**
50          * Constructor with table name
51          *
52          * @param tableName Name of "table"
53          */
54         public CsvDatabaseBackend (final String tableName) {
55                 // Debug message
56                 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName));
57
58                 // Set table name here, too
59                 this.setTableName(tableName);
60
61                 // Construct file name
62                 String fileName = String.format("data/table_%s.csv", tableName);
63
64                 // Debug message
65                 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName));
66
67                 try {
68                         // Try to initialize the storage (file instance)
69                         this.storageFile = new RandomAccessFile(fileName, "rw");
70                 } catch (final FileNotFoundException ex) {
71                         // Did not work
72                         this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString()));
73                         System.exit(1);
74                 }
75
76                 // Output message
77                 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName));
78         }
79
80         /**
81          * Gets an iterator for contacts
82          *
83          * @return Iterator for contacts
84          * @throws org.mxchange.addressbook.exceptions.BadTokenException If the
85          * underlaying method has found an invalid token
86          */
87         @Override
88         public Iterator<Contact> contactIterator () throws BadTokenException {
89                 /*
90                  * Then read the file into RAM (yes, not perfect for >1000 entries ...)
91                  * and get a List back.
92                  */
93                 List<Contact> list = this.readContactList();
94
95                 // Get iterator from list and return it
96                 return list.iterator();
97         }
98
99         /**
100          * Shuts down this backend
101          */
102         @Override
103         public void doShutdown () {
104                 try {
105                         // Close file
106                         this.getStorageFile().close();
107                 } catch (final IOException ex) {
108                         this.getLogger().catching(ex);
109                         System.exit(1);
110                 }
111         }
112
113         /**
114          * Get length of underlaying file
115          *
116          * @return Length of underlaying file
117          */
118         @Override
119         public long length () {
120                 long length = 0;
121
122                 try {
123                         length = this.getStorageFile().length();
124                         this.getLogger().debug(MessageFormat.format("length={0}", length));
125                 } catch (final IOException ex) {
126                         // Length cannot be determined
127                         this.getLogger().catching(ex);
128                         System.exit(1);
129                 }
130
131                 // Return result
132                 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length));
133                 return length;
134         }
135
136         /**
137          * Rewinds backend
138          */
139         @Override
140         public void rewind () {
141                 this.getLogger().trace("CALLED!");
142
143                 try {
144                         // Rewind underlaying database file
145                         this.getStorageFile().seek(0);
146                 } catch (final IOException ex) {
147                         this.getLogger().catching(ex);
148                         System.exit(1);
149                 }
150
151                 this.getLogger().trace("EXIT!");
152         }
153
154         /**
155          * Stores given object by "visiting" it
156          *
157          * @param object An object implementing Storeable
158          * @throws java.io.IOException From "inner" class
159          */
160         @Override
161         public void store (final Storeable object) throws IOException {
162                 // Make sure the instance is there (DataOutput flawor)
163                 assert (this.storageFile instanceof DataOutput);
164
165                 // Try to cast it, this will fail if the interface is not implemented
166                 StoreableCsv csv = (StoreableCsv) object;
167
168                 // Now get a string from the object that needs to be stored
169                 String str = csv.getCsvStringFromStoreableObject();
170
171                 // Debug message
172                 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str));
173
174                 // The string is now a valid CSV string
175                 this.getStorageFile().writeBytes(str);
176         }
177
178         /**
179          * Adds given contact to list
180          *
181          * @param contact Contact instance to add
182          * @param list List instance
183          */
184         private void addContactToList (final Contact contact, final List<Contact> list) {
185                 // No null here
186                 if (contact == null) {
187                         // Throw exception
188                         throw new NullPointerException("contact is null");
189                 } else if (list == null) {
190                         // Throw exception
191                         throw new NullPointerException("list is null");
192                 }
193
194                 // Debug message
195                 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
196
197                 // Is the contact read?
198                 if (contact instanceof Contact) {
199                         // Then add it
200                         boolean added = list.add(contact);
201
202                         // Debug message
203                         this.getLogger().debug(MessageFormat.format("contact={0} added={1}", contact, added));
204
205                         // Has it been added?
206                         if (!added) {
207                                 // Not added
208                                 this.getLogger().warn("Contact object has not been added.");
209                         }
210                 }
211         }
212
213         /**
214          * Returns storage file
215          *
216          * @return Storage file instance
217          */
218         private RandomAccessFile getStorageFile () {
219                 return this.storageFile;
220         }
221
222         /**
223          * Checks whether end of file has been reached
224          *
225          * @return Whether lines are left to read
226          */
227         private boolean isEndOfFile () {
228                 // Default is EOF
229                 boolean isEof = true;
230
231                 try {
232                         isEof = (this.getStorageFile().getFilePointer() >= this.length());
233                 } catch (final IOException ex) {
234                         // Length cannot be determined
235                         this.getLogger().catching(ex);
236                 }
237
238                 // Return status
239                 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof));
240                 return isEof;
241         }
242
243         /**
244          * Reads the database file, if available, and adds all read lines into the
245          * list.
246          *
247          * @return A list with Contact instances
248          */
249         private List<Contact> readContactList () throws BadTokenException {
250                 this.getLogger().trace("CALLED!");
251
252                 // First rewind
253                 this.rewind();
254
255                 // Get file size and divide it by 140 (possible average length of one line)
256                 int lines = Math.round(this.length() / 140 + 0.5f);
257
258                 // Debug message
259                 this.getLogger().debug(MessageFormat.format("lines={0}", lines));
260
261         // Instance list
262                 // @TODO The maximum length could be guessed from file size?
263                 List<Contact> list = new ArrayList<>(lines);
264
265                 // Init variables
266                 StringTokenizer tokenizer;
267                 String line;
268
269                 // Init A lot variables
270                 Long num = null;
271                 Boolean bool = null;
272                 Gender gender = null;
273                 int count = 0;
274                 Contact contact = null;
275
276                 // Read all lines
277                 while (!this.isEndOfFile()) {
278                         // Then read a line
279                         line = this.readLine();
280
281                         // Debug message
282                         this.getLogger().debug(MessageFormat.format("line={0}", line));
283
284                         // Then tokenize it
285                         // @TODO Move this into separate method
286                         tokenizer = new StringTokenizer(line, ";");
287
288                         // Reset variables
289                         count = 0;
290                         contact = null;
291
292                         // The tokens are now available, so get all
293                         while (tokenizer.hasMoreElements()) {
294                                 // Reset variables
295                                 num = null;
296                                 bool = null;
297
298                                 // Get next token
299                                 String token = tokenizer.nextToken();
300
301                                 // Debug message
302                                 this.getLogger().debug(MessageFormat.format("token={0}", token));
303
304                                 // Verify token, it must have double-quotes on each side
305                                 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) {
306                                         // Something bad was read
307                                         throw new BadTokenException(MessageFormat.format("Token {0} has not double-quotes on both ends.", token));
308                                 }
309
310                                 // All fine, so remove it
311                                 String strippedToken = token.substring(1, token.length() - 1);
312
313                                 // Is the string's content "null"?
314                                 if (strippedToken.equals("null")) {
315                                         // Debug message
316                                         this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken));
317
318                                         // This needs to be set to null
319                                         strippedToken = null;
320                                 }
321
322                                 // Debug message
323                                 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken));
324
325                                 // Now, let's try a number check, if no null
326                                 if (strippedToken != null) {
327                                         // Okay, no null, maybe the string bears a decimal number?
328                                         try {
329                                                 num = Long.valueOf(strippedToken);
330
331                                                 // Debug message
332                                                 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken));
333                                         } catch (final NumberFormatException ex) {
334                                                 // No number, then set default
335                                                 num = null;
336                                         }
337                                 }
338
339                                 // Now, let's try a boolean check, if no null
340                                 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) {
341                                         // Debug message
342                                         this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken));
343
344                                         // parseBoolean() is relaxed, so no exceptions
345                                         bool = Boolean.valueOf(strippedToken);
346                                 }
347
348                                 // Debug message
349                                 this.getLogger().debug(MessageFormat.format("strippedToken={0},num={1},bool={2}", strippedToken, num, bool));
350
351                                 // Now, let's try a gender check, if no null
352                                 if ((strippedToken != null) && (num == null) && (bool == null) && ((strippedToken.equals("M")) || (strippedToken.equals("F")) || (strippedToken.equals("C")))) {
353                                         // Get first character
354                                         gender = Gender.fromChar(strippedToken.charAt(0));
355
356                                         // Debug message
357                                         this.getLogger().debug(MessageFormat.format("strippedToken={0},gender={1}", strippedToken, gender));
358
359                                         // This instance must be there
360                                         assert (gender instanceof Gender) : "gender is not set by Gender.fromChar(" + strippedToken + ")";
361                                 }
362
363                                 // Now it depends on the counter which position we need to check
364                                 switch (count) {
365                                         case 0: // isOwnContact
366                                                 assert ((bool instanceof Boolean));
367
368                                                 // Debug message
369                                                 this.getLogger().debug(MessageFormat.format("bool={0}", bool));
370
371                                                 // Is it own contact?
372                                                 if (true == bool) {
373                                                         // Debug message
374                                                         this.getLogger().debug("Creating UserContact object ...");
375
376                                                         // Own entry
377                                                         contact = new UserContact();
378                                                 } else {
379                                                         // Debug message
380                                                         this.getLogger().debug("Creating BookContact object ...");
381
382                                                         // Other contact
383                                                         contact = new BookContact();
384                                                 }
385                                                 break;
386
387                                         case 1: // Gender
388                                                 assert (contact instanceof Contact) : "First token was not boolean";
389
390                                                 // Update data
391                                                 contact.updateNameData(gender, null, null, null);
392                                                 break;
393
394                                         case 2: // Surname
395                                                 assert (contact instanceof Contact) : "First token was not boolean";
396                                                 assert (gender instanceof Gender) : "gender instance is not set";
397
398                                                 // Update data
399                                                 contact.updateNameData(gender, strippedToken, null, null);
400                                                 break;
401
402                                         case 3: // Family name
403                                                 assert (contact instanceof Contact) : "First token was not boolean";
404                                                 assert (gender instanceof Gender) : "gender instance is not set";
405
406                                                 // Update data
407                                                 contact.updateNameData(gender, null, strippedToken, null);
408                                                 break;
409
410                                         case 4: // Company name
411                                                 assert (contact instanceof Contact) : "First token was not boolean";
412                                                 assert (gender instanceof Gender) : "gender instance is not set";
413
414                                                 // Update data
415                                                 contact.updateNameData(gender, null, null, strippedToken);
416                                                 break;
417
418                                         case 5: // Street number
419                                                 assert (contact instanceof Contact) : "First token was not boolean";
420
421                                                 // Update data
422                                                 contact.updateAddressData(strippedToken, 0, null, null);
423                                                 break;
424
425                                         case 6: // ZIP code
426                                                 assert (contact instanceof Contact) : "First token was not boolean";
427
428                                                 // Update data
429                                                 contact.updateAddressData(null, num, null, null);
430                                                 break;
431
432                                         case 7: // City name
433                                                 assert (contact instanceof Contact) : "First token was not boolean";
434
435                                                 // Update data
436                                                 contact.updateAddressData(null, 0, strippedToken, null);
437                                                 break;
438
439                                         case 8: // Country code
440                                                 assert (contact instanceof Contact) : "First token was not boolean";
441
442                                                 // Update data
443                                                 contact.updateAddressData(null, 0, null, strippedToken);
444                                                 break;
445
446                                         case 9: // Phone number
447                                                 assert (contact instanceof Contact) : "First token was not boolean";
448
449                                                 // Update data
450                                                 contact.updateOtherData(strippedToken, null, null, null, null, null);
451                                                 break;
452
453                                         case 10: // Fax number
454                                                 assert (contact instanceof Contact) : "First token was not boolean";
455
456                                                 // Update data
457                                                 contact.updateOtherData(null, strippedToken, null, null, null, null);
458                                                 break;
459
460                                         case 11: // Cellphone number
461                                                 assert (contact instanceof Contact) : "First token was not boolean";
462
463                                                 // Update data
464                                                 contact.updateOtherData(null, null, strippedToken, null, null, null);
465                                                 break;
466
467                                         case 12: // Email address
468                                                 assert (contact instanceof Contact) : "First token was not boolean";
469
470                                                 // Update data
471                                                 contact.updateOtherData(null, null, null, strippedToken, null, null);
472                                                 break;
473
474                                         case 13: // Birthday
475                                                 assert (contact instanceof Contact) : "First token was not boolean";
476
477                                                 // Update data
478                                                 contact.updateOtherData(null, null, null, null, strippedToken, null);
479                                                 break;
480
481                                         case 14: // Birthday
482                                                 assert (contact instanceof Contact) : "First token was not boolean";
483
484                                                 // Update data
485                                                 contact.updateOtherData(null, null, null, null, null, strippedToken);
486                                                 break;
487
488                                         default: // New data entry
489                                                 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count));
490                                                 break;
491                                 }
492
493                                 // Increment counter for next round
494                                 count++;
495                         }
496
497                         // The contact instance should be there now
498                         assert(contact instanceof Contact) : "contact is not set: " + contact;
499
500                         // Add contact
501                         this.addContactToList(contact, list);
502                 }
503
504                 // Return finished list
505                 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size()));
506                 return list;
507         }
508
509         /**
510          * Reads a line from file base
511          *
512          * @return Read line from file
513          */
514         private String readLine () {
515                 // Init input
516                 String input = null;
517
518                 try {
519                         input = this.getStorageFile().readLine();
520                 } catch (final IOException ex) {
521                         this.getLogger().catching(ex);
522                 }
523
524                 // Return read string or null
525                 return input;
526         }
527 }