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