2 * Copyright (C) 2015 Roland Haeder
\r
4 * This program is free software: you can redistribute it and/or modify
\r
5 * it under the terms of the GNU General Public License as published by
\r
6 * the Free Software Foundation, either version 3 of the License, or
\r
7 * (at your option) any later version.
\r
9 * This program is distributed in the hope that it will be useful,
\r
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
\r
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
\r
12 * GNU General Public License for more details.
\r
14 * You should have received a copy of the GNU General Public License
\r
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
\r
17 package org.mxchange.addressbook.database.backend.csv;
\r
19 import java.io.DataOutput;
\r
20 import java.io.FileNotFoundException;
\r
21 import java.io.IOException;
\r
22 import java.io.RandomAccessFile;
\r
23 import java.text.MessageFormat;
\r
24 import java.util.ArrayList;
\r
25 import java.util.Iterator;
\r
26 import java.util.List;
\r
27 import java.util.StringTokenizer;
\r
28 import org.mxchange.addressbook.BadTokenException;
\r
29 import org.mxchange.addressbook.contact.Contact;
\r
30 import org.mxchange.addressbook.contact.book.BookContact;
\r
31 import org.mxchange.addressbook.contact.user.UserContact;
\r
32 import org.mxchange.addressbook.database.backend.BaseDatabaseBackend;
\r
33 import org.mxchange.addressbook.database.storage.Storeable;
\r
34 import org.mxchange.addressbook.database.storage.csv.StoreableCsv;
\r
37 * A database backend with CSV file as storage implementation
\r
39 * @author Roland Haeder
\r
41 public class CsvDatabaseBackend extends BaseDatabaseBackend implements CsvBackend {
\r
43 * Output stream for this storage engine
\r
45 private RandomAccessFile storageFile;
\r
48 * Constructor with table name
\r
50 * @param tableName Name of "table"
\r
52 public CsvDatabaseBackend (final String tableName) {
\r
54 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName));
\r
56 // Set table name here, too
\r
57 this.setTableName(tableName);
\r
59 // Construct file name
\r
60 String fileName = String.format("data/table_%s.csv", tableName);
\r
63 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName));
\r
66 // Try to initialize the storage (file instance)
\r
67 this.storageFile = new RandomAccessFile(fileName, "rw");
\r
68 } catch (final FileNotFoundException ex) {
\r
70 this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString()));
\r
75 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName));
\r
79 * Gets an iterator for contacts
\r
81 * @return Iterator for contacts
\r
82 * @throws org.mxchange.addressbook.BadTokenException If the underlaying method has found an invalid token
\r
85 public Iterator<Contact> contactIterator () throws BadTokenException {
\r
87 * Then read the file into RAM (yes, not perfect for >1000 entries ...)
\r
88 * and get a List back.
\r
90 List<Contact> list = this.readContactList();
\r
92 // Get iterator from list and return it
\r
93 return list.iterator();
\r
97 * Get length of underlaying file
\r
99 * @return Length of underlaying file
\r
102 public long length () {
\r
106 length = this.storageFile.length();
\r
107 this.getLogger().debug(MessageFormat.format("length={0}", length));
\r
108 } catch (final IOException ex) {
\r
109 // Length cannot be determined
\r
110 this.getLogger().catching(ex);
\r
115 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length));
\r
123 public void rewind (){
\r
124 this.getLogger().trace("CALLED!");
\r
127 // Rewind underlaying database file
\r
128 this.storageFile.seek(0);
\r
129 } catch (final IOException ex) {
\r
130 this.getLogger().catching(ex);
\r
134 this.getLogger().trace("EXIT!");
\r
138 * Stores given object by "visiting" it
\r
140 * @param object An object implementing Storeable
\r
141 * @throws java.io.IOException From "inner" class
\r
144 public void store (final Storeable object) throws IOException {
\r
145 // Make sure the instance is there (DataOutput flawor)
\r
146 assert(this.storageFile instanceof DataOutput);
\r
148 // Try to cast it, this will fail if the interface is not implemented
\r
149 StoreableCsv csv = (StoreableCsv) object;
\r
151 // Now get a string from the object that needs to be stored
\r
152 String str = csv.getCsvStringFromStoreableObject();
\r
155 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str));
\r
157 // The string is now a valid CSV string
\r
158 this.storageFile.writeChars(str);
\r
162 * Checks whether end of file has been reached
\r
164 * @return Whether lines are left to read
\r
166 private boolean isEndOfFile () {
\r
168 boolean isEof = true;
\r
171 isEof = (this.storageFile.getFilePointer() >= this.length());
\r
172 } catch (final IOException ex) {
\r
173 // Length cannot be determined
\r
174 this.getLogger().catching(ex);
\r
178 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof));
\r
183 * Reads the database file, if available, and adds all read lines into
\r
186 * @return A list with Contact instances
\r
188 private List<Contact> readContactList () throws BadTokenException {
\r
189 this.getLogger().trace("CALLED!");
\r
195 // @TODO The maximum length could be guessed from file size?
\r
196 List<Contact> list = new ArrayList<>();
\r
199 StringTokenizer tokenizer;
\r
203 while (!this.isEndOfFile()) {
\r
204 // Then read a line
\r
205 line = this.readLine();
\r
208 this.getLogger().debug(MessageFormat.format("line={0}", line));
\r
210 // Then tokenize it
\r
211 // @TODO Move this into separate method
\r
212 tokenizer = new StringTokenizer(line, ";");
\r
217 // Init contact object
\r
218 Contact contact = null;
\r
220 // The tokens are now available, so get all
\r
221 while (tokenizer.hasMoreElements()) {
\r
223 String token = tokenizer.nextToken();
\r
226 this.getLogger().debug(MessageFormat.format("token={0}", token));
\r
228 // Verify token, it must have double-quotes on each side
\r
229 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) {
\r
230 // Something bad was read
\r
231 throw new BadTokenException(MessageFormat.format("Token {0} has not double-quotes on both ends.", token));
\r
234 // All fine, so remove it
\r
235 String strippedToken = token.substring(1, token.length() - 1);
\r
237 // Is the string's content "null"?
\r
238 if (strippedToken.equals("null")) {
\r
240 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken));
\r
242 // This needs to be set to null
\r
243 strippedToken = null;
\r
247 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken));
\r
249 // Init number/string data values
\r
250 String strData = strippedToken;
\r
252 Boolean bool = null;
\r
255 // Now, let's try a number check, if no null
\r
256 if (strippedToken != null) {
\r
257 // Okay, no null, maybe the string bears a decimal number?
\r
259 num = Long.valueOf(strippedToken);
\r
262 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken));
\r
263 } catch (final NumberFormatException ex) {
\r
264 // No number, then set default
\r
269 // Now, let's try a boolean check, if no null
\r
270 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) {
\r
272 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken));
\r
274 // parseBoolean() is relaxed, so no exceptions
\r
275 bool = Boolean.valueOf(strippedToken);
\r
278 // Now, let's try a boolean check, if no null
\r
279 if ((strippedToken != null) && (num == null) && (bool == null) && ((strippedToken.equals("M")) || (strippedToken.equals("F")) || (strippedToken.equals("C")))) {
\r
280 // Get first character
\r
281 gender = strippedToken.charAt(0);
\r
284 // Now it depends on the counter which position we need to check
\r
286 case 0: // isOwnContact
\r
287 assert((bool instanceof Boolean));
\r
290 this.getLogger().debug(MessageFormat.format("bool={0}", bool));
\r
292 // Is it own contact?
\r
293 if (true == bool) {
\r
295 this.getLogger().debug("Creating UserContact object ...");
\r
298 contact = new UserContact();
\r
301 this.getLogger().debug("Creating BookContact object ...");
\r
304 contact = new BookContact();
\r
309 assert(contact instanceof Contact) : "First token was not boolean";
\r
310 assert(gender != '?') : "Gender is not detected.";
\r
313 contact.updateNameData(gender, null, null, null);
\r
317 assert(contact instanceof Contact) : "First token was not boolean";
\r
318 assert(gender != '?') : "Gender is not detected.";
\r
321 contact.updateNameData(gender, strippedToken, null, null);
\r
324 case 3: // Family name
\r
325 assert(contact instanceof Contact) : "First token was not boolean";
\r
326 assert(gender != '?') : "Gender is not detected.";
\r
329 contact.updateNameData(gender, null, strippedToken, null);
\r
332 case 4: // Company name
\r
333 assert(contact instanceof Contact) : "First token was not boolean";
\r
334 assert(gender != '?') : "Gender is not detected.";
\r
337 contact.updateNameData(gender, null, null, strippedToken);
\r
340 case 5: // Street number
\r
341 assert(contact instanceof Contact) : "First token was not boolean";
\r
344 contact.updateAddressData(strippedToken, 0, null, null);
\r
347 case 6: // ZIP code
\r
348 assert(contact instanceof Contact) : "First token was not boolean";
\r
351 contact.updateAddressData(null, num, null, null);
\r
354 case 7: // City name
\r
355 assert(contact instanceof Contact) : "First token was not boolean";
\r
358 contact.updateAddressData(null, 0, strippedToken, null);
\r
361 case 8: // Country code
\r
362 assert(contact instanceof Contact) : "First token was not boolean";
\r
365 contact.updateAddressData(null, 0, null, strippedToken);
\r
368 case 9: // Phone number
\r
369 assert(contact instanceof Contact) : "First token was not boolean";
\r
372 contact.updateOtherData(strippedToken, null, null, null, null, null);
\r
375 case 10: // Fax number
\r
376 assert(contact instanceof Contact) : "First token was not boolean";
\r
379 contact.updateOtherData(null, strippedToken, null, null, null, null);
\r
382 case 11: // Cellphone number
\r
383 assert(contact instanceof Contact) : "First token was not boolean";
\r
386 contact.updateOtherData(null, null, strippedToken, null, null, null);
\r
389 case 12: // Email address
\r
390 assert(contact instanceof Contact) : "First token was not boolean";
\r
393 contact.updateOtherData(null, null, null, strippedToken, null, null);
\r
396 case 13: // Birthday
\r
397 assert(contact instanceof Contact) : "First token was not boolean";
\r
400 contact.updateOtherData(null, null, null, null, strippedToken, null);
\r
403 case 14: // Birthday
\r
404 assert(contact instanceof Contact) : "First token was not boolean";
\r
407 contact.updateOtherData(null, null, null, null, null, strippedToken);
\r
410 default: // New data entry
\r
411 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count));
\r
415 // Increment counter for next round
\r
419 // Is the contact read?
\r
420 if (contact instanceof Contact) {
\r
422 assert(list.add(contact));
\r
426 // Return finished list
\r
427 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size()));
\r
432 * Reads a line from file base
\r
434 * @return Read line from file
\r
436 private String readLine () {
\r
438 String input = null;
\r
441 input = this.storageFile.readLine();
\r
442 } catch (final IOException ex) {
\r
443 this.getLogger().catching(ex);
\r
446 // Return read string or null
\r