]> git.mxchange.org Git - jfinancials-lib.git/blob - src/org/mxchange/addressbook/database/frontend/contact/AddressbookContactDatabaseFrontend.java
Updated jcore + some more fixes for changed database backend (Table Data Gateway...
[jfinancials-lib.git] / src / org / mxchange / addressbook / database / frontend / contact / AddressbookContactDatabaseFrontend.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.frontend.contact;
18
19 import java.io.IOException;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.InvocationTargetException;
22 import java.sql.SQLException;
23 import java.text.MessageFormat;
24 import java.util.Iterator;
25 import java.util.Map;
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.criteria.searchable.SearchCriteria;
31 import org.mxchange.jcore.criteria.searchable.SearchableCriteria;
32 import org.mxchange.jcore.database.frontend.BaseDatabaseFrontend;
33 import org.mxchange.jcore.database.result.Result;
34 import org.mxchange.jcore.database.storage.Storeable;
35 import org.mxchange.jcore.exceptions.BadTokenException;
36 import org.mxchange.jcore.exceptions.CorruptedDatabaseFileException;
37 import org.mxchange.jcore.exceptions.UnsupportedDatabaseBackendException;
38
39 /**
40  * Stores and retrieves Contact instances
41  *
42  * @author Roland Haeder
43  */
44 public class AddressbookContactDatabaseFrontend extends BaseDatabaseFrontend implements AddressbookContactFrontend {
45
46         /**
47          * Constructor which accepts a contact manager
48          *
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
52          */
53         public AddressbookContactDatabaseFrontend (final AddressbookContactManager manager) throws UnsupportedDatabaseBackendException, SQLException {
54                 // Call own constructor
55                 this();
56
57                 // Trace message
58                 this.getLogger().trace(MessageFormat.format("manager={0} - CALLED!", manager)); //NOI18N
59
60                 // Manager instance must not be null
61                 if (manager == null) {
62                         // Abort here
63                         throw new NullPointerException("manager is null"); //NOI18N
64                 }
65
66                 // Set contact manager
67                 this.setContactManager(manager);
68         }
69
70         /**
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
74          */
75         protected AddressbookContactDatabaseFrontend () throws UnsupportedDatabaseBackendException, SQLException {
76                 // Trace message
77                 this.getLogger().trace("CALLED!"); //NOI18N
78
79                 // Set "table" name
80                 this.setTableName("contacts"); //NOI18N
81
82                 // Initalize backend
83                 this.initBackend();
84         }
85
86         /**
87          * Adds given contact instance to database
88          *
89          * @param contact Contact instance
90          * @throws org.mxchange.addressbook.exceptions.ContactAlreadyAddedException If the contact instance is already found
91          */
92         @Override
93         public void addContact (final Contact contact) throws ContactAlreadyAddedException {
94                 // Trace message
95                 this.getLogger().trace("CALLED!"); //NOI18N
96
97                 // Make sure the contact is set
98                 if (contact == null) {
99                         // Abort here
100                         throw new NullPointerException("contact is null"); //NOI18N
101                 }
102
103                 try {
104                         // First check if the contact is there
105                         if (this.isContactFound(contact)) {
106                                 // Already there
107                                 throw new ContactAlreadyAddedException(contact);
108                         }
109
110                         // Clear dataset from previous usage
111                         this.clearDataSet();
112
113                         // Get field iterator
114                         Iterator<Map.Entry<Field, Object>> iterator = contact.iterator();
115
116                         // Iterate over all
117                         while (iterator.hasNext()) {
118                                 // Get next field
119                                 Map.Entry<Field, Object> field = iterator.next();
120
121                                 // Add it to data set
122                                 this.addToDataSet(field.getKey().getName(), field.getValue());
123                         }
124
125                         // Then add it
126                         Result<? extends Storeable> result = this.doInsertDataSet();
127
128                         // Debug message
129                         this.getLogger().debug(MessageFormat.format("result={0}", result)); //NOI18N
130                 } catch (final IOException | BadTokenException | SQLException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) {
131                         // Abort here
132                         this.abortProgramWithException(ex);
133                 }
134
135                 // Trace message
136                 this.getLogger().trace("CALLED!"); //NOI18N
137         }
138
139         /**
140          * Shuts down the database layer
141          * @throws java.sql.SQLException If an SQL error occurs
142          * @throws java.io.IOException If an IO error occurs
143          */
144         @Override
145         public void doShutdown () throws SQLException, IOException {
146                 // Trace message
147                 this.getLogger().trace("CALLED!"); //NOI18N
148
149                 // Shutdown backend
150                 this.getBackend().doShutdown();
151
152                 // Trace message
153                 this.getLogger().trace("EXIT!"); //NOI18N
154         }
155
156         @Override
157         public Object emptyStringToNull (final String key, final Object value) {
158                 throw new UnsupportedOperationException(MessageFormat.format("Not supported yet: key={0},value={1}", key, value));
159         }
160
161         /**
162          * Some "getter" for total contact count
163          *
164          * @return Total contact count
165          */
166         @Override
167         public int getContactsCount () throws SQLException, IOException {
168                 // And deligate to backend
169                 return this.getBackend().getTotalRows(); //NOI18N
170         }
171
172         @Override
173         public String getIdName () {
174                 // Return id column
175                 return AddressbookContactDatabaseConstants.COLUMN_ID;
176         }
177
178         /**
179          * Some "getter" for own contact instance
180          *
181          * @return Own contact instance
182          */
183         @Override
184         public Contact getOwnContact () {
185                 // Trace message
186                 this.getLogger().trace("CALLED!"); //NOI18N
187
188                 // Get row index back from backend
189                 int rowIndex = this.getBackend().getRowIndexFromColumn(AddressbookContactDatabaseConstants.COLUMN_OWN_CONTACT, true);
190
191                 // Debug message
192                 this.getLogger().debug(MessageFormat.format("rowIndex={0}", rowIndex));
193
194                 // Init instance
195                 Contact contact = null;
196
197                 try {
198                         // Now simply read the row
199                         contact = (Contact) this.getBackend().readRow(rowIndex);
200                 } catch (final BadTokenException ex) {
201                         // Bad token found
202                         this.abortProgramWithException(ex);
203                 }
204
205                 // Trace message
206                 this.getLogger().trace(MessageFormat.format("contact={0} - EXIT!", contact));
207
208                 // Return it
209                 return contact;
210         }
211
212         /**
213          * Checks if given Contact is found
214          * 
215          * @param contact Contact instance to check
216          * @return Whether the given Contact instance is found
217          */
218         @Override
219         public boolean isContactFound (final Contact contact) throws BadTokenException {
220                 // Trace message
221                 this.getLogger().trace(MessageFormat.format("contact={0} - CALLED!", contact)); //NOI18N
222
223                 // contact should not be null
224                 if (contact == null) {
225                         // Abort here
226                         throw new NullPointerException("contact is null"); //NOI18N
227                 }
228
229                 // Default is not found
230                 boolean isFound = false;
231
232                 // Start iteration
233                 Iterator<? extends Storeable> iterator = this.getBackend().iterator();
234
235                 // Check all entries
236                 while (iterator.hasNext()) {
237                         // Get next element
238                         Contact c = (Contact) iterator.next();
239
240                         // Debug message
241                         this.getLogger().debug(MessageFormat.format("c={0},contact={1}", c, contact)); //NOI18N
242
243                         // Is it added?
244                         if (c.equals(contact)) {
245                                 // Is found
246                                 isFound = true;
247                                 break;
248                         }
249                 }
250
251                 // Trace message
252                 this.getLogger().trace(MessageFormat.format("isFound={0} - EXIT!", isFound)); //NOI18N
253
254                 // Return it
255                 return isFound;
256         }
257
258         /**
259          * Checks whether own contact is found in database
260          *
261          * @return Whether own contact is found
262          * @throws org.mxchange.jcore.exceptions.BadTokenException Continued throw
263          * @throws org.mxchange.jcore.exceptions.CorruptedDatabaseFileException If the database file is damaged
264          * @throws java.lang.NoSuchMethodException If a method cannot be found
265          * @throws java.lang.IllegalAccessException If a method is not accessible
266          * @throws java.lang.reflect.InvocationTargetException Any other problems?
267          */
268         @Override
269         public boolean isOwnContactFound () throws SQLException, IOException, BadTokenException, CorruptedDatabaseFileException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
270                 // Get search criteria instance
271                 SearchableCriteria critera = new SearchCriteria();
272
273                 // Add condition
274                 critera.addCriteria(AddressbookContactDatabaseConstants.COLUMN_OWN_CONTACT, true);
275
276                 // Get result
277                 Result<? extends Storeable> result = this.getBackend().doSelectByCriteria(critera);
278
279                 // Deligate this call to backend
280                 return result.hasNext();
281         }
282
283         /**
284          * Reads a single row and parses it to a contact instance
285          *
286          * @param rowIndex Row index (also how much to skip)
287          * @return Contact instance
288          */
289         @Override
290         public Contact readSingleContact (final int rowIndex) {
291                 try {
292                         // Deligate this to backend instance
293                         return (Contact) this.getBackend().readRow(rowIndex);
294                 } catch (final BadTokenException ex) {
295                         // Bad token found
296                         this.abortProgramWithException(ex);
297                 }
298
299                 // Bad state, should not be reached
300                 throw new IllegalStateException("This should not be reached");
301         }
302
303         @Override
304         public Storeable toStoreable (final Map<String, String> map) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
305                 throw new UnsupportedOperationException("Not supported yet: map=" + map);
306         }
307 }