]> git.mxchange.org Git - jaddressbook-lib.git/blob - Addressbook/src/org/mxchange/addressbook/database/backend/csv/Base64CsvDatabaseBackend.java
39eef663fd24ad67372e81fbf789bf95d17bd3bd
[jaddressbook-lib.git] / Addressbook / src / org / mxchange / addressbook / database / backend / csv / Base64CsvDatabaseBackend.java
1 /*
2  * Copyright (C) 2015 Roland Haeder
3  *
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.
8  *
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.
13  *
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/>.
16  */
17 package org.mxchange.addressbook.database.backend.csv;
18
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 org.mxchange.addressbook.FrameworkInterface;
30 import org.mxchange.addressbook.contact.Contact;
31 import org.mxchange.addressbook.database.backend.BaseDatabaseBackend;
32 import org.mxchange.addressbook.database.backend.DatabaseBackend;
33 import org.mxchange.addressbook.database.frontend.DatabaseFrontend;
34 import org.mxchange.addressbook.database.storage.Storeable;
35 import org.mxchange.addressbook.database.storage.csv.StoreableCsv;
36 import org.mxchange.addressbook.exceptions.BadTokenException;
37
38 /**
39  * A database backend with CSV file as storage implementation
40  *
41  * @author Roland Haeder
42  */
43 public class Base64CsvDatabaseBackend extends BaseDatabaseBackend implements DatabaseBackend {
44
45         /**
46          * Output stream for this storage engine
47          */
48         private RandomAccessFile storageFile;
49
50         /**
51          * Constructor with table name
52          *
53          * @param tableName Name of "table"
54          * @param wrapper Wrapper instance to call back
55          */
56         public Base64CsvDatabaseBackend (final String tableName, final DatabaseFrontend wrapper) {
57                 // Trace message
58                 this.getLogger().trace(MessageFormat.format("tableName={0},wrapper={1}", tableName, wrapper)); //NOI18N
59
60                 // Debug message
61                 this.getLogger().debug(MessageFormat.format("Trying to initialize table {0} ...", tableName)); //NOI18N
62
63                 // Set table name here, too
64                 this.setTableName(tableName);
65
66                 // Set wrapper here
67                 this.setWrapper(wrapper);
68
69                 // Construct file name
70                 String fileName = String.format("data/table_%s.b64", tableName); //NOI18N
71
72                 // Debug message
73                 this.getLogger().debug(MessageFormat.format("Trying to open file {0} ...", fileName)); //NOI18N
74
75                 try {
76                         // Try to initialize the storage (file instance)
77                         this.storageFile = new RandomAccessFile(fileName, "rw"); //NOI18N
78                 } catch (final FileNotFoundException ex) {
79                         // Did not work
80                         this.getLogger().error(MessageFormat.format("File {0} cannot be opened: {1}", fileName, ex.toString())); //NOI18N
81                         System.exit(1);
82                 }
83
84                 // Output message
85                 this.getLogger().debug(MessageFormat.format("Database for {0} has been initialized.", tableName)); //NOI18N
86         }
87
88         /**
89          * This database backend does not need to connect
90          */
91         @Override
92         public void connectToDatabase () throws SQLException {
93                 // Empty body
94         }
95
96         /**
97          * Shuts down this backend
98          */
99         @Override
100         public void doShutdown () {
101                 // Trace message
102                 this.getLogger().trace("CALLED!"); //NOI18N
103
104                 try {
105                         // Close file
106                         this.getStorageFile().close();
107                 } catch (final IOException ex) {
108                         // Abort program
109                         this.abortProgramWithException(ex);
110                 }
111
112                 // Trace message
113                 this.getLogger().trace("EXIT!"); //NOI18N
114         }
115
116         /**
117          * Some "getter" for row index from given boolean row value
118          *
119          * @param columnName Name of column
120          * @param bool Boolean value to look for
121          * @return Row index
122          */
123         @Override
124         public int getRowIndexFromColumn (final String columnName, final boolean bool) {
125                 // Trace message
126                 this.getLogger().trace(MessageFormat.format("columnName={0},bool={1} - CALLED!", columnName, bool)); //NOI18N
127
128                 // Row indexes start with zero
129                 int rowIndex = 0;
130
131                 // First rewind
132                 this.rewind();
133
134                 // Try to find the proper row
135                 while (!this.isEndOfFile()) {
136                         // Read line
137                         String line = this.readLine();
138
139                         // Debug message
140                         this.getLogger().debug(MessageFormat.format("line={0}", line));
141
142                         // Callback the wrapper to handle parsing
143                         try {
144                                 Storeable storeable = this.getWrapper().parseLineToStoreable(line);
145
146                                 // Debug message
147                                 this.getLogger().debug(MessageFormat.format("storeable={0}", storeable));
148
149                                 // Is the value qual
150                                 if (storeable.isValueEqual(columnName, bool)) {
151                                         // Debug message
152                                         this.getLogger().debug(MessageFormat.format("Found storeable={0} for columnName={1} and bool={2}", storeable, columnName, bool));
153
154                                         // Found it
155                                         break;
156                                 }
157                         } catch (final BadTokenException ex) {
158                                 // Bad token found
159                                 this.abortProgramWithException(ex);
160                         }
161
162                         // Count up
163                         rowIndex++;
164                 }
165
166                 // Return it
167                 return rowIndex;
168         }
169
170         /**
171          * Some "getter" for total row count
172          *
173          * @return Total row count
174          */
175         @Override
176         public int getTotalCount () {
177                 // Trace message
178                 this.getLogger().trace("CALLED!"); //NOI18N
179
180                 try {
181                         // Do a deprecated call
182                         // @todo this needs rewrite!
183                         return this.readList().size();
184                 } catch (final BadTokenException ex) {
185                         this.abortProgramWithException(ex);
186                 }
187
188                 // Invalid return
189                 this.getLogger().trace("Returning -1 ... : EXIT!"); //NOI18N
190                 return -1;
191         }
192
193         /**
194          * Checks whether at least one row is found with given boolean value.
195          *
196          * @param columnName Column to check for boolean value
197          * @param bool Boolean value to check
198          * @return Whether boolean value is found and returns at least one row
199          */
200         @Override
201         public boolean isRowFound (final String columnName, final boolean bool) {
202                 // Trace message
203                 this.getLogger().trace(MessageFormat.format("columnName={0},bool={1} - CALLED!", columnName, bool)); //NOI18N
204
205                 // Is at least one entry found?
206                 if (this.getTotalCount() == 0) {
207                         // No entry found at all
208                         return false;
209                 }
210
211                 // Default is not found
212                 boolean isFound = false;
213
214                 // Firsr rewind
215                 this.rewind();
216
217                 // Then loop through all lines
218                 while (!this.isEndOfFile()) {
219                         // Read line
220                         String line = this.readLine();
221
222                         // Debug message
223                         this.getLogger().debug(MessageFormat.format("line={0}", line));
224
225                         try {
226                                 // And parse it to a Contact instance
227                                 Contact contact = (Contact) this.getWrapper().parseLineToStoreable(line);
228
229                                 // Debug message
230                                 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
231
232                                 // This should not be null
233                                 if (contact == null) {
234                                         // Throw exception
235                                         throw new NullPointerException("contact is null");
236                                 }
237
238                                 // Now let the contact object check if it has such attribute
239                                 if (contact.isValueEqual(columnName, bool)) {
240                                         // Yes, it is set
241                                         isFound = true;
242                                         break;
243                                 }
244                         } catch (final BadTokenException ex) {
245                                 // Don't continue with bad data
246                                 this.abortProgramWithException(ex);
247                         }
248                 }
249
250                 // Trace message
251                 this.getLogger().trace(MessageFormat.format("isFound={0} - EXIT!", isFound));
252
253                 // Return result
254                 return isFound;
255         }
256
257         /**
258          * Gets an iterator for contacts
259          *
260          * @return Iterator for contacts
261          * @throws org.mxchange.addressbook.exceptions.BadTokenException If the
262          * underlaying method has found an invalid token
263          */
264         @Override
265         public Iterator<? extends Storeable> iterator () throws BadTokenException {
266                 // Trace message
267                 this.getLogger().trace("CALLED!"); //NOI18N
268
269                 /*
270                  * Then read the file into RAM (yes, not perfect for >1000 entries ...)
271                  * and get a List back.
272                  */
273                 List<? extends Storeable> list = this.readList();
274
275                 // List must be set
276                 assert (list instanceof List) : "list has not been set."; //NOI18N
277
278                 // Trace message
279                 this.getLogger().trace(MessageFormat.format("list.iterator()={0} - EXIT!", list.iterator())); //NOI18N
280
281                 // Get iterator from list and return it
282                 return list.iterator();
283         }
284
285         /**
286          * Get length of underlaying file
287          *
288          * @return Length of underlaying file
289          */
290         @Override
291         public long length () {
292                 long length = 0;
293
294                 try {
295                         length = this.getStorageFile().length();
296                         this.getLogger().debug(MessageFormat.format("length={0}", length)); //NOI18N
297                 } catch (final IOException ex) {
298                         // Length cannot be determined
299                         // Abort program
300                         this.abortProgramWithException(ex);
301                 }
302
303                 // Return result
304                 this.getLogger().trace(MessageFormat.format("length={0} : EXIT!", length)); //NOI18N
305                 return length;
306         }
307
308         /**
309          * Reads a single row from database.
310          *
311          * @param rowIndex Row index (or how much to skip)
312          * @return A Storeable instance
313          * @throws org.mxchange.addressbook.exceptions.BadTokenException If a token
314          * was badly formatted
315          */
316         @Override
317         public Storeable readRow (final int rowIndex) throws BadTokenException {
318                 // First rewind
319                 this.rewind();
320
321                 // Intialize variables
322                 int count = -1;
323                 Storeable storeable = null;
324
325                 // Read all rows
326                 while (!this.isEndOfFile() || (count < rowIndex)) {
327                         // Read row
328                         String line = this.readLine();
329
330                         // Debug message
331                         this.getLogger().debug(MessageFormat.format("line={0}", line));
332
333                         // Callback the wrapper to handle parsing
334                         storeable = this.getWrapper().parseLineToStoreable(line);
335
336                         // Debug message
337                         this.getLogger().debug(MessageFormat.format("storeable={0}", storeable));
338
339                         // Increment counter
340                         count++;
341                 }
342
343                 // Trace message
344                 this.getLogger().trace(MessageFormat.format("storeable={0} - EXIT!", storeable));
345                 // Return found element
346                 return storeable;
347         }
348
349         /**
350          * Rewinds backend
351          */
352         @Override
353         public void rewind () {
354                 // Trace message
355                 this.getLogger().trace("CALLED!"); //NOI18N
356
357                 try {
358                         // Rewind underlaying database file
359                         this.getStorageFile().seek(0);
360                 } catch (final IOException ex) {
361                         // Abort program
362                         this.abortProgramWithException(ex);
363                 }
364
365                 // Trace message
366                 this.getLogger().trace("EXIT!"); //NOI18N
367         }
368
369         /**
370          * Stores given object by "visiting" it
371          *
372          * @param object An object implementing Storeable
373          * @throws java.io.IOException From "inner" class
374          */
375         @Override
376         public void store (final Storeable object) throws IOException {
377                 // Trace message
378                 this.getLogger().trace(MessageFormat.format("object={0} - CALLED!", object)); //NOI18N
379
380                 // Object must not be null
381                 if (object == null) {
382                         // Abort here
383                         throw new NullPointerException("object is null"); //NOI18N
384                 }
385
386                 // Make sure the instance is there (DataOutput flawor)
387                 assert (this.storageFile instanceof DataOutput);
388
389                 // Try to cast it, this will fail if the interface is not implemented
390                 StoreableCsv csv = (StoreableCsv) object;
391
392                 // Now get a string from the object that needs to be stored
393                 String str = csv.getCsvStringFromStoreableObject();
394
395                 // Debug message
396                 this.getLogger().debug(MessageFormat.format("str({0})={1}", str.length(), str)); //NOI18N
397
398                 // Encode line in BASE-64
399                 byte[] encoded = Base64.getEncoder().encode(str.getBytes());
400
401                 // The string is now a valid CSV string
402                 this.getStorageFile().write(encoded);
403
404                 // Trace message
405                 this.getLogger().trace("EXIT!"); //NOI18N
406         }
407
408         /**
409          * Adds given contact to list
410          *
411          * @param instance An instance of FrameworkInterface to add
412          * @param list List instance
413          */
414         private void addToList (final Storeable instance, final List<Storeable> list) {
415                 // Trace message
416                 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", instance)); //NOI18N
417
418                 // No null here
419                 if (instance == null) {
420                         // Throw exception
421                         throw new NullPointerException("contact is null"); //NOI18N
422                 } else if (list == null) {
423                         // Throw exception
424                         throw new NullPointerException("list is null"); //NOI18N
425                 }
426
427                 // Debug message
428                 this.getLogger().debug(MessageFormat.format("contact={0}", instance)); //NOI18N
429
430                 // Is the contact read?
431                 if (instance instanceof FrameworkInterface) {
432                         // Then add it
433                         boolean added = list.add(instance);
434
435                         // Debug message
436                         this.getLogger().debug(MessageFormat.format("contact={0} added={1}", instance, added)); //NOI18N
437
438                         // Has it been added?
439                         if (!added) {
440                                 // Not added
441                                 this.getLogger().warn("Contact object has not been added."); //NOI18N
442                         }
443                 }
444
445                 // Trace message
446                 this.getLogger().trace("EXIT!"); //NOI18N
447         }
448
449         /**
450          * Returns storage file
451          *
452          * @return Storage file instance
453          */
454         private RandomAccessFile getStorageFile () {
455                 return this.storageFile;
456         }
457
458         /**
459          * Checks whether end of file has been reached
460          *
461          * @return Whether lines are left to read
462          */
463         private boolean isEndOfFile () {
464                 // Default is EOF
465                 boolean isEof = true;
466
467                 try {
468                         isEof = (this.getStorageFile().getFilePointer() >= this.length());
469                 } catch (final IOException ex) {
470                         // Length cannot be determined
471                         this.getLogger().catching(ex);
472                 }
473
474                 // Return status
475                 this.getLogger().trace(MessageFormat.format("isEof={0} : EXIT!", isEof)); //NOI18N
476                 return isEof;
477         }
478
479         /**
480          * Reads a line from file base
481          *
482          * @return Read line from file
483          */
484         private String readLine () {
485                 // Trace message
486                 this.getLogger().trace("CALLED!"); //NOI18N
487
488                 // Init input
489                 String input = null;
490
491                 try {
492                         // Read single line
493                         String base64 = this.getStorageFile().readLine();
494
495                         // Is the line null?
496                         if (base64 == null) {
497                                 // Then throw NPE here
498                                 throw new NullPointerException("base64 is null");
499                         }
500
501                         // Decode BASE-64
502                         byte[] decoded = Base64.getDecoder().decode(base64);
503
504                         // Convert to string
505                         input = new String(decoded);
506                 } catch (final IOException ex) {
507                         this.getLogger().catching(ex);
508                 }
509
510                 // Trace message
511                 this.getLogger().trace(MessageFormat.format("input={0} - EXIT!", input)); //NOI18N
512
513                 // Return read string or null
514                 return input;
515         }
516
517         /**
518          * Reads the database file, if available, and adds all read lines into the
519          * list.
520          *
521          * @return A list with Contact instances
522          */
523         private List<? extends Storeable> readList () throws BadTokenException {
524                 this.getLogger().trace("CALLED!"); //NOI18N
525
526                 // First rewind
527                 this.rewind();
528
529                 // Get file size and divide it by 140 (possible average length of one line)
530                 int lines = Math.round(this.length() / 140 + 0.5f);
531
532                 // Debug message
533                 this.getLogger().debug(MessageFormat.format("lines={0}", lines)); //NOI18N
534
535                 // Instance list
536                 // @TODO The maximum length could be guessed from file size?
537                 List<Storeable> list = new ArrayList<>(lines);
538
539                 // Init variables
540                 String line;
541                 Storeable instance = null;
542
543                 // Read all lines
544                 while (!this.isEndOfFile()) {
545                         // Then read a line
546                         line = this.readLine();
547
548                         // Parse line
549                         instance = this.getWrapper().parseLineToStoreable(line);
550
551                         // The contact instance should be there now
552                         assert (instance instanceof FrameworkInterface) : MessageFormat.format("instance is not set: {0}", instance); //NOI18N
553
554                         // Add contact
555                         this.addToList(instance, list);
556                 }
557
558                 // Return finished list
559                 this.getLogger().trace(MessageFormat.format("list.size()={0} : EXIT!", list.size())); //NOI18N
560                 return list;
561         }
562 }