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.frontend.contact;
19 import java.io.IOException;
20 import java.sql.SQLException;
21 import java.text.MessageFormat;
22 import java.util.Iterator;
23 import java.util.StringTokenizer;
24 import org.mxchange.addressbook.contact.book.BookContact;
25 import org.mxchange.addressbook.contact.user.UserContact;
26 import org.mxchange.addressbook.database.contact.AddressbookContactDatabaseConstants;
27 import org.mxchange.addressbook.exceptions.ContactAlreadyAddedException;
28 import org.mxchange.addressbook.manager.contact.AddressbookContactManager;
29 import org.mxchange.jcore.contact.Contact;
30 import org.mxchange.jcore.contact.Gender;
31 import org.mxchange.jcore.database.frontend.BaseDatabaseFrontend;
32 import org.mxchange.jcore.database.storage.Storeable;
33 import org.mxchange.jcore.exceptions.BadTokenException;
34 import org.mxchange.jcore.exceptions.UnsupportedDatabaseBackendException;
37 * Stores and retrieves Contact instances
39 * @author Roland Haeder
41 public class AddressbookContactDatabaseFrontend extends BaseDatabaseFrontend implements AddressbookContactFrontend {
44 * Constructor which accepts a contact manager
46 * @param manager Manager instance
48 public AddressbookContactDatabaseFrontend (final AddressbookContactManager manager) {
49 // Call own constructor
53 this.getLogger().trace(MessageFormat.format("manager={0} - CALLED!", manager)); //NOI18N
55 // Manager instance must not be null
56 if (manager == null) {
58 throw new NullPointerException("manager is null"); //NOI18N
61 // Set contact manager
62 this.setContactManager(manager);
68 protected AddressbookContactDatabaseFrontend () {
70 this.getLogger().trace("CALLED!"); //NOI18N
73 this.setTableName("contacts"); //NOI18N
78 } catch (final UnsupportedDatabaseBackendException | SQLException ex) {
80 this.abortProgramWithException(ex);
85 * Adds given contact instance to database
87 * @param contact Contact instance
88 * @throws org.mxchange.addressbook.exceptions.ContactAlreadyAddedException If the contact instance is already found
91 public void addContact (final Contact contact) throws ContactAlreadyAddedException {
93 this.getLogger().trace("CALLED!"); //NOI18N
95 // Make sure the contact is set
96 if (contact == null) {
98 throw new NullPointerException("contact is null"); //NOI18N
102 // First check if the contact is there
103 if (this.isContactFound(contact)) {
105 throw new ContactAlreadyAddedException(contact);
109 this.getBackend().store((Storeable) contact);
110 } catch (final IOException | BadTokenException ex) {
112 this.abortProgramWithException(ex);
116 this.getLogger().trace("CALLED!"); //NOI18N
120 * Shuts down the database layer
123 public void doShutdown () {
125 this.getLogger().trace("CALLED!"); //NOI18N
128 this.getBackend().doShutdown();
131 this.getLogger().trace("EXIT!"); //NOI18N
135 * Some "getter" for total contact count
137 * @return Total contact count
140 public int getContactsCount () throws SQLException {
141 // And deligate to backend
142 return this.getBackend().getTotalCount(); //NOI18N
146 * Some "getter" for own contact instance
148 * @return Own contact instance
151 public Contact getOwnContact () {
153 this.getLogger().trace("CALLED!"); //NOI18N
155 // Get row index back from backend
156 int rowIndex = this.getBackend().getRowIndexFromColumn(AddressbookContactDatabaseConstants.COLUMN_NAME_OWN_CONTACT, true);
159 this.getLogger().debug(MessageFormat.format("rowIndex={0}", rowIndex));
162 Contact contact = null;
165 // Now simply read the row
166 contact = (Contact) this.getBackend().readRow(rowIndex);
167 } catch (final BadTokenException ex) {
169 this.abortProgramWithException(ex);
173 this.getLogger().trace(MessageFormat.format("contact={0} - EXIT!", contact));
180 * Checks if given Contact is found
182 * @param contact Contact instance to check
183 * @return Whether the given Contact instance is found
186 public boolean isContactFound (final Contact contact) throws BadTokenException {
188 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
190 // contact should not be null
191 if (contact == null) {
193 throw new NullPointerException("contact is null"); //NOI18N
196 // Default is not found
197 boolean isFound = false;
200 Iterator<? extends Storeable> iterator = this.getBackend().iterator();
203 while (iterator.hasNext()) {
205 Contact c = (Contact) iterator.next();
208 this.getLogger().debug(MessageFormat.format("c={0},contact={1}", c, contact)); //NOI18N
211 if (c.equals(contact)) {
219 this.getLogger().trace(MessageFormat.format("isFound={0} - EXIT!", isFound)); //NOI18N
226 * Checks whether own contact is found in database
228 * @return Whether own contact is found
231 public boolean isOwnContactFound () throws SQLException {
232 // Deligate this call to backend
233 return this.getBackend().isRowFound(AddressbookContactDatabaseConstants.COLUMN_NAME_OWN_CONTACT, true);
237 * Parses given line from database backend into a Storeable instance. Please
238 * note that not all backends need this.
240 * @param line Line from database backend
241 * @return A Storeable instance
244 public Storeable parseLineToStoreable (final String line) throws BadTokenException {
246 this.getLogger().trace(MessageFormat.format("line={0} - CALLED!", line)); //NOI18N
249 Contact contact = this.parseLineToContact(line);
252 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
255 return (Storeable) contact;
259 * Reads a single row and parses it to a contact instance
261 * @param rowIndex Row index (also how much to skip)
262 * @return Contact instance
265 public Contact readSingleContact (final int rowIndex) {
267 // Deligate this to backend instance
268 return (Contact) this.getBackend().readRow(rowIndex);
269 } catch (final BadTokenException ex) {
271 this.abortProgramWithException(ex);
274 // Bad state, should not be reached
275 throw new IllegalStateException("This should not be reached");
279 * Parses given line and creates a Contact instance
281 * @param line Raw line to parse
283 * @return Contact instance
285 private Contact parseLineToContact (final String line) throws BadTokenException {
287 this.getLogger().trace(MessageFormat.format("line={0} - CALLED!", line)); //NOI18N
289 // Init A lot variables
292 Gender gender = null;
294 Contact contact = null;
297 this.getLogger().debug(MessageFormat.format("line={0}", line)); //NOI18N
300 // @TODO Move this into separate method
301 StringTokenizer tokenizer = new StringTokenizer(line, ";"); //NOI18N
307 // The tokens are now available, so get all
308 while (tokenizer.hasMoreElements()) {
314 String token = tokenizer.nextToken();
316 // If char " is at pos 2 (0,1,2), then cut it of there
317 if ((token.charAt(0) != '"') && (token.charAt(2) == '"')) {
318 // UTF-8 writer characters found
319 token = token.substring(2);
323 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
325 // Verify token, it must have double-quotes on each side
326 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) { //NOI18N
327 // Something bad was read
328 throw new BadTokenException(token, count); //NOI18N
331 // All fine, so remove it
332 String strippedToken = token.substring(1, token.length() - 1);
334 // Is the string's content "null"?
335 if (strippedToken.equals("null")) { //NOI18N
337 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken)); //NOI18N
339 // This needs to be set to null
340 strippedToken = null;
344 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken)); //NOI18N
346 // Now, let's try a number check, if no null
347 if (strippedToken != null) {
348 // Okay, no null, maybe the string bears a decimal number?
350 num = Long.valueOf(strippedToken);
353 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken)); //NOI18N
354 } catch (final NumberFormatException ex) {
355 // No number, then set default
360 // Now, let's try a boolean check, if no null
361 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) { //NOI18N
363 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken)); //NOI18N
365 // parseBoolean() is relaxed, so no exceptions
366 bool = Boolean.valueOf(strippedToken);
370 this.getLogger().debug(MessageFormat.format("strippedToken={0},num={1},bool={2}", strippedToken, num, bool)); //NOI18N
372 // Now, let's try a gender check, if no null
373 if ((strippedToken != null) && (num == null) && (bool == null) && (Gender.valueOf(strippedToken) instanceof Gender)) { //NOI18N
374 // Get first character
375 gender = Gender.valueOf(strippedToken);
378 this.getLogger().debug(MessageFormat.format("strippedToken={0},gender={1}", strippedToken, gender)); //NOI18N
380 // This instance must be there
381 assert (gender instanceof Gender) : MessageFormat.format("gender is not set by Gender.fromChar({0})", strippedToken); //NOI18N
384 // Now it depends on the counter which position we need to check
386 case 0: // isOwnContact
387 assert ((bool instanceof Boolean));
390 this.getLogger().debug(MessageFormat.format("bool={0}", bool)); //NOI18N
392 // Is it own contact?
395 this.getLogger().debug("Creating UserContact object ..."); //NOI18N
398 contact = new UserContact();
401 this.getLogger().debug("Creating BookContact object ..."); //NOI18N
404 contact = new BookContact();
409 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
412 contact.setGender(gender);
416 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
417 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
420 contact.setSurname(strippedToken);
423 case 3: // Family name
424 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
425 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
428 contact.setFamilyName(strippedToken);
431 case 4: // Company name
432 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
433 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
436 contact.setCompanyName(strippedToken);
439 case 5: // Street number
440 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
443 contact.setHouseNumber(num);
447 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
450 contact.setZipCode(num);
454 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
457 contact.setCity(strippedToken);
460 case 8: // Country code
461 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
464 contact.setCountryCode(strippedToken);
467 case 9: // Phone number
468 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
471 contact.setPhoneNumber(strippedToken);
474 case 10: // Fax number
475 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
478 contact.setFaxNumber(strippedToken);
481 case 11: // Cellphone number
482 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
485 contact.setCellphoneNumber(strippedToken);
488 case 12: // Email address
489 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
492 contact.setEmailAddress(strippedToken);
496 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
499 contact.setBirthday(strippedToken);
503 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
506 contact.setComment(strippedToken);
509 default: // New data entry
510 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count)); //NOI18N
514 // Increment counter for next round
519 this.getLogger().trace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
521 // Return finished instance