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.backend.DatabaseBackend;
35 import org.mxchange.addressbook.database.storage.Storeable;
36 import org.mxchange.addressbook.database.storage.csv.StoreableCsv;
37 import org.mxchange.addressbook.exceptions.BadTokenException;
40 * A database backend with CSV file as storage implementation
42 * @author Roland Haeder
44 public class Base64CsvDatabaseBackend extends BaseDatabaseBackend implements DatabaseBackend {
47 * Output stream for this storage engine
49 private RandomAccessFile storageFile;
52 * Constructor with table name
54 * @param tableName Name of "table"
56 public Base64CsvDatabaseBackend (final String tableName) {
58 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName)); //NOI18N
60 // Set table name here, too
61 this.setTableName(tableName);
63 // Construct file name
64 String fileName = String.format("data/table_%s.b64", tableName); //NOI18N
67 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName)); //NOI18N
70 // Try to initialize the storage (file instance)
71 this.storageFile = new RandomAccessFile(fileName, "rw"); //NOI18N
72 } catch (final FileNotFoundException ex) {
74 this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString())); //NOI18N
79 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName)); //NOI18N
83 * This database backend does not need to connect
86 public void connectToDatabase () {
91 * Gets an iterator for contacts
93 * @return Iterator for contacts
94 * @throws org.mxchange.addressbook.exceptions.BadTokenException If the
95 * underlaying method has found an invalid token
98 public Iterator<Contact> contactIterator () throws BadTokenException {
100 this.getLogger().trace("CALLED!"); //NOI18N
103 * Then read the file into RAM (yes, not perfect for >1000 entries ...)
104 * and get a List back.
106 List<Contact> list = this.readContactList();
109 assert (list instanceof List) : "list has not been set."; //NOI18N
112 this.getLogger().trace(MessageFormat.format("list.iterator()={0} - EXIT!", list.iterator())); //NOI18N
114 // Get iterator from list and return it
115 return list.iterator();
119 * Shuts down this backend
122 public void doShutdown () {
124 this.getLogger().trace("CALLED!"); //NOI18N
128 this.getStorageFile().close();
129 } catch (final IOException ex) {
131 this.abortProgramWithException(ex);
135 this.getLogger().trace("EXIT!"); //NOI18N
139 * Get length of underlaying file
141 * @return Length of underlaying file
144 public long length () {
148 length = this.getStorageFile().length();
149 this.getLogger().debug(MessageFormat.format("length={0}", length)); //NOI18N
150 } catch (final IOException ex) {
151 // Length cannot be determined
153 this.abortProgramWithException(ex);
157 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length)); //NOI18N
165 public void rewind () {
167 this.getLogger().trace("CALLED!"); //NOI18N
170 // Rewind underlaying database file
171 this.getStorageFile().seek(0);
172 } catch (final IOException ex) {
174 this.abortProgramWithException(ex);
178 this.getLogger().trace("EXIT!"); //NOI18N
182 * Stores given object by "visiting" it
184 * @param object An object implementing Storeable
185 * @throws java.io.IOException From "inner" class
188 public void store (final Storeable object) throws IOException {
190 this.getLogger().trace(MessageFormat.format("object={0} - CALLED!", object)); //NOI18N
192 // Object must not be null
193 if (object == null) {
195 throw new NullPointerException("object is null");
198 // Make sure the instance is there (DataOutput flawor)
199 assert (this.storageFile instanceof DataOutput);
201 // Try to cast it, this will fail if the interface is not implemented
202 StoreableCsv csv = (StoreableCsv) object;
204 // Now get a string from the object that needs to be stored
205 String str = csv.getCsvStringFromStoreableObject();
208 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str)); //NOI18N
210 // Encode line in BASE-64
211 byte[] encoded = Base64.getEncoder().encode(str.getBytes());
213 // The string is now a valid CSV string
214 this.getStorageFile().write(encoded);
217 this.getLogger().trace("EXIT!"); //NOI18N
221 * Adds given contact to list
223 * @param contact Contact instance to add
224 * @param list List instance
226 private void addContactToList (final Contact contact, final List<Contact> list) {
228 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
231 if (contact == null) {
233 throw new NullPointerException("contact is null"); //NOI18N
234 } else if (list == null) {
236 throw new NullPointerException("list is null"); //NOI18N
240 this.getLogger().debug(MessageFormat.format("contact={0}", contact)); //NOI18N
242 // Is the contact read?
243 if (contact instanceof Contact) {
245 boolean added = list.add(contact);
248 this.getLogger().debug(MessageFormat.format("contact={0} added={1}", contact, added)); //NOI18N
250 // Has it been added?
253 this.getLogger().warn("Contact object has not been added."); //NOI18N
258 this.getLogger().trace("EXIT!"); //NOI18N
262 * Returns storage file
264 * @return Storage file instance
266 private RandomAccessFile getStorageFile () {
267 return this.storageFile;
271 * Checks whether end of file has been reached
273 * @return Whether lines are left to read
275 private boolean isEndOfFile () {
277 boolean isEof = true;
280 isEof = (this.getStorageFile().getFilePointer() >= this.length());
281 } catch (final IOException ex) {
282 // Length cannot be determined
283 this.getLogger().catching(ex);
287 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof)); //NOI18N
292 * Reads the database file, if available, and adds all read lines into the
295 * @return A list with Contact instances
297 private List<Contact> readContactList () throws BadTokenException {
298 this.getLogger().trace("CALLED!"); //NOI18N
303 // Get file size and divide it by 140 (possible average length of one line)
304 int lines = Math.round(this.length() / 140 + 0.5f);
307 this.getLogger().debug(MessageFormat.format("lines={0}", lines)); //NOI18N
310 // @TODO The maximum length could be guessed from file size?
311 List<Contact> list = new ArrayList<>(lines);
314 StringTokenizer tokenizer;
317 // Init A lot variables
320 Gender gender = null;
322 Contact contact = null;
325 while (!this.isEndOfFile()) {
327 line = this.readLine();
330 this.getLogger().debug(MessageFormat.format("line={0}", line)); //NOI18N
333 // @TODO Move this into separate method
334 tokenizer = new StringTokenizer(line, ";"); //NOI18N
340 // The tokens are now available, so get all
341 while (tokenizer.hasMoreElements()) {
347 String token = tokenizer.nextToken();
349 // If char " is at pos 2 (0,1,2), then cut it of there
350 if ((token.charAt(0) != '"') && (token.charAt(2) == '"')) {
351 // UTF-8 writer characters found
352 token = token.substring(2);
356 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
358 // Verify token, it must have double-quotes on each side
359 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) { //NOI18N
360 // Something bad was read
361 throw new BadTokenException(token, count); //NOI18N
364 // All fine, so remove it
365 String strippedToken = token.substring(1, token.length() - 1);
367 // Is the string's content "null"?
368 if (strippedToken.equals("null")) { //NOI18N
370 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken)); //NOI18N
372 // This needs to be set to null
373 strippedToken = null;
377 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken)); //NOI18N
379 // Now, let's try a number check, if no null
380 if (strippedToken != null) {
381 // Okay, no null, maybe the string bears a decimal number?
383 num = Long.valueOf(strippedToken);
386 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken)); //NOI18N
387 } catch (final NumberFormatException ex) {
388 // No number, then set default
393 // Now, let's try a boolean check, if no null
394 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) { //NOI18N
396 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken)); //NOI18N
398 // parseBoolean() is relaxed, so no exceptions
399 bool = Boolean.valueOf(strippedToken);
403 this.getLogger().debug(MessageFormat.format("strippedToken={0},num={1},bool={2}", strippedToken, num, bool)); //NOI18N
405 // Now, let's try a gender check, if no null
406 if ((strippedToken != null) && (num == null) && (bool == null) && ((strippedToken.equals("M")) || (strippedToken.equals("F")) || (strippedToken.equals("C")))) { //NOI18N
407 // Get first character
408 gender = Gender.fromChar(strippedToken.charAt(0));
411 this.getLogger().debug(MessageFormat.format("strippedToken={0},gender={1}", strippedToken, gender)); //NOI18N
413 // This instance must be there
414 assert (gender instanceof Gender) : "gender is not set by Gender.fromChar(" + strippedToken + ")"; //NOI18N
417 // Now it depends on the counter which position we need to check
419 case 0: // isOwnContact
420 assert ((bool instanceof Boolean));
423 this.getLogger().debug(MessageFormat.format("bool={0}", bool)); //NOI18N
425 // Is it own contact?
428 this.getLogger().debug("Creating UserContact object ..."); //NOI18N
431 contact = new UserContact();
434 this.getLogger().debug("Creating BookContact object ..."); //NOI18N
437 contact = new BookContact();
442 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
445 contact.updateNameData(gender, null, null, null);
449 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
450 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
453 contact.updateNameData(gender, strippedToken, null, null);
456 case 3: // Family name
457 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
458 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
461 contact.updateNameData(gender, null, strippedToken, null);
464 case 4: // Company name
465 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
466 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
469 contact.updateNameData(gender, null, null, strippedToken);
472 case 5: // Street number
473 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
476 contact.updateAddressData(strippedToken, 0, null, null);
480 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
483 contact.updateAddressData(null, num, null, null);
487 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
490 contact.updateAddressData(null, 0, strippedToken, null);
493 case 8: // Country code
494 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
497 contact.updateAddressData(null, 0, null, strippedToken);
500 case 9: // Phone number
501 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
504 contact.updateOtherData(strippedToken, null, null, null, null, null);
507 case 10: // Fax number
508 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
511 contact.updateOtherData(null, strippedToken, null, null, null, null);
514 case 11: // Cellphone number
515 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
518 contact.updateOtherData(null, null, strippedToken, null, null, null);
521 case 12: // Email address
522 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
525 contact.updateOtherData(null, null, null, strippedToken, null, null);
529 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
532 contact.updateOtherData(null, null, null, null, strippedToken, null);
536 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
539 contact.updateOtherData(null, null, null, null, null, strippedToken);
542 default: // New data entry
543 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count)); //NOI18N
547 // Increment counter for next round
551 // The contact instance should be there now
552 assert (contact instanceof Contact) : "contact is not set: " + contact; //NOI18N
555 this.addContactToList(contact, list);
558 // Return finished list
559 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size())); //NOI18N
564 * Reads a line from file base
566 * @return Read line from file
568 private String readLine () {
570 this.getLogger().trace("CALLED!"); //NOI18N
577 String base64 = this.getStorageFile().readLine();
580 byte[] decoded = Base64.getDecoder().decode(base64);
583 input = new String(decoded);
584 } catch (final IOException ex) {
585 this.getLogger().catching(ex);
589 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
591 // Return read string or null