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.Base64;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.StringTokenizer;
29 import org.mxchange.addressbook.contact.Contact;
30 import org.mxchange.addressbook.contact.Gender;
31 import org.mxchange.addressbook.contact.book.BookContact;
32 import org.mxchange.addressbook.contact.user.UserContact;
33 import org.mxchange.addressbook.database.backend.BaseDatabaseBackend;
34 import org.mxchange.addressbook.database.storage.Storeable;
35 import org.mxchange.addressbook.database.storage.csv.StoreableCsv;
36 import org.mxchange.addressbook.exceptions.BadTokenException;
39 * A database backend with CSV file as storage implementation
41 * @author Roland Haeder
43 public class CsvDatabaseBackend extends BaseDatabaseBackend implements CsvBackend {
46 * Output stream for this storage engine
48 private RandomAccessFile storageFile;
51 * Constructor with table name
53 * @param tableName Name of "table"
55 public CsvDatabaseBackend (final String tableName) {
57 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName));
59 // Set table name here, too
60 this.setTableName(tableName);
62 // Construct file name
63 String fileName = String.format("data/table_%s.b64", tableName);
66 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName));
69 // Try to initialize the storage (file instance)
70 this.storageFile = new RandomAccessFile(fileName, "rw");
71 } catch (final FileNotFoundException ex) {
73 this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString()));
78 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName));
82 * Gets an iterator for contacts
84 * @return Iterator for contacts
85 * @throws org.mxchange.addressbook.exceptions.BadTokenException If the
86 * underlaying method has found an invalid token
89 public Iterator<Contact> contactIterator () throws BadTokenException {
91 * Then read the file into RAM (yes, not perfect for >1000 entries ...)
92 * and get a List back.
94 List<Contact> list = this.readContactList();
96 // Get iterator from list and return it
97 return list.iterator();
101 * Shuts down this backend
104 public void doShutdown () {
107 this.getStorageFile().close();
108 } catch (final IOException ex) {
109 this.getLogger().catching(ex);
115 * Get length of underlaying file
117 * @return Length of underlaying file
120 public long length () {
124 length = this.getStorageFile().length();
125 this.getLogger().debug(MessageFormat.format("length={0}", length));
126 } catch (final IOException ex) {
127 // Length cannot be determined
128 this.getLogger().catching(ex);
133 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length));
141 public void rewind () {
142 this.getLogger().trace("CALLED!");
145 // Rewind underlaying database file
146 this.getStorageFile().seek(0);
147 } catch (final IOException ex) {
148 this.getLogger().catching(ex);
152 this.getLogger().trace("EXIT!");
156 * Stores given object by "visiting" it
158 * @param object An object implementing Storeable
159 * @throws java.io.IOException From "inner" class
162 public void store (final Storeable object) throws IOException {
163 // Make sure the instance is there (DataOutput flawor)
164 assert (this.storageFile instanceof DataOutput);
166 // Try to cast it, this will fail if the interface is not implemented
167 StoreableCsv csv = (StoreableCsv) object;
169 // Now get a string from the object that needs to be stored
170 String str = csv.getCsvStringFromStoreableObject();
173 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str));
175 // Encode line in BASE-64
176 byte[] encoded = Base64.getEncoder().encode(str.trim().getBytes());
178 // The string is now a valid CSV string
179 this.getStorageFile().write(encoded);
183 * Adds given contact to list
185 * @param contact Contact instance to add
186 * @param list List instance
188 private void addContactToList (final Contact contact, final List<Contact> list) {
190 if (contact == null) {
192 throw new NullPointerException("contact is null");
193 } else if (list == null) {
195 throw new NullPointerException("list is null");
199 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
201 // Is the contact read?
202 if (contact instanceof Contact) {
204 boolean added = list.add(contact);
207 this.getLogger().debug(MessageFormat.format("contact={0} added={1}", contact, added));
209 // Has it been added?
212 this.getLogger().warn("Contact object has not been added.");
218 * Returns storage file
220 * @return Storage file instance
222 private RandomAccessFile getStorageFile () {
223 return this.storageFile;
227 * Checks whether end of file has been reached
229 * @return Whether lines are left to read
231 private boolean isEndOfFile () {
233 boolean isEof = true;
236 isEof = (this.getStorageFile().getFilePointer() >= this.length());
237 } catch (final IOException ex) {
238 // Length cannot be determined
239 this.getLogger().catching(ex);
243 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof));
248 * Reads the database file, if available, and adds all read lines into the
251 * @return A list with Contact instances
253 private List<Contact> readContactList () throws BadTokenException {
254 this.getLogger().trace("CALLED!");
259 // Get file size and divide it by 140 (possible average length of one line)
260 int lines = Math.round(this.length() / 140 + 0.5f);
263 this.getLogger().debug(MessageFormat.format("lines={0}", lines));
266 // @TODO The maximum length could be guessed from file size?
267 List<Contact> list = new ArrayList<>(lines);
270 StringTokenizer tokenizer;
273 // Init A lot variables
276 Gender gender = null;
278 Contact contact = null;
281 while (!this.isEndOfFile()) {
283 line = this.readLine();
286 this.getLogger().debug(MessageFormat.format("line={0}", line));
289 // @TODO Move this into separate method
290 tokenizer = new StringTokenizer(line, ";");
296 // The tokens are now available, so get all
297 while (tokenizer.hasMoreElements()) {
303 String token = tokenizer.nextToken();
305 // If char " is at pos 2 (0,1,2), then cut it of there
306 if ((token.charAt(0) != '"') && (token.charAt(2) == '"')) {
307 // UTF-8 writer characters found
308 token = token.substring(2);
312 this.getLogger().debug(MessageFormat.format("token={0}", token));
314 // Verify token, it must have double-quotes on each side
315 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) {
316 // Something bad was read
317 throw new BadTokenException(MessageFormat.format("Token {0} at position {1} has not double-quotes on both ends.", token, count));
320 // All fine, so remove it
321 String strippedToken = token.substring(1, token.length() - 1);
323 // Is the string's content "null"?
324 if (strippedToken.equals("null")) {
326 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken));
328 // This needs to be set to null
329 strippedToken = null;
333 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken));
335 // Now, let's try a number check, if no null
336 if (strippedToken != null) {
337 // Okay, no null, maybe the string bears a decimal number?
339 num = Long.valueOf(strippedToken);
342 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken));
343 } catch (final NumberFormatException ex) {
344 // No number, then set default
349 // Now, let's try a boolean check, if no null
350 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) {
352 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken));
354 // parseBoolean() is relaxed, so no exceptions
355 bool = Boolean.valueOf(strippedToken);
359 this.getLogger().debug(MessageFormat.format("strippedToken={0},num={1},bool={2}", strippedToken, num, bool));
361 // Now, let's try a gender check, if no null
362 if ((strippedToken != null) && (num == null) && (bool == null) && ((strippedToken.equals("M")) || (strippedToken.equals("F")) || (strippedToken.equals("C")))) {
363 // Get first character
364 gender = Gender.fromChar(strippedToken.charAt(0));
367 this.getLogger().debug(MessageFormat.format("strippedToken={0},gender={1}", strippedToken, gender));
369 // This instance must be there
370 assert (gender instanceof Gender) : "gender is not set by Gender.fromChar(" + strippedToken + ")";
373 // Now it depends on the counter which position we need to check
375 case 0: // isOwnContact
376 assert ((bool instanceof Boolean));
379 this.getLogger().debug(MessageFormat.format("bool={0}", bool));
381 // Is it own contact?
384 this.getLogger().debug("Creating UserContact object ...");
387 contact = new UserContact();
390 this.getLogger().debug("Creating BookContact object ...");
393 contact = new BookContact();
398 assert (contact instanceof Contact) : "First token was not boolean";
401 contact.updateNameData(gender, null, null, null);
405 assert (contact instanceof Contact) : "First token was not boolean";
406 assert (gender instanceof Gender) : "gender instance is not set";
409 contact.updateNameData(gender, strippedToken, null, null);
412 case 3: // Family name
413 assert (contact instanceof Contact) : "First token was not boolean";
414 assert (gender instanceof Gender) : "gender instance is not set";
417 contact.updateNameData(gender, null, strippedToken, null);
420 case 4: // Company name
421 assert (contact instanceof Contact) : "First token was not boolean";
422 assert (gender instanceof Gender) : "gender instance is not set";
425 contact.updateNameData(gender, null, null, strippedToken);
428 case 5: // Street number
429 assert (contact instanceof Contact) : "First token was not boolean";
432 contact.updateAddressData(strippedToken, 0, null, null);
436 assert (contact instanceof Contact) : "First token was not boolean";
439 contact.updateAddressData(null, num, null, null);
443 assert (contact instanceof Contact) : "First token was not boolean";
446 contact.updateAddressData(null, 0, strippedToken, null);
449 case 8: // Country code
450 assert (contact instanceof Contact) : "First token was not boolean";
453 contact.updateAddressData(null, 0, null, strippedToken);
456 case 9: // Phone number
457 assert (contact instanceof Contact) : "First token was not boolean";
460 contact.updateOtherData(strippedToken, null, null, null, null, null);
463 case 10: // Fax number
464 assert (contact instanceof Contact) : "First token was not boolean";
467 contact.updateOtherData(null, strippedToken, null, null, null, null);
470 case 11: // Cellphone number
471 assert (contact instanceof Contact) : "First token was not boolean";
474 contact.updateOtherData(null, null, strippedToken, null, null, null);
477 case 12: // Email address
478 assert (contact instanceof Contact) : "First token was not boolean";
481 contact.updateOtherData(null, null, null, strippedToken, null, null);
485 assert (contact instanceof Contact) : "First token was not boolean";
488 contact.updateOtherData(null, null, null, null, strippedToken, null);
492 assert (contact instanceof Contact) : "First token was not boolean";
495 contact.updateOtherData(null, null, null, null, null, strippedToken);
498 default: // New data entry
499 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count));
503 // Increment counter for next round
507 // The contact instance should be there now
508 assert(contact instanceof Contact) : "contact is not set: " + contact;
511 this.addContactToList(contact, list);
514 // Return finished list
515 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size()));
520 * Reads a line from file base
522 * @return Read line from file
524 private String readLine () {
529 String base64 = this.getStorageFile().readLine();
532 byte[] decoded = Base64.getDecoder().decode(base64);
535 input = new String(decoded);
536 } catch (final IOException ex) {
537 this.getLogger().catching(ex);
540 // Return read string or null