]> git.mxchange.org Git - pizzaservice-war.git/blob - src/java/org/mxchange/pizzaapplication/beans/basket/BasketWebBean.java
updated jars + switched from Deque to List
[pizzaservice-war.git] / src / java / org / mxchange / pizzaapplication / beans / basket / BasketWebBean.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.beans.basket;
18
19 import java.text.MessageFormat;
20 import java.util.List;
21 import javax.annotation.PostConstruct;
22 import javax.enterprise.context.SessionScoped;
23 import javax.faces.FacesException;
24 import javax.faces.view.facelets.FaceletException;
25 import javax.inject.Named;
26 import javax.naming.Context;
27 import javax.naming.InitialContext;
28 import javax.naming.NamingException;
29 import org.mxchange.jcoreee.beans.BaseFrameworkBean;
30 import org.mxchange.jshopcore.exceptions.BasketItemAlreadyAddedException;
31 import org.mxchange.jshopcore.model.basket.AddableBasketItem;
32 import org.mxchange.jshopcore.model.basket.Basket;
33 import org.mxchange.jshopcore.model.basket.BasketSessionBeanRemote;
34 import org.mxchange.jshopcore.model.basket.ShopBasket;
35 import org.mxchange.jshopcore.model.basket.items.BasketItem;
36 import org.mxchange.jshopcore.model.product.Product;
37
38 /**
39  * A bean for the basket
40  *
41  * @author Roland Haeder<roland@mxchange.org>
42  */
43 @Named ("basketController")
44 @SessionScoped
45 public class BasketWebBean extends BaseFrameworkBean implements BasketWebController {
46
47         /**
48          * Serial number
49          */
50         private static final long serialVersionUID = 5_476_347_320_198L;
51
52         /**
53          * Instance of wrapped basket
54          */
55         private final Basket<AddableBasketItem> basket;
56
57         /**
58          * Basket bean
59          */
60         private final BasketSessionBeanRemote basketBean;
61
62         /////////////////////// Properties /////////////////////
63         /**
64          * Ordered amount
65          */
66         private Long amount;
67
68         /**
69          * Current item
70          */
71         private AddableBasketItem currentItem;
72
73         /**
74          * Default constructor
75          */
76         public BasketWebBean () {
77                 // Get new application instance
78                 this.basket = new ShopBasket();
79
80                 try {
81                         // Get initial context
82                         Context context = new InitialContext();
83
84                         // Try to lookup
85                         this.basketBean = (BasketSessionBeanRemote) context.lookup("ejb/stateless-basket"); //NOI18N
86                 } catch (final NamingException ex) {
87                         // Continue to throw
88                         throw new FaceletException(ex);
89                 }
90         }
91
92         @Override
93         public String addItem (final Product product) {
94                 // Trace message
95                 this.getLogger().logTrace(MessageFormat.format("addItem: product={0} - CALLED!", product));
96
97                 // product should not be null
98                 if (null == product) {
99                         // Abort here
100                         throw new NullPointerException("product is null");
101                 }
102
103                 // Generate item instance
104                 AddableBasketItem item = new BasketItem(product, this.getAmount());
105
106                 // Is amount set?
107                 if (this.getAmount() == null) {
108                         // Trace message
109                         this.getLogger().logTrace("addItem: amount not specified, returning null ... - EXIT!");
110
111                         // No amount specified?!
112                         return null;
113                 }
114
115                 try {
116                         // item should not be null
117                         if (null == item) {
118                                 // Abort here
119                                 throw new NullPointerException("item is null"); //NOI18N
120                         }
121
122                         // Deligate to model
123                         this.basket.addItem(item);
124
125                         // Remove amount
126                         this.setAmount(null);
127
128                         // Trace message
129                         this.getLogger().logTrace(MessageFormat.format("addItem: item {0} - has been added to basket. - EXIT!", item));
130
131                         // Added
132                         return "item_added"; //NOI18N
133                 } catch (final BasketItemAlreadyAddedException ex) {
134                         // Throw unchecked exception
135                         throw new FacesException(ex);
136                 }
137         }
138
139         @Override
140         public List<AddableBasketItem> allItems () {
141                 // Trace message
142                 this.getLogger().logTrace("allItems: CALLED!");
143
144                 // Deligate to basket instance
145                 List<AddableBasketItem> list = this.basket.getAll();
146
147                 // Trace message
148                 this.getLogger().logTrace(MessageFormat.format("allItems: list={0} - EXIT!", list));
149
150                 // Return it
151                 return list;
152         }
153
154         @Override
155         public Float calculateCurrentItemPrice () {
156                 // Trace message
157                 this.getLogger().logTrace("calculateCurrentItemPrice: CALLED!");
158
159                 // Is the current item/amount set?
160                 if (this.getCurrentItem() == null) {
161                         // Current item is null
162                         throw new NullPointerException("currentItem is null"); //NOI18N
163                 } else if (this.getCurrentItem().getProduct() == null) {
164                         // Product is null
165                         throw new NullPointerException("currentItem.product is null"); //NOI18N
166                 } else if (this.getCurrentItem().getAmount() == null) {
167                         // Amount is null
168                         throw new NullPointerException("currentItem.amount is null"); //NOI18N
169                 }
170
171                 // Caculate item's price
172                 Float totalPrice = (this.getCurrentItem().getProduct().getPrice() * this.getCurrentItem().getAmount());
173
174                 // Trace message
175                 this.getLogger().logTrace(MessageFormat.format("calculateCurrentItemPrice: totalPrice={0} - EXIT!", totalPrice));
176
177                 // Return it
178                 return totalPrice;
179         }
180
181         @Override
182         public Float calculateItemPrice (final AddableBasketItem item) {
183                 // Trace message
184                 this.getLogger().logTrace(MessageFormat.format("calculateItemPrice: item={0} - CALLED!", item));
185
186                 // item must not be null
187                 if (null == item) {
188                         // Abort here
189                         throw new NullPointerException("item is null");
190                 }
191
192                 // Default value
193                 Float totalPrice = 0.0f;
194
195                 // Is it a product?
196                 if (item.isProductType()) {
197                         // Caculate item's price
198                         totalPrice = (item.getProduct().getPrice() * item.getAmount());
199                 }
200
201                 // Trace message
202                 this.getLogger().logTrace(MessageFormat.format("calculateItemPrice: totalPrice={0} - EXIT!", totalPrice));
203
204                 // Return it
205                 return totalPrice;
206         }
207
208         @Override
209         public Float calculateTotalPrice () {
210                 // Trace message
211                 this.getLogger().logTrace("calculateTotalPrice: CALLED!");
212
213                 // Init total price
214                 Float totalPrice = 0.0f;
215
216                 // Iterate over all items
217                 for (final AddableBasketItem item : this.allItems()) {
218                         // Is the item a product?
219                         if (item.isProductType()) {
220                                 // Calculate single price and add it
221                                 totalPrice += this.calculateItemPrice(item);
222                         }
223                 }
224
225                 // Trace message
226                 this.getLogger().logTrace(MessageFormat.format("calculateTotalPrice: totalPrice={0} - EXIT!", totalPrice));
227
228                 // Return final sum
229                 return totalPrice;
230         }
231
232         @Override
233         public String changeItem (final AddableBasketItem item) {
234                 // Trace message
235                 this.getLogger().logTrace(MessageFormat.format("changeItem: item={0} - CALLED!", item));
236
237                 // item shall not be null
238                 if (null == item) {
239                         // Abort here
240                         throw new NullPointerException("item is null");
241                 }
242
243                 // Default is not found
244                 String targetPage = "item_not_changed"; //NOI18N
245
246                 // Lookup item in basket
247                 for (final AddableBasketItem basketItem : this.allItems()) {
248                         // Is it the same?
249                         if (basketItem.equals(item)) {
250                                 // Found it, so allow redirect to proper page
251                                 targetPage = "basket"; //NOI18N
252                                 break;
253                         }
254                 }
255
256                 // Trace message
257                 this.getLogger().logTrace(MessageFormat.format("changeItem: targetPage={0} - EXIT!", targetPage));
258
259                 // Return page
260                 return targetPage;
261         }
262
263         @Override
264         public void clear () {
265                 // @TODO Also clear EJB
266                 // Deligate to basket instance
267                 this.basket.clear();
268         }
269
270         @Override
271         public Long getAmount () {
272                 return this.amount;
273         }
274
275         @Override
276         public void setAmount (final Long amount) {
277                 this.amount = amount;
278         }
279
280         @Override
281         public AddableBasketItem getCurrentItem () {
282                 return this.currentItem;
283         }
284
285         @Override
286         public void setCurrentItem (final AddableBasketItem currentItem) {
287                 this.currentItem = currentItem;
288         }
289
290         @Override
291         public Long getItemAmount (final Product product) {
292                 // Trace message
293                 this.getLogger().logTrace(MessageFormat.format("getItemAmount: product={0} - CALLED!", product));
294
295                 // product should not be null
296                 if (null == product) {
297                         // Abort here
298                         throw new NullPointerException("product is null");
299                 }
300
301                 // Initial value is zero
302                 Long itemAmount = 0L;
303
304                 // Iterate over all
305                 for (final AddableBasketItem item : this.allItems()) {
306                         // Debug message
307                         this.getLogger().logDebug(MessageFormat.format("getItemAmount: item={0}", item));
308
309                         // Is this product instance and same?
310                         if (null == item) {
311                                 // item is null
312                                 throw new NullPointerException("item is null");
313                         } else if ((item.isProductType()) && (item.getProduct().equals(product))) {
314                                 // Found it
315                                 itemAmount = item.getAmount();
316                                 break;
317                         }
318                 }
319
320                 // Trace message
321                 this.getLogger().logTrace(MessageFormat.format("getItemAmount: itemAmount={0} - EXIT!", itemAmount));
322
323                 // Return it
324                 return itemAmount;
325         }
326
327         @Override
328         public AddableBasketItem getLast () {
329                 // Deligate to basket instance
330                 return this.basket.getLast();
331         }
332
333         @Override
334         public int getLastNumRows () {
335                 // Deligate to basket instance
336                 return this.basket.getLastNumRows();
337         }
338
339         @Override
340         public boolean hasItems () {
341                 // Call above and invert it
342                 return (!this.isEmpty());
343         }
344
345         @PostConstruct
346         public void init () {
347                 // Call generic init first
348                 super.genericInit();
349         }
350
351         @Override
352         public boolean isEmpty () {
353                 // Deligate to basket instance
354                 return this.basket.isEmpty();
355         }
356
357         @Override
358         public boolean isProductAdded (final Product product) {
359                 // Trace message
360                 this.getLogger().logTrace(MessageFormat.format("isProductAdded: product={0} - EXIT!", product));
361
362                 // Must not be null
363                 if (null == product) {
364                         // Abort here
365                         throw new NullPointerException("product is null"); //NOI18N
366                 }
367
368                 // Generate fake instance
369                 AddableBasketItem fake = new BasketItem(product);
370
371                 // Debug message
372                 this.getLogger().logDebug(MessageFormat.format("isProductAdded: fake={0}", fake));
373
374                 // Ask bean about it
375                 boolean isAdded = this.basket.isAdded(fake);
376
377                 // Debug message
378                 this.getLogger().logDebug(MessageFormat.format("isProductAdded: isAdded={0}", isAdded));
379
380                 // Is it added?
381                 if (isAdded) {
382                         // Get item
383                         AddableBasketItem item = this.getItemFromProduct(product);
384
385                         // Debug message
386                         this.getLogger().logDebug(MessageFormat.format("isProductAdded: item={0} - setting as current item.", item));
387
388                         // Set this as current item
389                         this.setCurrentItem(item);
390                 }
391
392                 // Trace message
393                 this.getLogger().logTrace(MessageFormat.format("isProductAdded: isAdded={0} - EXIT!", isAdded));
394
395                 // Return status
396                 return isAdded;
397         }
398
399         @Override
400         public String outputLastAddedItem () {
401                 // Trace message
402                 this.getLogger().logTrace("outputLastAddedItem: CALLED!");
403
404                 // Default message
405                 String lastItem = ""; //NOI18N
406
407                 // Get instance
408                 AddableBasketItem item = this.getLast();
409
410                 // Is it set?
411                 if (item instanceof AddableBasketItem) {
412                         // Get type
413                         switch (item.getItemType()) {
414                                 case "product": // Sellable product //NOI18N
415                                         assert (item.getProduct() instanceof Product) : MessageFormat.format("item {0} has no product instance set.", item); //NOI18N
416
417                                         // Get title
418                                         lastItem = item.getProduct().getTitle();
419                                         break;
420
421                                 default: // Not supported
422                                         throw new FacesException(MessageFormat.format("item type {0} is not supported.", item.getItemType())); //NOI18N
423                         }
424                 }
425
426                 // Trace message
427                 this.getLogger().logTrace(MessageFormat.format("outputLastAddedItem: lastItem={0} - EXIT!", lastItem));
428
429                 // Return it
430                 return lastItem;
431         }
432
433         /**
434          * Getter for basket bean instance
435          *
436          * @return Basket bean instance
437          */
438         private BasketSessionBeanRemote getBasketBean () {
439                 return this.basketBean;
440         }
441
442         /**
443          * Somewhat getter for an item instance from given product instance. This
444          * method returns null if no item was found to given product. The product is
445          * found by checking it's id and itemType=product
446          *
447          * @param product Product instance
448          * @return Item instance or null if not found
449          */
450         private AddableBasketItem getItemFromProduct (final Product product) {
451                 // Trace message
452                 this.getLogger().logTrace(MessageFormat.format("getItemFromProduct: product={0} - CALLED!", product));
453
454                 // Product must not be null
455                 if (null == product) {
456                         // Abort here
457                         throw new NullPointerException("product is null"); //NOI18N
458                 }
459
460                 // Create item instance
461                 AddableBasketItem foundItem = null;
462
463                 // Create fake instance
464                 AddableBasketItem fake = new BasketItem(product);
465
466                 // Debug message
467                 this.getLogger().logDebug(MessageFormat.format("getItemFromProduct: fake={0}", fake));
468
469                 // Get all items
470                 List<AddableBasketItem> list = this.basket.getAll();
471
472                 // Debug message
473                 this.getLogger().logDebug(MessageFormat.format("getItemFromProduct: list={0}", list));
474
475                 // Check all entries
476                 for (final AddableBasketItem item : list) {
477                         // Debug message
478                         this.getLogger().logDebug(MessageFormat.format("getItemFromProduct: item={0}", item));
479
480                         // item must not be null
481                         if (null == item) {
482                                 // Abort here
483                                 throw new NullPointerException("item is null"); //NOI18N
484                         }
485
486                         // Is it the same?
487                         if (item.equals(fake)) {
488                                 // Set found item and abort look
489                                 foundItem = item;
490                                 break;
491                         }
492                 }
493
494                 // Trace message
495                 this.getLogger().logTrace(MessageFormat.format("getItemFromProduct: foundItem={0} - EXIT!", foundItem));
496
497                 // Return it
498                 return foundItem;
499         }
500 }