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