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