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