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 {
43 * Output stream for this storage engine
45 private RandomAccessFile storageFile;
48 * Constructor with table name
50 * @param tableName Name of "table"
52 public CsvDatabaseBackend (final String tableName) {
54 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName));
56 // Set table name here, too
57 this.setTableName(tableName);
59 // Construct file name
60 String fileName = String.format("data/table_%s.csv", tableName);
63 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName));
66 // Try to initialize the storage (file instance)
67 this.storageFile = new RandomAccessFile(fileName, "rw");
68 } catch (final FileNotFoundException ex) {
70 this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString()));
75 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName));
79 * Gets an iterator for contacts
81 * @return Iterator for contacts
82 * @throws org.mxchange.addressbook.exceptions.BadTokenException If the underlaying method has found an invalid token
85 public Iterator<Contact> contactIterator () throws BadTokenException {
87 * Then read the file into RAM (yes, not perfect for >1000 entries ...)
88 * and get a List back.
90 List<Contact> list = this.readContactList();
92 // Get iterator from list and return it
93 return list.iterator();
97 * Shuts down this backend
100 public void doShutdown () {
103 this.getStorageFile().close();
104 } catch (final IOException ex) {
105 this.getLogger().catching(ex);
111 * Get length of underlaying file
113 * @return Length of underlaying file
116 public long length () {
120 length = this.getStorageFile().length();
121 this.getLogger().debug(MessageFormat.format("length={0}", length));
122 } catch (final IOException ex) {
123 // Length cannot be determined
124 this.getLogger().catching(ex);
129 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length));
137 public void rewind (){
138 this.getLogger().trace("CALLED!");
141 // Rewind underlaying database file
142 this.getStorageFile().seek(0);
143 } catch (final IOException ex) {
144 this.getLogger().catching(ex);
148 this.getLogger().trace("EXIT!");
152 * Stores given object by "visiting" it
154 * @param object An object implementing Storeable
155 * @throws java.io.IOException From "inner" class
158 public void store (final Storeable object) throws IOException {
159 // Make sure the instance is there (DataOutput flawor)
160 assert(this.storageFile instanceof DataOutput);
162 // Try to cast it, this will fail if the interface is not implemented
163 StoreableCsv csv = (StoreableCsv) object;
165 // Now get a string from the object that needs to be stored
166 String str = csv.getCsvStringFromStoreableObject();
169 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str));
171 // The string is now a valid CSV string
172 this.getStorageFile().writeBytes(str);
176 * Adds given contact to list
178 * @param contact Contact instance to add
179 * @param list List instance
181 private void addContactToList (final Contact contact, final List<Contact> list) {
183 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
185 // Is the contact read?
186 if (contact instanceof Contact) {
188 boolean added = list.add(contact);
191 this.getLogger().debug(MessageFormat.format("contact={0} added={1}", contact, added));
193 // Has it been added?
196 this.getLogger().warn("Contact object has not been added.");
202 * Returns storage file
204 * @return Storage file instance
206 private RandomAccessFile getStorageFile () {
207 return this.storageFile;
211 * Checks whether end of file has been reached
213 * @return Whether lines are left to read
215 private boolean isEndOfFile () {
217 boolean isEof = true;
220 isEof = (this.getStorageFile().getFilePointer() >= this.length());
221 } catch (final IOException ex) {
222 // Length cannot be determined
223 this.getLogger().catching(ex);
227 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof));
232 * Reads the database file, if available, and adds all read lines into
235 * @return A list with Contact instances
237 private List<Contact> readContactList () throws BadTokenException {
238 this.getLogger().trace("CALLED!");
243 // Get file size and divide it by 140 (possible average length of one line)
244 int lines = Math.round(this.length() / 140 + 0.5f);
247 this.getLogger().debug(MessageFormat.format("lines={0}", lines));
250 // @TODO The maximum length could be guessed from file size?
251 List<Contact> list = new ArrayList<>(lines);
254 StringTokenizer tokenizer;
258 while (!this.isEndOfFile()) {
260 line = this.readLine();
263 this.getLogger().debug(MessageFormat.format("line={0}", line));
266 // @TODO Move this into separate method
267 tokenizer = new StringTokenizer(line, ";");
272 // Init contact object
273 Contact contact = null;
275 // The tokens are now available, so get all
276 while (tokenizer.hasMoreElements()) {
278 String token = tokenizer.nextToken();
281 this.getLogger().debug(MessageFormat.format("token={0}", token));
283 // Verify token, it must have double-quotes on each side
284 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) {
285 // Something bad was read
286 throw new BadTokenException(MessageFormat.format("Token {0} has not double-quotes on both ends.", token));
289 // All fine, so remove it
290 String strippedToken = token.substring(1, token.length() - 1);
292 // Is the string's content "null"?
293 if (strippedToken.equals("null")) {
295 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken));
297 // This needs to be set to null
298 strippedToken = null;
302 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken));
304 // Init number/string data values
305 String strData = strippedToken;
310 // Now, let's try a number check, if no null
311 if (strippedToken != null) {
312 // Okay, no null, maybe the string bears a decimal number?
314 num = Long.valueOf(strippedToken);
317 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken));
318 } catch (final NumberFormatException ex) {
319 // No number, then set default
324 // Now, let's try a boolean check, if no null
325 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) {
327 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken));
329 // parseBoolean() is relaxed, so no exceptions
330 bool = Boolean.valueOf(strippedToken);
333 // Now, let's try a boolean check, if no null
334 if ((strippedToken != null) && (num == null) && (bool == null) && ((strippedToken.equals("M")) || (strippedToken.equals("F")) || (strippedToken.equals("C")))) {
335 // Get first character
336 gender = strippedToken.charAt(0);
339 // Now it depends on the counter which position we need to check
341 case 0: // isOwnContact
342 assert((bool instanceof Boolean));
345 this.getLogger().debug(MessageFormat.format("bool={0}", bool));
347 // Is it own contact?
350 this.getLogger().debug("Creating UserContact object ...");
353 contact = new UserContact();
356 this.getLogger().debug("Creating BookContact object ...");
359 contact = new BookContact();
364 assert(contact instanceof Contact) : "First token was not boolean";
365 assert(gender != '?') : "Gender is not detected.";
368 contact.updateNameData(gender, null, null, null);
372 assert(contact instanceof Contact) : "First token was not boolean";
373 assert(gender != '?') : "Gender is not detected.";
376 contact.updateNameData(gender, strippedToken, null, null);
379 case 3: // Family name
380 assert(contact instanceof Contact) : "First token was not boolean";
381 assert(gender != '?') : "Gender is not detected.";
384 contact.updateNameData(gender, null, strippedToken, null);
387 case 4: // Company name
388 assert(contact instanceof Contact) : "First token was not boolean";
389 assert(gender != '?') : "Gender is not detected.";
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