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 Base64CsvDatabaseBackend 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 Base64CsvDatabaseBackend (final String tableName) {
57 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName)); //NOI18N
59 // Set table name here, too
60 this.setTableName(tableName);
62 // Construct file name
63 String fileName = String.format("data/table_%s.b64", tableName); //NOI18N
66 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName)); //NOI18N
69 // Try to initialize the storage (file instance)
70 this.storageFile = new RandomAccessFile(fileName, "rw"); //NOI18N
71 } catch (final FileNotFoundException ex) {
73 this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString())); //NOI18N
78 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName)); //NOI18N
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 this.getLogger().trace("CALLED!"); //NOI18N
94 * Then read the file into RAM (yes, not perfect for >1000 entries ...)
95 * and get a List back.
97 List<Contact> list = this.readContactList();
100 assert (list instanceof List) : "list has not been set."; //NOI18N
103 this.getLogger().trace(MessageFormat.format("list.iterator()={0} - EXIT!", list.iterator())); //NOI18N
105 // Get iterator from list and return it
106 return list.iterator();
110 * Shuts down this backend
113 public void doShutdown () {
115 this.getLogger().trace("CALLED!"); //NOI18N
119 this.getStorageFile().close();
120 } catch (final IOException ex) {
121 this.getLogger().catching(ex);
126 this.getLogger().trace("EXIT!"); //NOI18N
130 * Get length of underlaying file
132 * @return Length of underlaying file
135 public long length () {
139 length = this.getStorageFile().length();
140 this.getLogger().debug(MessageFormat.format("length={0}", length)); //NOI18N
141 } catch (final IOException ex) {
142 // Length cannot be determined
143 this.getLogger().catching(ex);
148 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length)); //NOI18N
156 public void rewind () {
158 this.getLogger().trace("CALLED!"); //NOI18N
161 // Rewind underlaying database file
162 this.getStorageFile().seek(0);
163 } catch (final IOException ex) {
164 this.getLogger().catching(ex);
169 this.getLogger().trace("EXIT!"); //NOI18N
173 * Stores given object by "visiting" it
175 * @param object An object implementing Storeable
176 * @throws java.io.IOException From "inner" class
179 public void store (final Storeable object) throws IOException {
181 this.getLogger().trace(MessageFormat.format("object={0} - CALLED!", object)); //NOI18N
183 // Object must not be null
184 if (object == null) {
186 throw new NullPointerException("object is null");
189 // Make sure the instance is there (DataOutput flawor)
190 assert (this.storageFile instanceof DataOutput);
192 // Try to cast it, this will fail if the interface is not implemented
193 StoreableCsv csv = (StoreableCsv) object;
195 // Now get a string from the object that needs to be stored
196 String str = csv.getCsvStringFromStoreableObject();
199 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str)); //NOI18N
201 // Encode line in BASE-64
202 byte[] encoded = Base64.getEncoder().encode(str.getBytes());
204 // The string is now a valid CSV string
205 this.getStorageFile().write(encoded);
208 this.getLogger().trace("EXIT!"); //NOI18N
212 * Adds given contact to list
214 * @param contact Contact instance to add
215 * @param list List instance
217 private void addContactToList (final Contact contact, final List<Contact> list) {
219 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
222 if (contact == null) {
224 throw new NullPointerException("contact is null"); //NOI18N
225 } else if (list == null) {
227 throw new NullPointerException("list is null"); //NOI18N
231 this.getLogger().debug(MessageFormat.format("contact={0}", contact)); //NOI18N
233 // Is the contact read?
234 if (contact instanceof Contact) {
236 boolean added = list.add(contact);
239 this.getLogger().debug(MessageFormat.format("contact={0} added={1}", contact, added)); //NOI18N
241 // Has it been added?
244 this.getLogger().warn("Contact object has not been added."); //NOI18N
249 this.getLogger().trace("EXIT!"); //NOI18N
253 * Returns storage file
255 * @return Storage file instance
257 private RandomAccessFile getStorageFile () {
258 return this.storageFile;
262 * Checks whether end of file has been reached
264 * @return Whether lines are left to read
266 private boolean isEndOfFile () {
268 boolean isEof = true;
271 isEof = (this.getStorageFile().getFilePointer() >= this.length());
272 } catch (final IOException ex) {
273 // Length cannot be determined
274 this.getLogger().catching(ex);
278 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof)); //NOI18N
283 * Reads the database file, if available, and adds all read lines into the
286 * @return A list with Contact instances
288 private List<Contact> readContactList () throws BadTokenException {
289 this.getLogger().trace("CALLED!"); //NOI18N
294 // Get file size and divide it by 140 (possible average length of one line)
295 int lines = Math.round(this.length() / 140 + 0.5f);
298 this.getLogger().debug(MessageFormat.format("lines={0}", lines)); //NOI18N
301 // @TODO The maximum length could be guessed from file size?
302 List<Contact> list = new ArrayList<>(lines);
305 StringTokenizer tokenizer;
308 // Init A lot variables
311 Gender gender = null;
313 Contact contact = null;
316 while (!this.isEndOfFile()) {
318 line = this.readLine();
321 this.getLogger().debug(MessageFormat.format("line={0}", line)); //NOI18N
324 // @TODO Move this into separate method
325 tokenizer = new StringTokenizer(line, ";"); //NOI18N
331 // The tokens are now available, so get all
332 while (tokenizer.hasMoreElements()) {
338 String token = tokenizer.nextToken();
340 // If char " is at pos 2 (0,1,2), then cut it of there
341 if ((token.charAt(0) != '"') && (token.charAt(2) == '"')) {
342 // UTF-8 writer characters found
343 token = token.substring(2);
347 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
349 // Verify token, it must have double-quotes on each side
350 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) { //NOI18N
351 // Something bad was read
352 throw new BadTokenException(MessageFormat.format("Token {0} at position {1} has not double-quotes on both ends.", token, count)); //NOI18N
355 // All fine, so remove it
356 String strippedToken = token.substring(1, token.length() - 1);
358 // Is the string's content "null"?
359 if (strippedToken.equals("null")) { //NOI18N
361 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken)); //NOI18N
363 // This needs to be set to null
364 strippedToken = null;
368 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken)); //NOI18N
370 // Now, let's try a number check, if no null
371 if (strippedToken != null) {
372 // Okay, no null, maybe the string bears a decimal number?
374 num = Long.valueOf(strippedToken);
377 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken)); //NOI18N
378 } catch (final NumberFormatException ex) {
379 // No number, then set default
384 // Now, let's try a boolean check, if no null
385 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) { //NOI18N
387 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken)); //NOI18N
389 // parseBoolean() is relaxed, so no exceptions
390 bool = Boolean.valueOf(strippedToken);
394 this.getLogger().debug(MessageFormat.format("strippedToken={0},num={1},bool={2}", strippedToken, num, bool)); //NOI18N
396 // Now, let's try a gender check, if no null
397 if ((strippedToken != null) && (num == null) && (bool == null) && ((strippedToken.equals("M")) || (strippedToken.equals("F")) || (strippedToken.equals("C")))) { //NOI18N
398 // Get first character
399 gender = Gender.fromChar(strippedToken.charAt(0));
402 this.getLogger().debug(MessageFormat.format("strippedToken={0},gender={1}", strippedToken, gender)); //NOI18N
404 // This instance must be there
405 assert (gender instanceof Gender) : "gender is not set by Gender.fromChar(" + strippedToken + ")"; //NOI18N
408 // Now it depends on the counter which position we need to check
410 case 0: // isOwnContact
411 assert ((bool instanceof Boolean));
414 this.getLogger().debug(MessageFormat.format("bool={0}", bool)); //NOI18N
416 // Is it own contact?
419 this.getLogger().debug("Creating UserContact object ..."); //NOI18N
422 contact = new UserContact();
425 this.getLogger().debug("Creating BookContact object ..."); //NOI18N
428 contact = new BookContact();
433 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
436 contact.updateNameData(gender, null, null, null);
440 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
441 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
444 contact.updateNameData(gender, strippedToken, null, null);
447 case 3: // Family name
448 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
449 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
452 contact.updateNameData(gender, null, strippedToken, null);
455 case 4: // Company name
456 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
457 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
460 contact.updateNameData(gender, null, null, strippedToken);
463 case 5: // Street number
464 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
467 contact.updateAddressData(strippedToken, 0, null, null);
471 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
474 contact.updateAddressData(null, num, null, null);
478 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
481 contact.updateAddressData(null, 0, strippedToken, null);
484 case 8: // Country code
485 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
488 contact.updateAddressData(null, 0, null, strippedToken);
491 case 9: // Phone number
492 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
495 contact.updateOtherData(strippedToken, null, null, null, null, null);
498 case 10: // Fax number
499 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
502 contact.updateOtherData(null, strippedToken, null, null, null, null);
505 case 11: // Cellphone number
506 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
509 contact.updateOtherData(null, null, strippedToken, null, null, null);
512 case 12: // Email address
513 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
516 contact.updateOtherData(null, null, null, strippedToken, null, null);
520 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
523 contact.updateOtherData(null, null, null, null, strippedToken, null);
527 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
530 contact.updateOtherData(null, null, null, null, null, strippedToken);
533 default: // New data entry
534 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count)); //NOI18N
538 // Increment counter for next round
542 // The contact instance should be there now
543 assert (contact instanceof Contact) : "contact is not set: " + contact; //NOI18N
546 this.addContactToList(contact, list);
549 // Return finished list
550 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size())); //NOI18N
555 * Reads a line from file base
557 * @return Read line from file
559 private String readLine () {
561 this.getLogger().trace("CALLED!"); //NOI18N
568 String base64 = this.getStorageFile().readLine();
571 byte[] decoded = Base64.getDecoder().decode(base64);
574 input = new String(decoded);
575 } catch (final IOException ex) {
576 this.getLogger().catching(ex);
580 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
582 // Return read string or null