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