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 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
188 // Is the contact read?
189 if (contact instanceof Contact) {
191 boolean added = list.add(contact);
194 this.getLogger().debug(MessageFormat.format("contact={0} added={1}", contact, added));
196 // Has it been added?
199 this.getLogger().warn("Contact object has not been added.");
205 * Returns storage file
207 * @return Storage file instance
209 private RandomAccessFile getStorageFile () {
210 return this.storageFile;
214 * Checks whether end of file has been reached
216 * @return Whether lines are left to read
218 private boolean isEndOfFile () {
220 boolean isEof = true;
223 isEof = (this.getStorageFile().getFilePointer() >= this.length());
224 } catch (final IOException ex) {
225 // Length cannot be determined
226 this.getLogger().catching(ex);
230 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof));
235 * Reads the database file, if available, and adds all read lines into the
238 * @return A list with Contact instances
240 private List<Contact> readContactList () throws BadTokenException {
241 this.getLogger().trace("CALLED!");
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);
250 this.getLogger().debug(MessageFormat.format("lines={0}", lines));
253 // @TODO The maximum length could be guessed from file size?
254 List<Contact> list = new ArrayList<>(lines);
257 StringTokenizer tokenizer;
261 while (!this.isEndOfFile()) {
263 line = this.readLine();
266 this.getLogger().debug(MessageFormat.format("line={0}", line));
269 // @TODO Move this into separate method
270 tokenizer = new StringTokenizer(line, ";");
275 // Init contact object
276 Contact contact = null;
278 // The tokens are now available, so get all
279 while (tokenizer.hasMoreElements()) {
281 String token = tokenizer.nextToken();
284 this.getLogger().debug(MessageFormat.format("token={0}", token));
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));
292 // All fine, so remove it
293 String strippedToken = token.substring(1, token.length() - 1);
295 // Is the string's content "null"?
296 if (strippedToken.equals("null")) {
298 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken));
300 // This needs to be set to null
301 strippedToken = null;
305 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken));
307 // Init number/string data values
308 String strData = strippedToken;
311 Gender gender = null;
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?
317 num = Long.valueOf(strippedToken);
320 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken));
321 } catch (final NumberFormatException ex) {
322 // No number, then set default
327 // Now, let's try a boolean check, if no null
328 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) {
330 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken));
332 // parseBoolean() is relaxed, so no exceptions
333 bool = Boolean.valueOf(strippedToken);
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!");
343 // Now it depends on the counter which position we need to check
345 case 0: // isOwnContact
346 assert ((bool instanceof Boolean));
349 this.getLogger().debug(MessageFormat.format("bool={0}", bool));
351 // Is it own contact?
354 this.getLogger().debug("Creating UserContact object ...");
357 contact = new UserContact();
360 this.getLogger().debug("Creating BookContact object ...");
363 contact = new BookContact();
368 assert (contact instanceof Contact) : "First token was not boolean";
371 contact.updateNameData(gender, null, null, null);
375 assert (contact instanceof Contact) : "First token was not boolean";
378 contact.updateNameData(gender, strippedToken, null, null);
381 case 3: // Family name
382 assert (contact instanceof Contact) : "First token was not boolean";
385 contact.updateNameData(gender, null, strippedToken, null);
388 case 4: // Company name
389 assert (contact instanceof Contact) : "First token was not boolean";
392 contact.updateNameData(gender, null, null, strippedToken);
395 case 5: // Street number
396 assert (contact instanceof Contact) : "First token was not boolean";
399 contact.updateAddressData(strippedToken, 0, null, null);
403 assert (contact instanceof Contact) : "First token was not boolean";
406 contact.updateAddressData(null, num, null, null);
410 assert (contact instanceof Contact) : "First token was not boolean";
413 contact.updateAddressData(null, 0, strippedToken, null);
416 case 8: // Country code
417 assert (contact instanceof Contact) : "First token was not boolean";
420 contact.updateAddressData(null, 0, null, strippedToken);
423 case 9: // Phone number
424 assert (contact instanceof Contact) : "First token was not boolean";
427 contact.updateOtherData(strippedToken, null, null, null, null, null);
430 case 10: // Fax number
431 assert (contact instanceof Contact) : "First token was not boolean";
434 contact.updateOtherData(null, strippedToken, null, null, null, null);
437 case 11: // Cellphone number
438 assert (contact instanceof Contact) : "First token was not boolean";
441 contact.updateOtherData(null, null, strippedToken, null, null, null);
444 case 12: // Email address
445 assert (contact instanceof Contact) : "First token was not boolean";
448 contact.updateOtherData(null, null, null, strippedToken, null, null);
452 assert (contact instanceof Contact) : "First token was not boolean";
455 contact.updateOtherData(null, null, null, null, strippedToken, null);
459 assert (contact instanceof Contact) : "First token was not boolean";
462 contact.updateOtherData(null, null, null, null, null, strippedToken);
465 default: // New data entry
466 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count));
470 // Increment counter for next round
475 this.addContactToList(contact, list);
478 // Return finished list
479 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size()));
484 * Reads a line from file base
486 * @return Read line from file
488 private String readLine () {
493 input = this.getStorageFile().readLine();
494 } catch (final IOException ex) {
495 this.getLogger().catching(ex);
498 // Return read string or null