]> git.mxchange.org Git - addressbook-swing.git/blob - Addressbook/src/org/mxchange/addressbook/database/backend/csv/CsvDatabaseBackend.java
Introduced Gender enum which replaces the old char
[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 = strippedToken.charAt(0);
340                                         throw new UnsupportedOperationException("Gender dection is unifnished!");
341                                 }
342
343                                 // Now it depends on the counter which position we need to check
344                                 switch (count) {
345                                         case 0: // isOwnContact
346                                                 assert ((bool instanceof Boolean));
347
348                                                 // Debug message
349                                                 this.getLogger().debug(MessageFormat.format("bool={0}", bool));
350
351                                                 // Is it own contact?
352                                                 if (true == bool) {
353                                                         // Debug message
354                                                         this.getLogger().debug("Creating UserContact object ...");
355
356                                                         // Own entry
357                                                         contact = new UserContact();
358                                                 } else {
359                                                         // Debug message
360                                                         this.getLogger().debug("Creating BookContact object ...");
361
362                                                         // Other contact
363                                                         contact = new BookContact();
364                                                 }
365                                                 break;
366
367                                         case 1: // Gender
368                                                 assert (contact instanceof Contact) : "First token was not boolean";
369
370                                                 // Update data
371                                                 contact.updateNameData(gender, null, null, null);
372                                                 break;
373
374                                         case 2: // Surname
375                                                 assert (contact instanceof Contact) : "First token was not boolean";
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
384                                                 // Update data
385                                                 contact.updateNameData(gender, null, strippedToken, null);
386                                                 break;
387
388                                         case 4: // Company name
389                                                 assert (contact instanceof Contact) : "First token was not boolean";
390
391                                                 // Update data
392                                                 contact.updateNameData(gender, null, null, strippedToken);
393                                                 break;
394
395                                         case 5: // Street number
396                                                 assert (contact instanceof Contact) : "First token was not boolean";
397
398                                                 // Update data
399                                                 contact.updateAddressData(strippedToken, 0, null, null);
400                                                 break;
401
402                                         case 6: // ZIP code
403                                                 assert (contact instanceof Contact) : "First token was not boolean";
404
405                                                 // Update data
406                                                 contact.updateAddressData(null, num, null, null);
407                                                 break;
408
409                                         case 7: // City name
410                                                 assert (contact instanceof Contact) : "First token was not boolean";
411
412                                                 // Update data
413                                                 contact.updateAddressData(null, 0, strippedToken, null);
414                                                 break;
415
416                                         case 8: // Country code
417                                                 assert (contact instanceof Contact) : "First token was not boolean";
418
419                                                 // Update data
420                                                 contact.updateAddressData(null, 0, null, strippedToken);
421                                                 break;
422
423                                         case 9: // Phone number
424                                                 assert (contact instanceof Contact) : "First token was not boolean";
425
426                                                 // Update data
427                                                 contact.updateOtherData(strippedToken, null, null, null, null, null);
428                                                 break;
429
430                                         case 10: // Fax number
431                                                 assert (contact instanceof Contact) : "First token was not boolean";
432
433                                                 // Update data
434                                                 contact.updateOtherData(null, strippedToken, null, null, null, null);
435                                                 break;
436
437                                         case 11: // Cellphone number
438                                                 assert (contact instanceof Contact) : "First token was not boolean";
439
440                                                 // Update data
441                                                 contact.updateOtherData(null, null, strippedToken, null, null, null);
442                                                 break;
443
444                                         case 12: // Email address
445                                                 assert (contact instanceof Contact) : "First token was not boolean";
446
447                                                 // Update data
448                                                 contact.updateOtherData(null, null, null, strippedToken, null, null);
449                                                 break;
450
451                                         case 13: // Birthday
452                                                 assert (contact instanceof Contact) : "First token was not boolean";
453
454                                                 // Update data
455                                                 contact.updateOtherData(null, null, null, null, strippedToken, null);
456                                                 break;
457
458                                         case 14: // Birthday
459                                                 assert (contact instanceof Contact) : "First token was not boolean";
460
461                                                 // Update data
462                                                 contact.updateOtherData(null, null, null, null, null, strippedToken);
463                                                 break;
464
465                                         default: // New data entry
466                                                 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count));
467                                                 break;
468                                 }
469
470                                 // Increment counter for next round
471                                 count++;
472                         }
473
474                         // Add contact
475                         this.addContactToList(contact, list);
476                 }
477
478                 // Return finished list
479                 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size()));
480                 return list;
481         }
482
483         /**
484          * Reads a line from file base
485          *
486          * @return Read line from file
487          */
488         private String readLine () {
489                 // Init input
490                 String input = null;
491
492                 try {
493                         input = this.getStorageFile().readLine();
494                 } catch (final IOException ex) {
495                         this.getLogger().catching(ex);
496                 }
497
498                 // Return read string or null
499                 return input;
500         }
501 }