]> git.mxchange.org Git - addressbook-swing.git/blob - Addressbook/src/org/mxchange/addressbook/database/backend/csv/CsvDatabaseBackend.java
Now much easier to handle
[addressbook-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                 // Debug message
186                 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
187
188                 // Is the contact read?
189                 if (contact instanceof Contact) {
190                         // Then add it
191                         boolean added = list.add(contact);
192
193                         // Debug message
194                         this.getLogger().debug(MessageFormat.format("contact={0} added={1}", contact, added));
195
196                         // Has it been added?
197                         if (!added) {
198                                 // Not added
199                                 this.getLogger().warn("Contact object has not been added.");
200                         }
201                 }
202         }
203
204         /**
205          * Returns storage file
206          *
207          * @return Storage file instance
208          */
209         private RandomAccessFile getStorageFile () {
210                 return this.storageFile;
211         }
212
213         /**
214          * Checks whether end of file has been reached
215          *
216          * @return Whether lines are left to read
217          */
218         private boolean isEndOfFile () {
219                 // Default is EOF
220                 boolean isEof = true;
221
222                 try {
223                         isEof = (this.getStorageFile().getFilePointer() >= this.length());
224                 } catch (final IOException ex) {
225                         // Length cannot be determined
226                         this.getLogger().catching(ex);
227                 }
228
229                 // Return status
230                 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof));
231                 return isEof;
232         }
233
234         /**
235          * Reads the database file, if available, and adds all read lines into the
236          * list.
237          *
238          * @return A list with Contact instances
239          */
240         private List<Contact> readContactList () throws BadTokenException {
241                 this.getLogger().trace("CALLED!");
242
243                 // First rewind
244                 this.rewind();
245
246                 // Get file size and divide it by 140 (possible average length of one line)
247                 int lines = Math.round(this.length() / 140 + 0.5f);
248
249                 // Debug message
250                 this.getLogger().debug(MessageFormat.format("lines={0}", lines));
251
252         // Instance list
253                 // @TODO The maximum length could be guessed from file size?
254                 List<Contact> list = new ArrayList<>(lines);
255
256                 // Init variables
257                 StringTokenizer tokenizer;
258                 String line;
259
260                 // Read all lines
261                 while (!this.isEndOfFile()) {
262                         // Then read a line
263                         line = this.readLine();
264
265                         // Debug message
266                         this.getLogger().debug(MessageFormat.format("line={0}", line));
267
268             // Then tokenize it
269                         // @TODO Move this into separate method
270                         tokenizer = new StringTokenizer(line, ";");
271
272                         // Count round
273                         int count = 0;
274
275                         // Init contact object
276                         Contact contact = null;
277
278                         // The tokens are now available, so get all
279                         while (tokenizer.hasMoreElements()) {
280                                 // Get next token
281                                 String token = tokenizer.nextToken();
282
283                                 // Debug message
284                                 this.getLogger().debug(MessageFormat.format("token={0}", token));
285
286                                 // Verify token, it must have double-quotes on each side
287                                 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) {
288                                         // Something bad was read
289                                         throw new BadTokenException(MessageFormat.format("Token {0} has not double-quotes on both ends.", token));
290                                 }
291
292                                 // All fine, so remove it
293                                 String strippedToken = token.substring(1, token.length() - 1);
294
295                                 // Is the string's content "null"?
296                                 if (strippedToken.equals("null")) {
297                                         // Debug message
298                                         this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken));
299
300                                         // This needs to be set to null
301                                         strippedToken = null;
302                                 }
303
304                                 // Debug message
305                                 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken));
306
307                                 // Init number/string data values
308                                 String strData = strippedToken;
309                                 Long num = null;
310                                 Boolean bool = null;
311                                 Gender gender = null;
312
313                                 // Now, let's try a number check, if no null
314                                 if (strippedToken != null) {
315                                         // Okay, no null, maybe the string bears a decimal number?
316                                         try {
317                                                 num = Long.valueOf(strippedToken);
318
319                                                 // Debug message
320                                                 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken));
321                                         } catch (final NumberFormatException ex) {
322                                                 // No number, then set default
323                                                 num = null;
324                                         }
325                                 }
326
327                                 // Now, let's try a boolean check, if no null
328                                 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) {
329                                         // Debug message
330                                         this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken));
331
332                                         // parseBoolean() is relaxed, so no exceptions
333                                         bool = Boolean.valueOf(strippedToken);
334                                 }
335
336                                 // Now, let's try a boolean check, if no null
337                                 if ((strippedToken != null) && (num == null) && (bool == null) && ((strippedToken.equals("M")) || (strippedToken.equals("F")) || (strippedToken.equals("C")))) {
338                                         // Get first character
339                                         gender = Gender.fromChar(strippedToken.charAt(0));
340                                 }
341
342                                 // Now it depends on the counter which position we need to check
343                                 switch (count) {
344                                         case 0: // isOwnContact
345                                                 assert ((bool instanceof Boolean));
346
347                                                 // Debug message
348                                                 this.getLogger().debug(MessageFormat.format("bool={0}", bool));
349
350                                                 // Is it own contact?
351                                                 if (true == bool) {
352                                                         // Debug message
353                                                         this.getLogger().debug("Creating UserContact object ...");
354
355                                                         // Own entry
356                                                         contact = new UserContact();
357                                                 } else {
358                                                         // Debug message
359                                                         this.getLogger().debug("Creating BookContact object ...");
360
361                                                         // Other contact
362                                                         contact = new BookContact();
363                                                 }
364                                                 break;
365
366                                         case 1: // Gender
367                                                 assert (contact instanceof Contact) : "First token was not boolean";
368
369                                                 // Update data
370                                                 contact.updateNameData(gender, null, null, null);
371                                                 break;
372
373                                         case 2: // Surname
374                                                 assert (contact instanceof Contact) : "First token was not boolean";
375
376                                                 // Update data
377                                                 contact.updateNameData(gender, strippedToken, null, null);
378                                                 break;
379
380                                         case 3: // Family name
381                                                 assert (contact instanceof Contact) : "First token was not boolean";
382
383                                                 // Update data
384                                                 contact.updateNameData(gender, null, strippedToken, null);
385                                                 break;
386
387                                         case 4: // Company name
388                                                 assert (contact instanceof Contact) : "First token was not boolean";
389
390                                                 // Update data
391                                                 contact.updateNameData(gender, null, null, strippedToken);
392                                                 break;
393
394                                         case 5: // Street number
395                                                 assert (contact instanceof Contact) : "First token was not boolean";
396
397                                                 // Update data
398                                                 contact.updateAddressData(strippedToken, 0, null, null);
399                                                 break;
400
401                                         case 6: // ZIP code
402                                                 assert (contact instanceof Contact) : "First token was not boolean";
403
404                                                 // Update data
405                                                 contact.updateAddressData(null, num, null, null);
406                                                 break;
407
408                                         case 7: // City name
409                                                 assert (contact instanceof Contact) : "First token was not boolean";
410
411                                                 // Update data
412                                                 contact.updateAddressData(null, 0, strippedToken, null);
413                                                 break;
414
415                                         case 8: // Country code
416                                                 assert (contact instanceof Contact) : "First token was not boolean";
417
418                                                 // Update data
419                                                 contact.updateAddressData(null, 0, null, strippedToken);
420                                                 break;
421
422                                         case 9: // Phone number
423                                                 assert (contact instanceof Contact) : "First token was not boolean";
424
425                                                 // Update data
426                                                 contact.updateOtherData(strippedToken, null, null, null, null, null);
427                                                 break;
428
429                                         case 10: // Fax number
430                                                 assert (contact instanceof Contact) : "First token was not boolean";
431
432                                                 // Update data
433                                                 contact.updateOtherData(null, strippedToken, null, null, null, null);
434                                                 break;
435
436                                         case 11: // Cellphone number
437                                                 assert (contact instanceof Contact) : "First token was not boolean";
438
439                                                 // Update data
440                                                 contact.updateOtherData(null, null, strippedToken, null, null, null);
441                                                 break;
442
443                                         case 12: // Email address
444                                                 assert (contact instanceof Contact) : "First token was not boolean";
445
446                                                 // Update data
447                                                 contact.updateOtherData(null, null, null, strippedToken, null, null);
448                                                 break;
449
450                                         case 13: // Birthday
451                                                 assert (contact instanceof Contact) : "First token was not boolean";
452
453                                                 // Update data
454                                                 contact.updateOtherData(null, null, null, null, strippedToken, null);
455                                                 break;
456
457                                         case 14: // Birthday
458                                                 assert (contact instanceof Contact) : "First token was not boolean";
459
460                                                 // Update data
461                                                 contact.updateOtherData(null, null, null, null, null, strippedToken);
462                                                 break;
463
464                                         default: // New data entry
465                                                 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count));
466                                                 break;
467                                 }
468
469                                 // Increment counter for next round
470                                 count++;
471                         }
472
473                         // Add contact
474                         this.addContactToList(contact, list);
475                 }
476
477                 // Return finished list
478                 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size()));
479                 return list;
480         }
481
482         /**
483          * Reads a line from file base
484          *
485          * @return Read line from file
486          */
487         private String readLine () {
488                 // Init input
489                 String input = null;
490
491                 try {
492                         input = this.getStorageFile().readLine();
493                 } catch (final IOException ex) {
494                         this.getLogger().catching(ex);
495                 }
496
497                 // Return read string or null
498                 return input;
499         }
500 }