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