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.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;
37 * A database backend with CSV file as storage implementation
39 * @author Roland Haeder
41 public class CsvDatabaseBackend extends BaseDatabaseBackend implements CsvBackend {
44 * Output stream for this storage engine
46 private RandomAccessFile storageFile;
49 * Constructor with table name
51 * @param tableName Name of "table"
53 public CsvDatabaseBackend (final String tableName) {
55 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName));
57 // Set table name here, too
58 this.setTableName(tableName);
60 // Construct file name
61 String fileName = String.format("data/table_%s.csv", tableName);
64 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName));
67 // Try to initialize the storage (file instance)
68 this.storageFile = new RandomAccessFile(fileName, "rw");
69 } catch (final FileNotFoundException ex) {
71 this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString()));
76 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName));
80 * Gets an iterator for contacts
82 * @return Iterator for contacts
83 * @throws org.mxchange.addressbook.exceptions.BadTokenException If the
84 * underlaying method has found an invalid token
87 public Iterator<Contact> contactIterator () throws BadTokenException {
89 * Then read the file into RAM (yes, not perfect for >1000 entries ...)
90 * and get a List back.
92 List<Contact> list = this.readContactList();
94 // Get iterator from list and return it
95 return list.iterator();
99 * Shuts down this backend
102 public void doShutdown () {
105 this.getStorageFile().close();
106 } catch (final IOException ex) {
107 this.getLogger().catching(ex);
113 * Get length of underlaying file
115 * @return Length of underlaying file
118 public long length () {
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);
131 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length));
139 public void rewind () {
140 this.getLogger().trace("CALLED!");
143 // Rewind underlaying database file
144 this.getStorageFile().seek(0);
145 } catch (final IOException ex) {
146 this.getLogger().catching(ex);
150 this.getLogger().trace("EXIT!");
154 * Stores given object by "visiting" it
156 * @param object An object implementing Storeable
157 * @throws java.io.IOException From "inner" class
160 public void store (final Storeable object) throws IOException {
161 // Make sure the instance is there (DataOutput flawor)
162 assert (this.storageFile instanceof DataOutput);
164 // Try to cast it, this will fail if the interface is not implemented
165 StoreableCsv csv = (StoreableCsv) object;
167 // Now get a string from the object that needs to be stored
168 String str = csv.getCsvStringFromStoreableObject();
171 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str));
173 // The string is now a valid CSV string
174 this.getStorageFile().writeBytes(str);
178 * Adds given contact to list
180 * @param contact Contact instance to add
181 * @param list List instance
183 private void addContactToList (final Contact contact, final List<Contact> list) {
185 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
187 // Is the contact read?
188 if (contact instanceof Contact) {
190 boolean added = list.add(contact);
193 this.getLogger().debug(MessageFormat.format("contact={0} added={1}", contact, added));
195 // Has it been added?
198 this.getLogger().warn("Contact object has not been added.");
204 * Returns storage file
206 * @return Storage file instance
208 private RandomAccessFile getStorageFile () {
209 return this.storageFile;
213 * Checks whether end of file has been reached
215 * @return Whether lines are left to read
217 private boolean isEndOfFile () {
219 boolean isEof = true;
222 isEof = (this.getStorageFile().getFilePointer() >= this.length());
223 } catch (final IOException ex) {
224 // Length cannot be determined
225 this.getLogger().catching(ex);
229 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof));
234 * Reads the database file, if available, and adds all read lines into the
237 * @return A list with Contact instances
239 private List<Contact> readContactList () throws BadTokenException {
240 this.getLogger().trace("CALLED!");
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);
249 this.getLogger().debug(MessageFormat.format("lines={0}", lines));
252 // @TODO The maximum length could be guessed from file size?
253 List<Contact> list = new ArrayList<>(lines);
256 StringTokenizer tokenizer;
260 while (!this.isEndOfFile()) {
262 line = this.readLine();
265 this.getLogger().debug(MessageFormat.format("line={0}", line));
268 // @TODO Move this into separate method
269 tokenizer = new StringTokenizer(line, ";");
274 // Init contact object
275 Contact contact = null;
277 // The tokens are now available, so get all
278 while (tokenizer.hasMoreElements()) {
280 String token = tokenizer.nextToken();
283 this.getLogger().debug(MessageFormat.format("token={0}", token));
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));
291 // All fine, so remove it
292 String strippedToken = token.substring(1, token.length() - 1);
294 // Is the string's content "null"?
295 if (strippedToken.equals("null")) {
297 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken));
299 // This needs to be set to null
300 strippedToken = null;
304 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken));
306 // Init number/string data values
307 String strData = strippedToken;
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?
316 num = Long.valueOf(strippedToken);
319 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken));
320 } catch (final NumberFormatException ex) {
321 // No number, then set default
326 // Now, let's try a boolean check, if no null
327 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) {
329 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken));
331 // parseBoolean() is relaxed, so no exceptions
332 bool = Boolean.valueOf(strippedToken);
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);
341 // Now it depends on the counter which position we need to check
343 case 0: // isOwnContact
344 assert ((bool instanceof Boolean));
347 this.getLogger().debug(MessageFormat.format("bool={0}", bool));
349 // Is it own contact?
352 this.getLogger().debug("Creating UserContact object ...");
355 contact = new UserContact();
358 this.getLogger().debug("Creating BookContact object ...");
361 contact = new BookContact();
366 assert (contact instanceof Contact) : "First token was not boolean";
367 assert (gender != '?') : "Gender is not detected.";
370 contact.updateNameData(gender, null, null, null);
374 assert (contact instanceof Contact) : "First token was not boolean";
375 assert (gender != '?') : "Gender is not detected.";
378 contact.updateNameData(gender, strippedToken, null, null);
381 case 3: // Family name
382 assert (contact instanceof Contact) : "First token was not boolean";
383 assert (gender != '?') : "Gender is not detected.";
386 contact.updateNameData(gender, null, strippedToken, null);
389 case 4: // Company name
390 assert (contact instanceof Contact) : "First token was not boolean";
391 assert (gender != '?') : "Gender is not detected.";
394 contact.updateNameData(gender, null, null, strippedToken);
397 case 5: // Street number
398 assert (contact instanceof Contact) : "First token was not boolean";
401 contact.updateAddressData(strippedToken, 0, null, null);
405 assert (contact instanceof Contact) : "First token was not boolean";
408 contact.updateAddressData(null, num, null, null);
412 assert (contact instanceof Contact) : "First token was not boolean";
415 contact.updateAddressData(null, 0, strippedToken, null);
418 case 8: // Country code
419 assert (contact instanceof Contact) : "First token was not boolean";
422 contact.updateAddressData(null, 0, null, strippedToken);
425 case 9: // Phone number
426 assert (contact instanceof Contact) : "First token was not boolean";
429 contact.updateOtherData(strippedToken, null, null, null, null, null);
432 case 10: // Fax number
433 assert (contact instanceof Contact) : "First token was not boolean";
436 contact.updateOtherData(null, strippedToken, null, null, null, null);
439 case 11: // Cellphone number
440 assert (contact instanceof Contact) : "First token was not boolean";
443 contact.updateOtherData(null, null, strippedToken, null, null, null);
446 case 12: // Email address
447 assert (contact instanceof Contact) : "First token was not boolean";
450 contact.updateOtherData(null, null, null, strippedToken, null, null);
454 assert (contact instanceof Contact) : "First token was not boolean";
457 contact.updateOtherData(null, null, null, null, strippedToken, null);
461 assert (contact instanceof Contact) : "First token was not boolean";
464 contact.updateOtherData(null, null, null, null, null, strippedToken);
467 default: // New data entry
468 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count));
472 // Increment counter for next round
477 this.addContactToList(contact, list);
480 // Return finished list
481 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size()));
486 * Reads a line from file base
488 * @return Read line from file
490 private String readLine () {
495 input = this.getStorageFile().readLine();
496 } catch (final IOException ex) {
497 this.getLogger().catching(ex);
500 // Return read string or null