2 * Copyright (C) 2015 Roland Haeder
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.
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.
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/>.
17 package org.mxchange.addressbook.database.backend.csv;
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;
38 * A database backend with CSV file as storage implementation
40 * @author Roland Haeder
42 public class CsvDatabaseBackend extends BaseDatabaseBackend implements CsvBackend {
45 * Output stream for this storage engine
47 private RandomAccessFile storageFile;
50 * Constructor with table name
52 * @param tableName Name of "table"
54 public CsvDatabaseBackend (final String tableName) {
56 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName));
58 // Set table name here, too
59 this.setTableName(tableName);
61 // Construct file name
62 String fileName = String.format("data/table_%s.csv", tableName);
65 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName));
68 // Try to initialize the storage (file instance)
69 this.storageFile = new RandomAccessFile(fileName, "rw");
70 } catch (final FileNotFoundException ex) {
72 this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString()));
77 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName));
81 * Gets an iterator for contacts
83 * @return Iterator for contacts
84 * @throws org.mxchange.addressbook.exceptions.BadTokenException If the
85 * underlaying method has found an invalid token
88 public Iterator<Contact> contactIterator () throws BadTokenException {
90 * Then read the file into RAM (yes, not perfect for >1000 entries ...)
91 * and get a List back.
93 List<Contact> list = this.readContactList();
95 // Get iterator from list and return it
96 return list.iterator();
100 * Shuts down this backend
103 public void doShutdown () {
106 this.getStorageFile().close();
107 } catch (final IOException ex) {
108 this.getLogger().catching(ex);
114 * Get length of underlaying file
116 * @return Length of underlaying file
119 public long length () {
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);
132 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length));
140 public void rewind () {
141 this.getLogger().trace("CALLED!");
144 // Rewind underlaying database file
145 this.getStorageFile().seek(0);
146 } catch (final IOException ex) {
147 this.getLogger().catching(ex);
151 this.getLogger().trace("EXIT!");
155 * Stores given object by "visiting" it
157 * @param object An object implementing Storeable
158 * @throws java.io.IOException From "inner" class
161 public void store (final Storeable object) throws IOException {
162 // Make sure the instance is there (DataOutput flawor)
163 assert (this.storageFile instanceof DataOutput);
165 // Try to cast it, this will fail if the interface is not implemented
166 StoreableCsv csv = (StoreableCsv) object;
168 // Now get a string from the object that needs to be stored
169 String str = csv.getCsvStringFromStoreableObject();
172 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str));
174 // The string is now a valid CSV string
175 this.getStorageFile().writeBytes(str);
179 * Adds given contact to list
181 * @param contact Contact instance to add
182 * @param list List instance
184 private void addContactToList (final Contact contact, final List<Contact> list) {
186 if (contact == null) {
188 throw new NullPointerException("contact is null");
189 } else if (list == null) {
191 throw new NullPointerException("list is null");
195 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
197 // Is the contact read?
198 if (contact instanceof Contact) {
200 boolean added = list.add(contact);
203 this.getLogger().debug(MessageFormat.format("contact={0} added={1}", contact, added));
205 // Has it been added?
208 this.getLogger().warn("Contact object has not been added.");
214 * Returns storage file
216 * @return Storage file instance
218 private RandomAccessFile getStorageFile () {
219 return this.storageFile;
223 * Checks whether end of file has been reached
225 * @return Whether lines are left to read
227 private boolean isEndOfFile () {
229 boolean isEof = true;
232 isEof = (this.getStorageFile().getFilePointer() >= this.length());
233 } catch (final IOException ex) {
234 // Length cannot be determined
235 this.getLogger().catching(ex);
239 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof));
244 * Reads the database file, if available, and adds all read lines into the
247 * @return A list with Contact instances
249 private List<Contact> readContactList () throws BadTokenException {
250 this.getLogger().trace("CALLED!");
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);
259 this.getLogger().debug(MessageFormat.format("lines={0}", lines));
262 // @TODO The maximum length could be guessed from file size?
263 List<Contact> list = new ArrayList<>(lines);
266 StringTokenizer tokenizer;
269 // Init A lot variables
272 Gender gender = null;
274 Contact contact = null;
277 while (!this.isEndOfFile()) {
279 line = this.readLine();
282 this.getLogger().debug(MessageFormat.format("line={0}", line));
285 // @TODO Move this into separate method
286 tokenizer = new StringTokenizer(line, ";");
292 // The tokens are now available, so get all
293 while (tokenizer.hasMoreElements()) {
299 String token = tokenizer.nextToken();
302 this.getLogger().debug(MessageFormat.format("token={0}", token));
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));
310 // All fine, so remove it
311 String strippedToken = token.substring(1, token.length() - 1);
313 // Is the string's content "null"?
314 if (strippedToken.equals("null")) {
316 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken));
318 // This needs to be set to null
319 strippedToken = null;
323 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken));
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?
329 num = Long.valueOf(strippedToken);
332 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken));
333 } catch (final NumberFormatException ex) {
334 // No number, then set default
339 // Now, let's try a boolean check, if no null
340 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) {
342 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken));
344 // parseBoolean() is relaxed, so no exceptions
345 bool = Boolean.valueOf(strippedToken);
349 this.getLogger().debug(MessageFormat.format("strippedToken={0},num={1},bool={2}", strippedToken, num, bool));
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));
357 this.getLogger().debug(MessageFormat.format("strippedToken={0},gender={1}", strippedToken, gender));
359 // This instance must be there
360 assert (gender instanceof Gender) : "gender is not set by Gender.fromChar(" + strippedToken + ")";
363 // Now it depends on the counter which position we need to check
365 case 0: // isOwnContact
366 assert ((bool instanceof Boolean));
369 this.getLogger().debug(MessageFormat.format("bool={0}", bool));
371 // Is it own contact?
374 this.getLogger().debug("Creating UserContact object ...");
377 contact = new UserContact();
380 this.getLogger().debug("Creating BookContact object ...");
383 contact = new BookContact();
388 assert (contact instanceof Contact) : "First token was not boolean";
391 contact.updateNameData(gender, null, null, null);
395 assert (contact instanceof Contact) : "First token was not boolean";
396 assert (gender instanceof Gender) : "gender instance is not set";
399 contact.updateNameData(gender, strippedToken, null, null);
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";
407 contact.updateNameData(gender, null, strippedToken, null);
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";
415 contact.updateNameData(gender, null, null, strippedToken);
418 case 5: // Street number
419 assert (contact instanceof Contact) : "First token was not boolean";
422 contact.updateAddressData(strippedToken, 0, null, null);
426 assert (contact instanceof Contact) : "First token was not boolean";
429 contact.updateAddressData(null, num, null, null);
433 assert (contact instanceof Contact) : "First token was not boolean";
436 contact.updateAddressData(null, 0, strippedToken, null);
439 case 8: // Country code
440 assert (contact instanceof Contact) : "First token was not boolean";
443 contact.updateAddressData(null, 0, null, strippedToken);
446 case 9: // Phone number
447 assert (contact instanceof Contact) : "First token was not boolean";
450 contact.updateOtherData(strippedToken, null, null, null, null, null);
453 case 10: // Fax number
454 assert (contact instanceof Contact) : "First token was not boolean";
457 contact.updateOtherData(null, strippedToken, null, null, null, null);
460 case 11: // Cellphone number
461 assert (contact instanceof Contact) : "First token was not boolean";
464 contact.updateOtherData(null, null, strippedToken, null, null, null);
467 case 12: // Email address
468 assert (contact instanceof Contact) : "First token was not boolean";
471 contact.updateOtherData(null, null, null, strippedToken, null, null);
475 assert (contact instanceof Contact) : "First token was not boolean";
478 contact.updateOtherData(null, null, null, null, strippedToken, null);
482 assert (contact instanceof Contact) : "First token was not boolean";
485 contact.updateOtherData(null, null, null, null, null, strippedToken);
488 default: // New data entry
489 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count));
493 // Increment counter for next round
497 // The contact instance should be there now
498 assert(contact instanceof Contact) : "contact is not set: " + contact;
501 this.addContactToList(contact, list);
504 // Return finished list
505 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size()));
510 * Reads a line from file base
512 * @return Read line from file
514 private String readLine () {
519 input = this.getStorageFile().readLine();
520 } catch (final IOException ex) {
521 this.getLogger().catching(ex);
524 // Return read string or null