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.sql.SQLException;
24 import java.text.MessageFormat;
25 import java.util.ArrayList;
26 import java.util.Base64;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.StringTokenizer;
30 import org.mxchange.addressbook.contact.Contact;
31 import org.mxchange.addressbook.contact.Gender;
32 import org.mxchange.addressbook.contact.book.BookContact;
33 import org.mxchange.addressbook.contact.user.UserContact;
34 import org.mxchange.addressbook.database.backend.BaseDatabaseBackend;
35 import org.mxchange.addressbook.database.backend.DatabaseBackend;
36 import org.mxchange.addressbook.database.storage.Storeable;
37 import org.mxchange.addressbook.database.storage.csv.StoreableCsv;
38 import org.mxchange.addressbook.exceptions.BadTokenException;
41 * A database backend with CSV file as storage implementation
43 * @author Roland Haeder
45 public class Base64CsvDatabaseBackend extends BaseDatabaseBackend implements DatabaseBackend {
48 * Output stream for this storage engine
50 private RandomAccessFile storageFile;
53 * Constructor with table name
55 * @param tableName Name of "table"
57 public Base64CsvDatabaseBackend (final String tableName) {
59 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName)); //NOI18N
61 // Set table name here, too
62 this.setTableName(tableName);
64 // Construct file name
65 String fileName = String.format("data/table_%s.b64", tableName); //NOI18N
68 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName)); //NOI18N
71 // Try to initialize the storage (file instance)
72 this.storageFile = new RandomAccessFile(fileName, "rw"); //NOI18N
73 } catch (final FileNotFoundException ex) {
75 this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString())); //NOI18N
80 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName)); //NOI18N
84 * This database backend does not need to connect
87 public void connectToDatabase () throws SQLException {
92 * Gets an iterator for contacts
94 * @return Iterator for contacts
95 * @throws org.mxchange.addressbook.exceptions.BadTokenException If the
96 * underlaying method has found an invalid token
99 public Iterator<Contact> contactIterator () throws BadTokenException {
101 this.getLogger().trace("CALLED!"); //NOI18N
104 * Then read the file into RAM (yes, not perfect for >1000 entries ...)
105 * and get a List back.
107 List<Contact> list = this.readContactList();
110 assert (list instanceof List) : "list has not been set."; //NOI18N
113 this.getLogger().trace(MessageFormat.format("list.iterator()={0} - EXIT!", list.iterator())); //NOI18N
115 // Get iterator from list and return it
116 return list.iterator();
120 * Shuts down this backend
123 public void doShutdown () {
125 this.getLogger().trace("CALLED!"); //NOI18N
129 this.getStorageFile().close();
130 } catch (final IOException ex) {
132 this.abortProgramWithException(ex);
136 this.getLogger().trace("EXIT!"); //NOI18N
140 * Get length of underlaying file
142 * @return Length of underlaying file
145 public long length () {
149 length = this.getStorageFile().length();
150 this.getLogger().debug(MessageFormat.format("length={0}", length)); //NOI18N
151 } catch (final IOException ex) {
152 // Length cannot be determined
154 this.abortProgramWithException(ex);
158 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length)); //NOI18N
166 public void rewind () {
168 this.getLogger().trace("CALLED!"); //NOI18N
171 // Rewind underlaying database file
172 this.getStorageFile().seek(0);
173 } catch (final IOException ex) {
175 this.abortProgramWithException(ex);
179 this.getLogger().trace("EXIT!"); //NOI18N
183 * Stores given object by "visiting" it
185 * @param object An object implementing Storeable
186 * @throws java.io.IOException From "inner" class
189 public void store (final Storeable object) throws IOException {
191 this.getLogger().trace(MessageFormat.format("object={0} - CALLED!", object)); //NOI18N
193 // Object must not be null
194 if (object == null) {
196 throw new NullPointerException("object is null");
199 // Make sure the instance is there (DataOutput flawor)
200 assert (this.storageFile instanceof DataOutput);
202 // Try to cast it, this will fail if the interface is not implemented
203 StoreableCsv csv = (StoreableCsv) object;
205 // Now get a string from the object that needs to be stored
206 String str = csv.getCsvStringFromStoreableObject();
209 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str)); //NOI18N
211 // Encode line in BASE-64
212 byte[] encoded = Base64.getEncoder().encode(str.getBytes());
214 // The string is now a valid CSV string
215 this.getStorageFile().write(encoded);
218 this.getLogger().trace("EXIT!"); //NOI18N
222 * Adds given contact to list
224 * @param contact Contact instance to add
225 * @param list List instance
227 private void addContactToList (final Contact contact, final List<Contact> list) {
229 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
232 if (contact == null) {
234 throw new NullPointerException("contact is null"); //NOI18N
235 } else if (list == null) {
237 throw new NullPointerException("list is null"); //NOI18N
241 this.getLogger().debug(MessageFormat.format("contact={0}", contact)); //NOI18N
243 // Is the contact read?
244 if (contact instanceof Contact) {
246 boolean added = list.add(contact);
249 this.getLogger().debug(MessageFormat.format("contact={0} added={1}", contact, added)); //NOI18N
251 // Has it been added?
254 this.getLogger().warn("Contact object has not been added."); //NOI18N
259 this.getLogger().trace("EXIT!"); //NOI18N
263 * Returns storage file
265 * @return Storage file instance
267 private RandomAccessFile getStorageFile () {
268 return this.storageFile;
272 * Checks whether end of file has been reached
274 * @return Whether lines are left to read
276 private boolean isEndOfFile () {
278 boolean isEof = true;
281 isEof = (this.getStorageFile().getFilePointer() >= this.length());
282 } catch (final IOException ex) {
283 // Length cannot be determined
284 this.getLogger().catching(ex);
288 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof)); //NOI18N
293 * Reads the database file, if available, and adds all read lines into the
296 * @return A list with Contact instances
298 private List<Contact> readContactList () throws BadTokenException {
299 this.getLogger().trace("CALLED!"); //NOI18N
304 // Get file size and divide it by 140 (possible average length of one line)
305 int lines = Math.round(this.length() / 140 + 0.5f);
308 this.getLogger().debug(MessageFormat.format("lines={0}", lines)); //NOI18N
311 // @TODO The maximum length could be guessed from file size?
312 List<Contact> list = new ArrayList<>(lines);
315 StringTokenizer tokenizer;
318 // Init A lot variables
321 Gender gender = null;
323 Contact contact = null;
326 while (!this.isEndOfFile()) {
328 line = this.readLine();
331 this.getLogger().debug(MessageFormat.format("line={0}", line)); //NOI18N
334 // @TODO Move this into separate method
335 tokenizer = new StringTokenizer(line, ";"); //NOI18N
341 // The tokens are now available, so get all
342 while (tokenizer.hasMoreElements()) {
348 String token = tokenizer.nextToken();
350 // If char " is at pos 2 (0,1,2), then cut it of there
351 if ((token.charAt(0) != '"') && (token.charAt(2) == '"')) {
352 // UTF-8 writer characters found
353 token = token.substring(2);
357 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
359 // Verify token, it must have double-quotes on each side
360 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) { //NOI18N
361 // Something bad was read
362 throw new BadTokenException(token, count); //NOI18N
365 // All fine, so remove it
366 String strippedToken = token.substring(1, token.length() - 1);
368 // Is the string's content "null"?
369 if (strippedToken.equals("null")) { //NOI18N
371 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken)); //NOI18N
373 // This needs to be set to null
374 strippedToken = null;
378 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken)); //NOI18N
380 // Now, let's try a number check, if no null
381 if (strippedToken != null) {
382 // Okay, no null, maybe the string bears a decimal number?
384 num = Long.valueOf(strippedToken);
387 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken)); //NOI18N
388 } catch (final NumberFormatException ex) {
389 // No number, then set default
394 // Now, let's try a boolean check, if no null
395 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) { //NOI18N
397 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken)); //NOI18N
399 // parseBoolean() is relaxed, so no exceptions
400 bool = Boolean.valueOf(strippedToken);
404 this.getLogger().debug(MessageFormat.format("strippedToken={0},num={1},bool={2}", strippedToken, num, bool)); //NOI18N
406 // Now, let's try a gender check, if no null
407 if ((strippedToken != null) && (num == null) && (bool == null) && ((strippedToken.equals("M")) || (strippedToken.equals("F")) || (strippedToken.equals("C")))) { //NOI18N
408 // Get first character
409 gender = Gender.fromChar(strippedToken.charAt(0));
412 this.getLogger().debug(MessageFormat.format("strippedToken={0},gender={1}", strippedToken, gender)); //NOI18N
414 // This instance must be there
415 assert (gender instanceof Gender) : "gender is not set by Gender.fromChar(" + strippedToken + ")"; //NOI18N
418 // Now it depends on the counter which position we need to check
420 case 0: // isOwnContact
421 assert ((bool instanceof Boolean));
424 this.getLogger().debug(MessageFormat.format("bool={0}", bool)); //NOI18N
426 // Is it own contact?
429 this.getLogger().debug("Creating UserContact object ..."); //NOI18N
432 contact = new UserContact();
435 this.getLogger().debug("Creating BookContact object ..."); //NOI18N
438 contact = new BookContact();
443 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
446 contact.updateNameData(gender, null, null, null);
450 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
451 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
454 contact.updateNameData(gender, strippedToken, null, null);
457 case 3: // Family name
458 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
459 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
462 contact.updateNameData(gender, null, strippedToken, null);
465 case 4: // Company name
466 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
467 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
470 contact.updateNameData(gender, null, null, strippedToken);
473 case 5: // Street number
474 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
477 contact.updateAddressData(strippedToken, 0, null, null);
481 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
484 contact.updateAddressData(null, num, null, null);
488 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
491 contact.updateAddressData(null, 0, strippedToken, null);
494 case 8: // Country code
495 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
498 contact.updateAddressData(null, 0, null, strippedToken);
501 case 9: // Phone number
502 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
505 contact.updateOtherData(strippedToken, null, null, null, null, null);
508 case 10: // Fax number
509 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
512 contact.updateOtherData(null, strippedToken, null, null, null, null);
515 case 11: // Cellphone number
516 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
519 contact.updateOtherData(null, null, strippedToken, null, null, null);
522 case 12: // Email address
523 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
526 contact.updateOtherData(null, null, null, strippedToken, null, null);
530 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
533 contact.updateOtherData(null, null, null, null, strippedToken, null);
537 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
540 contact.updateOtherData(null, null, null, null, null, strippedToken);
543 default: // New data entry
544 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count)); //NOI18N
548 // Increment counter for next round
552 // The contact instance should be there now
553 assert (contact instanceof Contact) : "contact is not set: " + contact; //NOI18N
556 this.addContactToList(contact, list);
559 // Return finished list
560 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size())); //NOI18N
565 * Reads a line from file base
567 * @return Read line from file
569 private String readLine () {
571 this.getLogger().trace("CALLED!"); //NOI18N
578 String base64 = this.getStorageFile().readLine();
581 byte[] decoded = Base64.getDecoder().decode(base64);
584 input = new String(decoded);
585 } catch (final IOException ex) {
586 this.getLogger().catching(ex);
590 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
592 // Return read string or null