]> git.mxchange.org Git - pizzaservice-war.git/blob
0afecbc9e18cea07e7e36c74ba759ac716e3e747
[pizzaservice-war.git] /
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.pizzaapplication.database.frontend.category;
18
19 import java.io.IOException;
20 import java.lang.reflect.InvocationTargetException;
21 import java.sql.ResultSet;
22 import java.sql.SQLException;
23 import java.text.MessageFormat;
24 import java.util.Iterator;
25 import java.util.Map;
26 import org.mxchange.jcore.criteria.searchable.SearchCriteria;
27 import org.mxchange.jcore.criteria.searchable.SearchableCriteria;
28 import org.mxchange.jcore.database.frontend.BaseDatabaseFrontend;
29 import org.mxchange.jcore.database.result.DatabaseResult;
30 import org.mxchange.jcore.database.result.Result;
31 import org.mxchange.jcore.database.storage.Storable;
32 import org.mxchange.jcore.exceptions.BadTokenException;
33 import org.mxchange.jcore.exceptions.CorruptedDatabaseFileException;
34 import org.mxchange.jcore.exceptions.UnsupportedDatabaseBackendException;
35 import org.mxchange.pizzaapplication.category.Category;
36 import org.mxchange.pizzaapplication.category.product.ProductCategory;
37 import org.mxchange.pizzaapplication.product.Product;
38
39 /**
40  * Stores and retrieves Contact instances
41  *
42  * @author Roland Haeder
43  */
44 public class PizzaCategoryDatabaseFrontend extends BaseDatabaseFrontend implements CategoryFrontend {
45
46         /**
47          * Default constrcutor
48          *
49          * @throws org.mxchange.jcore.exceptions.UnsupportedDatabaseBackendException If the configured backend is not supported
50          * @throws java.sql.SQLException If any SQL error occurs
51          */
52         public PizzaCategoryDatabaseFrontend () throws UnsupportedDatabaseBackendException, SQLException {
53                 // Trace message
54                 this.getLogger().trace("CALLED!"); //NOI18N
55
56                 // Set "table" name
57                 this.setTableName("category"); //NOI18N
58
59                 // Initalize backend
60                 this.initBackend();
61         }
62
63         /**
64          * Adds given category title as new category, parent may be null if not
65          * selected.
66          *
67          * @param title Title of category
68          * @param parent Parent id or null if not selected
69          */
70         @Override
71         public void addCategory (final String title, final Integer parent) throws SQLException, IOException {
72                 // Trace message
73                 this.getLogger().trace(MessageFormat.format("title={0},parent={1} - CALLED!", title, parent)); //NOI18N
74
75                 // Title should not be null
76                 if (null == title) {
77                         // Abort here
78                         throw new NullPointerException("title is null"); //NOI18N
79                 }
80
81                 // Clear dataset from previous usage
82                 this.clearDataSet();
83
84                 // Add title and parent
85                 this.addToDataSet(CategoryFrontend.COLUMN_TITLE, title);
86                 this.addToDataSet(CategoryFrontend.COLUMN_PARENT, parent);
87
88                 // Handle this over to the backend
89                 // @todo Nothing is done yet!
90                 Result<? extends Storable> result = this.doInsertDataSet();
91
92                 // Debug message
93                 this.getLogger().debug(MessageFormat.format("result={0}", result)); //NOI18N
94
95                 // Trace message
96                 this.getLogger().trace("EXIT!"); //NOI18N
97         }
98
99         /**
100          * Shuts down the database layer
101          *
102          * @throws java.sql.SQLException If an SQL error occurs
103          * @throws java.io.IOException If any IO error occurs
104          */
105         @Override
106         public void doShutdown () throws SQLException, IOException {
107                 // Trace message
108                 this.getLogger().trace("CALLED!"); //NOI18N
109
110                 // Shutdown backend
111                 this.getBackend().doShutdown();
112
113                 // Trace message
114                 this.getLogger().trace("EXIT!"); //NOI18N
115         }
116
117         /**
118          * Depending on column, an empty value may be converted to null
119          *
120          * @param key Key to check
121          * @param value Value to check
122          * @return Possible previous value or null
123          */
124         @Override
125         public Object emptyStringToNull (final String key, final Object value) {
126                 // Trace message
127                 this.getLogger().trace(MessageFormat.format("key={0},value={1} - CALLED!", key, value)); //NOI18N
128
129                 // Copy value
130                 Object v = value;
131
132                 // Is the value empty?
133                 if ((value instanceof String) && ("".equals(value))) { //NOI18N
134                         // This value may need to be changed
135                         switch (key) {
136                                 case CategoryFrontend.COLUMN_PARENT: // Convert this
137                                         v = null;
138                                         break;
139                         }
140                 }
141
142                 // Trace message
143                 this.getLogger().trace(MessageFormat.format("v={0} - EXIT!", v)); //NOI18N
144
145                 // Return it
146                 return v;
147         }
148
149         @Override
150         @SuppressWarnings ("unchecked")
151         public Iterator<Category> getAllCategories () throws IOException, BadTokenException, SQLException, CorruptedDatabaseFileException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
152                 // Trace message
153                 this.getLogger().trace("CALLED!"); //NOI18N
154
155                 // Instance search criteria
156                 SearchableCriteria criteria = new SearchCriteria();
157
158                 // Run the query
159                 Result<? extends Storable> result = this.getBackend().doSelectByCriteria(criteria);
160
161                 // Debug message
162                 this.getLogger().debug(MessageFormat.format("result={0}", result)); //NOI18N
163
164                 // Get iterator
165                 Iterator<?> iterator = result.iterator();
166
167                 // Trace message
168                 this.getLogger().trace(MessageFormat.format("iterator={0} - EXIT!", iterator)); //NOI18N
169
170                 // Get iterator and return it
171                 return (Iterator<Category>) iterator;
172         }
173
174         @Override
175         public Category getCategory (final Product product) throws IOException, BadTokenException, CorruptedDatabaseFileException, SQLException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
176                 // Trace message
177                 this.getLogger().trace(MessageFormat.format("product={0} - CALLED!", product)); //NOI18N
178
179                 // product must not be null
180                 if (null == product) {
181                         // Abort here
182                         throw new NullPointerException("product is null"); //NOI18N
183                 }
184
185                 // Get category id from it
186                 Long id = product.getCategory();
187
188                 // Debug message
189                 this.getLogger().debug(MessageFormat.format("id={0}", id)); //NOI18N
190
191                 // It should be >0 here
192                 assert (id > 0) : MessageFormat.format("id={0} must be larger zero", id); //NOI18N
193
194                 // Then construct a search instance
195                 SearchableCriteria criteria = new SearchCriteria();
196
197                 // Add id to it
198                 criteria.addCriteria(CategoryFrontend.COLUMN_ID, id);
199
200                 // Only one entry is find
201                 criteria.setLimit(1);
202
203                 // Run it on backend
204                 Result<? extends Storable> result = this.getBackend().doSelectByCriteria(criteria);
205
206                 // Debug log
207                 this.getLogger().debug(MessageFormat.format("result({0})={1}", result, result.size())); //NOI18N
208
209                 // Init category instance
210                 Category category = null;
211
212                 // Is there one entry?
213                 if (result.hasNext()) {
214                         // Read result from it
215                         Storable storeable = result.next();
216
217                         // Debug message
218                         this.getLogger().debug(MessageFormat.format("storeable={0}", storeable)); //NOI18N
219
220                         // Is it instance of Category?
221                         if (storeable instanceof Category) {
222                                 // Then cast it
223                                 category = (Category) storeable;
224                         }
225                 }
226
227                 // Trace message
228                 this.getLogger().trace(MessageFormat.format("category={0} - EXIT!", category)); //NOI18N
229
230                 // Return it
231                 return category;
232         }
233
234         @Override
235         public String getIdName () {
236                 // Return column id
237                 return CategoryFrontend.COLUMN_ID;
238         }
239
240         /**
241          * Gets a Result back from given ResultSet instance
242          *
243          * @param resultSet ResultSet instance from SQL driver
244          * @return A typorized Result instance
245          * @throws java.sql.SQLException If any SQL error occurs
246          */
247         @Override
248         public Result<? extends Storable> getResultFromSet (final ResultSet resultSet) throws SQLException {
249                 // Trace message
250                 this.getLogger().trace(MessageFormat.format("resultSet={0} - CALLED!", resultSet)); //NOI18N
251
252                 // Init result instance
253                 Result<? extends Storable> result = new DatabaseResult();
254
255                 // Reset result set before first row
256                 resultSet.beforeFirst();
257
258                 // "Walk" through all entries
259                 while (resultSet.next()) {
260                         // Get id, title and parent id
261                         Long id = resultSet.getLong(CategoryFrontend.COLUMN_ID);
262                         String title = resultSet.getString(CategoryFrontend.COLUMN_TITLE);
263                         Long parent = resultSet.getLong(CategoryFrontend.COLUMN_PARENT);
264
265                         // Debug message
266                         this.getLogger().debug(MessageFormat.format("id={0},title={1},parent={2}", id, title, parent)); //NOI18N
267
268                         // Instance new object
269                         Category category = new ProductCategory(id, title, parent);
270
271                         // Debug log
272                         this.getLogger().debug(MessageFormat.format("category={0}", category)); //NOI18N
273
274                         // Add it to result
275                         result.add(category);
276                 }
277
278                 // Trace message
279                 this.getLogger().trace(MessageFormat.format("result({0})={1} - EXIT!", result.size(), result)); //NOI18N
280
281                 // Return result
282                 return result;
283         }
284
285         @Override
286         public Storable getStorableAtRow (final int rowIndex) {
287                 throw new UnsupportedOperationException("Not supported yet: rowIndex=" + rowIndex);
288         }
289
290         /**
291          * Checks if given category title is already used
292          *
293          * @param title Title to check
294          * @return Whether the title has been used
295          */
296         @Override
297         public boolean isCategoryTitleUsed (final String title) throws IOException, SQLException, BadTokenException, CorruptedDatabaseFileException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
298                 // Trace message
299                 this.getLogger().trace(MessageFormat.format("title={0} - CALLED!", title)); //NOI18N
300
301                 // Get search criteria
302                 SearchableCriteria criteria = new SearchCriteria();
303
304                 // Add criteria
305                 criteria.addCriteria(CategoryFrontend.COLUMN_TITLE, title);
306
307                 // Only one entry is find
308                 criteria.setLimit(1);
309
310                 // Run it on backend
311                 Result<? extends Storable> result = this.getBackend().doSelectByCriteria(criteria);
312
313                 // Debug log
314                 this.getLogger().debug(MessageFormat.format("result({0})={1}", result, result.size())); //NOI18N
315
316                 // Now check size of the result
317                 boolean isFound = (result.size() == 1);
318
319                 // Trace message
320                 this.getLogger().trace(MessageFormat.format("isFound={0} - EXIT!", isFound)); //NOI18N
321
322                 // Return it
323                 return isFound;
324         }
325
326         /**
327          * Converts the given map into a Storable instance, depending on which
328          * class implements it. All keys are being interpreted as class
329          * fields/attributes and their respective setters are being searched for. As
330          * this method may fail to find one or access it, this method throws some
331          * exception.
332          *
333          * @param map Map instance to convert to Storable
334          * @return An instance of a Storable implementation
335          */
336         @Override
337         public Storable toStorable (final Map<String, String> map) throws NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
338                 // Trace message
339                 this.getLogger().trace(MessageFormat.format("map={0} - CALLED!", map)); //NOI18N
340
341                 // Is map null?
342                 if (null == map) {
343                         // Is null
344                         throw new NullPointerException("map is null"); //NOI18N
345                 } else if (map.isEmpty()) {
346                         // Map is empty
347                         throw new IllegalArgumentException("map is empty."); //NOI18N
348                 }
349
350                 // Debug message
351                 this.getLogger().debug(MessageFormat.format("Has to handle {0} entries", map.size())); //NOI18N
352
353                 // Get iterator on all entries
354                 Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
355
356                 // Init object instance
357                 Storable instance = new ProductCategory();
358
359                 // Iterate over all
360                 while (iterator.hasNext()) {
361                         // Get next entry
362                         Map.Entry<String, String> entry = iterator.next();
363
364                         // Debug message
365                         this.getLogger().debug(MessageFormat.format("entry:{0}={1}", entry.getKey(), entry.getValue())); //NOI18N
366
367                         // Try to set value
368                         instance.setValueFromColumn(entry.getKey(), entry.getValue());
369                 }
370
371                 // Trace message
372                 this.getLogger().trace(MessageFormat.format("instance={0} - EXIT!", instance)); //NOI18N
373
374                 // Return it
375                 return instance;
376         }
377 }