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