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.criteria.searchable.SearchCriteria;
32 import org.mxchange.jcore.criteria.searchable.SearchableCritera;
33 import org.mxchange.jcore.database.frontend.BaseDatabaseFrontend;
34 import org.mxchange.jcore.database.result.Result;
35 import org.mxchange.jcore.database.storage.Storeable;
36 import org.mxchange.jcore.exceptions.BadTokenException;
37 import org.mxchange.jcore.exceptions.UnsupportedDatabaseBackendException;
40 * Stores and retrieves Contact instances
42 * @author Roland Haeder
44 public class AddressbookContactDatabaseFrontend extends BaseDatabaseFrontend implements AddressbookContactFrontend {
47 * Constructor which accepts a contact manager
49 * @param manager Manager instance
51 public AddressbookContactDatabaseFrontend (final AddressbookContactManager manager) {
52 // Call own constructor
56 this.getLogger().trace(MessageFormat.format("manager={0} - CALLED!", manager)); //NOI18N
58 // Manager instance must not be null
59 if (manager == null) {
61 throw new NullPointerException("manager is null"); //NOI18N
64 // Set contact manager
65 this.setContactManager(manager);
70 * @throws org.mxchange.jcore.exceptions.UnsupportedDatabaseBackendException If the database backend is not supported
71 * @throws java.sql.SQLException Any SQL exception from e.g. MySQL connector
73 protected AddressbookContactDatabaseFrontend () throws UnsupportedDatabaseBackendException, SQLException {
75 this.getLogger().trace("CALLED!"); //NOI18N
78 this.setTableName("contacts"); //NOI18N
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 // Get search criteria instance
233 SearchableCritera critera = new SearchCriteria();
236 critera.addCriteria(AddressbookContactDatabaseConstants.COLUMN_NAME_OWN_CONTACT, true);
239 Result<? extends Storeable> result = this.getBackend().doSelectByCriteria(critera);
241 // Deligate this call to backend
242 return result.hasNext();
246 * Parses given line from database backend into a Storeable instance. Please
247 * note that not all backends need this.
249 * @param line Line from database backend
250 * @return A Storeable instance
253 public Storeable parseLineToStoreable (final String line) throws BadTokenException {
255 this.getLogger().trace(MessageFormat.format("line={0} - CALLED!", line)); //NOI18N
258 Contact contact = this.parseLineToContact(line);
261 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
264 return (Storeable) contact;
268 * Reads a single row and parses it to a contact instance
270 * @param rowIndex Row index (also how much to skip)
271 * @return Contact instance
274 public Contact readSingleContact (final int rowIndex) {
276 // Deligate this to backend instance
277 return (Contact) this.getBackend().readRow(rowIndex);
278 } catch (final BadTokenException ex) {
280 this.abortProgramWithException(ex);
283 // Bad state, should not be reached
284 throw new IllegalStateException("This should not be reached");
288 * Parses given line and creates a Contact instance
290 * @param line Raw line to parse
292 * @return Contact instance
294 private Contact parseLineToContact (final String line) throws BadTokenException {
296 this.getLogger().trace(MessageFormat.format("line={0} - CALLED!", line)); //NOI18N
298 // Init A lot variables
301 Gender gender = null;
303 Contact contact = null;
306 this.getLogger().debug(MessageFormat.format("line={0}", line)); //NOI18N
309 // @TODO Move this into separate method
310 StringTokenizer tokenizer = new StringTokenizer(line, ";"); //NOI18N
316 // The tokens are now available, so get all
317 while (tokenizer.hasMoreElements()) {
323 String token = tokenizer.nextToken();
325 // If char " is at pos 2 (0,1,2), then cut it of there
326 if ((token.charAt(0) != '"') && (token.charAt(2) == '"')) {
327 // UTF-8 writer characters found
328 token = token.substring(2);
332 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
334 // Verify token, it must have double-quotes on each side
335 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) { //NOI18N
336 // Something bad was read
337 throw new BadTokenException(token, count); //NOI18N
340 // All fine, so remove it
341 String strippedToken = token.substring(1, token.length() - 1);
343 // Is the string's content "null"?
344 if (strippedToken.equals("null")) { //NOI18N
346 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken)); //NOI18N
348 // This needs to be set to null
349 strippedToken = null;
353 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken)); //NOI18N
355 // Now, let's try a number check, if no null
356 if (strippedToken != null) {
357 // Okay, no null, maybe the string bears a decimal number?
359 num = Long.valueOf(strippedToken);
362 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken)); //NOI18N
363 } catch (final NumberFormatException ex) {
364 // No number, then set default
369 // Now, let's try a boolean check, if no null
370 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) { //NOI18N
372 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken)); //NOI18N
374 // parseBoolean() is relaxed, so no exceptions
375 bool = Boolean.valueOf(strippedToken);
379 this.getLogger().debug(MessageFormat.format("strippedToken={0},num={1},bool={2}", strippedToken, num, bool)); //NOI18N
381 // Now, let's try a gender check, if no null
382 if ((strippedToken != null) && (num == null) && (bool == null) && (Gender.valueOf(strippedToken) instanceof Gender)) { //NOI18N
383 // Get first character
384 gender = Gender.valueOf(strippedToken);
387 this.getLogger().debug(MessageFormat.format("strippedToken={0},gender={1}", strippedToken, gender)); //NOI18N
389 // This instance must be there
390 assert (gender instanceof Gender) : MessageFormat.format("gender is not set by Gender.fromChar({0})", strippedToken); //NOI18N
393 // Now it depends on the counter which position we need to check
395 case 0: // isOwnContact
396 assert ((bool instanceof Boolean));
399 this.getLogger().debug(MessageFormat.format("bool={0}", bool)); //NOI18N
401 // Is it own contact?
404 this.getLogger().debug("Creating UserContact object ..."); //NOI18N
407 contact = new UserContact();
410 this.getLogger().debug("Creating BookContact object ..."); //NOI18N
413 contact = new BookContact();
418 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
421 contact.setGender(gender);
425 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
426 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
429 contact.setSurname(strippedToken);
432 case 3: // Family name
433 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
434 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
437 contact.setFamilyName(strippedToken);
440 case 4: // Company name
441 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
442 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
445 contact.setCompanyName(strippedToken);
448 case 5: // Street number
449 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
452 contact.setHouseNumber(num);
456 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
459 contact.setZipCode(num);
463 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
466 contact.setCity(strippedToken);
469 case 8: // Country code
470 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
473 contact.setCountryCode(strippedToken);
476 case 9: // Phone number
477 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
480 contact.setPhoneNumber(strippedToken);
483 case 10: // Fax number
484 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
487 contact.setFaxNumber(strippedToken);
490 case 11: // Cellphone number
491 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
494 contact.setCellphoneNumber(strippedToken);
497 case 12: // Email address
498 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
501 contact.setEmailAddress(strippedToken);
505 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
508 contact.setBirthday(strippedToken);
512 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
515 contact.setComment(strippedToken);
518 default: // New data entry
519 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count)); //NOI18N
523 // Increment counter for next round
528 this.getLogger().trace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
530 // Return finished instance