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