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
50 * @throws org.mxchange.jcore.exceptions.UnsupportedDatabaseBackendException If the database backend is not supported
51 * @throws java.sql.SQLException If an SQL error occurs
53 public AddressbookContactDatabaseFrontend (final AddressbookContactManager manager) throws UnsupportedDatabaseBackendException, SQLException {
54 // Call own constructor
58 this.getLogger().trace(MessageFormat.format("manager={0} - CALLED!", manager)); //NOI18N
60 // Manager instance must not be null
61 if (manager == null) {
63 throw new NullPointerException("manager is null"); //NOI18N
66 // Set contact manager
67 this.setContactManager(manager);
71 * Default but protected constructor
72 * @throws org.mxchange.jcore.exceptions.UnsupportedDatabaseBackendException If the database backend is not supported
73 * @throws java.sql.SQLException Any SQL exception from e.g. MySQL connector
75 protected AddressbookContactDatabaseFrontend () throws UnsupportedDatabaseBackendException, SQLException {
77 this.getLogger().trace("CALLED!"); //NOI18N
80 this.setTableName("contacts"); //NOI18N
87 * Adds given contact instance to database
89 * @param contact Contact instance
90 * @throws org.mxchange.addressbook.exceptions.ContactAlreadyAddedException If the contact instance is already found
93 public void addContact (final Contact contact) throws ContactAlreadyAddedException {
95 this.getLogger().trace("CALLED!"); //NOI18N
97 // Make sure the contact is set
98 if (contact == null) {
100 throw new NullPointerException("contact is null"); //NOI18N
104 // First check if the contact is there
105 if (this.isContactFound(contact)) {
107 throw new ContactAlreadyAddedException(contact);
111 this.getBackend().store((Storeable) contact);
112 } catch (final IOException | BadTokenException ex) {
114 this.abortProgramWithException(ex);
118 this.getLogger().trace("CALLED!"); //NOI18N
122 * Shuts down the database layer
125 public void doShutdown () throws SQLException, IOException {
127 this.getLogger().trace("CALLED!"); //NOI18N
130 this.getBackend().doShutdown();
133 this.getLogger().trace("EXIT!"); //NOI18N
137 public Object emptyStringToNull (final String key, final Object value) {
138 throw new UnsupportedOperationException(MessageFormat.format("Not supported yet: key={0},value={1}", key, value));
142 * Some "getter" for total contact count
144 * @return Total contact count
147 public int getContactsCount () throws SQLException {
148 // And deligate to backend
149 return this.getBackend().getTotalCount(); //NOI18N
153 * Some "getter" for own contact instance
155 * @return Own contact instance
158 public Contact getOwnContact () {
160 this.getLogger().trace("CALLED!"); //NOI18N
162 // Get row index back from backend
163 int rowIndex = this.getBackend().getRowIndexFromColumn(AddressbookContactDatabaseConstants.COLUMN_NAME_OWN_CONTACT, true);
166 this.getLogger().debug(MessageFormat.format("rowIndex={0}", rowIndex));
169 Contact contact = null;
172 // Now simply read the row
173 contact = (Contact) this.getBackend().readRow(rowIndex);
174 } catch (final BadTokenException ex) {
176 this.abortProgramWithException(ex);
180 this.getLogger().trace(MessageFormat.format("contact={0} - EXIT!", contact));
187 * Checks if given Contact is found
189 * @param contact Contact instance to check
190 * @return Whether the given Contact instance is found
193 public boolean isContactFound (final Contact contact) throws BadTokenException {
195 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
197 // contact should not be null
198 if (contact == null) {
200 throw new NullPointerException("contact is null"); //NOI18N
203 // Default is not found
204 boolean isFound = false;
207 Iterator<? extends Storeable> iterator = this.getBackend().iterator();
210 while (iterator.hasNext()) {
212 Contact c = (Contact) iterator.next();
215 this.getLogger().debug(MessageFormat.format("c={0},contact={1}", c, contact)); //NOI18N
218 if (c.equals(contact)) {
226 this.getLogger().trace(MessageFormat.format("isFound={0} - EXIT!", isFound)); //NOI18N
233 * Checks whether own contact is found in database
235 * @return Whether own contact is found
236 * @throws java.io.IOException If any IO error occurs
237 * @throws org.mxchange.jcore.exceptions.BadTokenException If a bad token was found
240 public boolean isOwnContactFound () throws SQLException, IOException, BadTokenException {
241 // Get search criteria instance
242 SearchableCritera critera = new SearchCriteria();
245 critera.addCriteria(AddressbookContactDatabaseConstants.COLUMN_NAME_OWN_CONTACT, true);
248 Result<? extends Storeable> result = this.getBackend().doSelectByCriteria(critera);
250 // Deligate this call to backend
251 return result.hasNext();
255 * Parses given line from database backend into a Storeable instance. Please
256 * note that not all backends need this.
258 * @param line Line from database backend
259 * @return A Storeable instance
262 public Storeable parseLineToStoreable (final String line) throws BadTokenException {
264 this.getLogger().trace(MessageFormat.format("line={0} - CALLED!", line)); //NOI18N
267 Contact contact = this.parseLineToContact(line);
270 this.getLogger().debug(MessageFormat.format("contact={0}", contact));
273 return (Storeable) contact;
277 * Reads a single row and parses it to a contact instance
279 * @param rowIndex Row index (also how much to skip)
280 * @return Contact instance
283 public Contact readSingleContact (final int rowIndex) {
285 // Deligate this to backend instance
286 return (Contact) this.getBackend().readRow(rowIndex);
287 } catch (final BadTokenException ex) {
289 this.abortProgramWithException(ex);
292 // Bad state, should not be reached
293 throw new IllegalStateException("This should not be reached");
297 * Parses given line and creates a Contact instance
299 * @param line Raw line to parse
301 * @return Contact instance
303 private Contact parseLineToContact (final String line) throws BadTokenException {
305 this.getLogger().trace(MessageFormat.format("line={0} - CALLED!", line)); //NOI18N
307 // Init A lot variables
310 Gender gender = null;
312 Contact contact = null;
315 this.getLogger().debug(MessageFormat.format("line={0}", line)); //NOI18N
318 // @TODO Move this into separate method
319 StringTokenizer tokenizer = new StringTokenizer(line, ";"); //NOI18N
325 // The tokens are now available, so get all
326 while (tokenizer.hasMoreElements()) {
332 String token = tokenizer.nextToken();
334 // If char " is at pos 2 (0,1,2), then cut it of there
335 if ((token.charAt(0) != '"') && (token.charAt(2) == '"')) {
336 // UTF-8 writer characters found
337 token = token.substring(2);
341 this.getLogger().debug(MessageFormat.format("token={0}", token)); //NOI18N
343 // Verify token, it must have double-quotes on each side
344 if ((!token.startsWith("\"")) || (!token.endsWith("\""))) { //NOI18N
345 // Something bad was read
346 throw new BadTokenException(token, count); //NOI18N
349 // All fine, so remove it
350 String strippedToken = token.substring(1, token.length() - 1);
352 // Is the string's content "null"?
353 if (strippedToken.equals("null")) { //NOI18N
355 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NULL!", strippedToken)); //NOI18N
357 // This needs to be set to null
358 strippedToken = null;
362 this.getLogger().debug(MessageFormat.format("strippedToken={0}", strippedToken)); //NOI18N
364 // Now, let's try a number check, if no null
365 if (strippedToken != null) {
366 // Okay, no null, maybe the string bears a decimal number?
368 num = Long.valueOf(strippedToken);
371 this.getLogger().debug(MessageFormat.format("strippedToken={0} - NUMBER!", strippedToken)); //NOI18N
372 } catch (final NumberFormatException ex) {
373 // No number, then set default
378 // Now, let's try a boolean check, if no null
379 if ((strippedToken != null) && (num == null) && ((strippedToken.equals("true")) || (strippedToken.equals("false")))) { //NOI18N
381 this.getLogger().debug(MessageFormat.format("strippedToken={0} - BOOLEAN!", strippedToken)); //NOI18N
383 // parseBoolean() is relaxed, so no exceptions
384 bool = Boolean.valueOf(strippedToken);
388 this.getLogger().debug(MessageFormat.format("strippedToken={0},num={1},bool={2}", strippedToken, num, bool)); //NOI18N
390 // Now, let's try a gender check, if no null
391 if ((strippedToken != null) && (num == null) && (bool == null) && (Gender.valueOf(strippedToken) instanceof Gender)) { //NOI18N
392 // Get first character
393 gender = Gender.valueOf(strippedToken);
396 this.getLogger().debug(MessageFormat.format("strippedToken={0},gender={1}", strippedToken, gender)); //NOI18N
398 // This instance must be there
399 assert (gender instanceof Gender) : MessageFormat.format("gender is not set by Gender.fromChar({0})", strippedToken); //NOI18N
402 // Now it depends on the counter which position we need to check
404 case 0: // isOwnContact
405 assert ((bool instanceof Boolean));
408 this.getLogger().debug(MessageFormat.format("bool={0}", bool)); //NOI18N
410 // Is it own contact?
413 this.getLogger().debug("Creating UserContact object ..."); //NOI18N
416 contact = new UserContact();
419 this.getLogger().debug("Creating BookContact object ..."); //NOI18N
422 contact = new BookContact();
427 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
430 contact.setGender(gender);
434 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
435 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
438 contact.setSurname(strippedToken);
441 case 3: // Family name
442 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
443 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
446 contact.setFamilyName(strippedToken);
449 case 4: // Company name
450 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
451 assert (gender instanceof Gender) : "gender instance is not set"; //NOI18N
454 contact.setCompanyName(strippedToken);
457 case 5: // Street number
458 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
461 contact.setHouseNumber(num);
465 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
468 contact.setZipCode(num);
472 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
475 contact.setCity(strippedToken);
478 case 8: // Country code
479 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
482 contact.setCountryCode(strippedToken);
485 case 9: // Phone number
486 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
489 contact.setPhoneNumber(strippedToken);
492 case 10: // Fax number
493 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
496 contact.setFaxNumber(strippedToken);
499 case 11: // Cellphone number
500 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
503 contact.setCellphoneNumber(strippedToken);
506 case 12: // Email address
507 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
510 contact.setEmailAddress(strippedToken);
514 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
517 contact.setBirthday(strippedToken);
521 assert (contact instanceof Contact) : "First token was not boolean"; //NOI18N
524 contact.setComment(strippedToken);
527 default: // New data entry
528 this.getLogger().warn(MessageFormat.format("Will not handle unknown data {0} at index {1}", strippedToken, count)); //NOI18N
532 // Increment counter for next round
537 this.getLogger().trace(MessageFormat.format("contact={0} - EXIT!", contact)); //NOI18N
539 // Return finished instance