]> git.mxchange.org Git - jfinancials-war.git/blob - src/java/org/mxchange/jfinancials/beans/generic_product/list/FinancialsProductListWebViewBean.java
Updated copyright year
[jfinancials-war.git] / src / java / org / mxchange / jfinancials / beans / generic_product / list / FinancialsProductListWebViewBean.java
1 /*
2  * Copyright (C) 2017 - 2022 Free Software Foundation
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Affero General Public License as
6  * published by the Free Software Foundation, either version 3 of the
7  * License, or (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 Affero General Public License for more details.
13  *
14  * You should have received a copy of the GNU Affero General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 package org.mxchange.jfinancials.beans.generic_product.list;
18
19 import fish.payara.cdi.jsr107.impl.NamedCache;
20 import java.text.MessageFormat;
21 import java.util.Comparator;
22 import java.util.LinkedList;
23 import java.util.List;
24 import java.util.Objects;
25 import javax.annotation.PostConstruct;
26 import javax.cache.Cache;
27 import javax.ejb.EJB;
28 import javax.enterprise.event.Observes;
29 import javax.faces.view.ViewScoped;
30 import javax.inject.Inject;
31 import javax.inject.Named;
32 import org.mxchange.jfinancials.beans.BaseFinancialsBean;
33 import org.mxchange.jproduct.events.product.added.AddedProductEvent;
34 import org.mxchange.jproduct.events.product.updated.ObservableProductUpdatedEvent;
35 import org.mxchange.jproduct.exceptions.product.ProductNotFoundException;
36 import org.mxchange.jproduct.model.product.Product;
37 import org.mxchange.jproduct.model.product.ProductSessionBeanRemote;
38
39 /**
40  * A view-scoped bean for product lists
41  * <p>
42  * @author Roland Haeder<roland@mxchange.org>
43  */
44 @Named ("productListController")
45 @ViewScoped
46 public class FinancialsProductListWebViewBean extends BaseFinancialsBean implements FinancialsProductListWebViewController {
47
48         /**
49          * Serial number
50          */
51         private static final long serialVersionUID = 34_869_872_672_643L;
52
53         /**
54          * List for all products
55          */
56         private final List<Product> allProducts;
57
58         /**
59          * List for filtered products
60          */
61         private List<Product> filteredProducts;
62
63         /**
64          * EJB for general product purposes
65          */
66         @EJB (lookup = "java:global/jfinancials-ejb/product!org.mxchange.jproduct.model.product.ProductSessionBeanRemote")
67         private ProductSessionBeanRemote productBean;
68
69         /**
70          * Cached products
71          */
72         @Inject
73         @NamedCache (cacheName = "productCache")
74         private transient Cache<Long, Product> productCache;
75
76         /**
77          * Selected product
78          */
79         private Product selectedProduct;
80
81         /**
82          * Default constructor
83          */
84         public FinancialsProductListWebViewBean () {
85                 // Call super constructor
86                 super();
87
88                 // Init list
89                 this.allProducts = new LinkedList<>();
90         }
91
92         /**
93          * Observes events fired after a new product has been added
94          * <p>
95          * @param event Event to be observed
96          */
97         public void afterProductAddedEvent (@Observes final AddedProductEvent event) {
98                 // Is all valid?
99                 if (null == event) {
100                         // Throw NPE
101                         throw new NullPointerException("event is null"); //NOI18N
102                 } else if (event.getAddedProduct() == null) {
103                         // Throw again ...
104                         throw new NullPointerException("event.addedProduct is null"); //NOI18N
105                 } else if (event.getAddedProduct().getProductId() == null) {
106                         // And again ...
107                         throw new NullPointerException("event.addedProduct.productId is null"); //NOI18N
108                 } else if (event.getAddedProduct().getProductId() < 1) {
109                         // Id is invalid
110                         throw new IllegalArgumentException(MessageFormat.format("event.addedProduct.productId={0} is not valid.", event.getAddedProduct().getProductId())); //NOI18N
111                 }
112
113                 // Add it
114                 this.addProduct(event.getAddedProduct());
115         }
116
117         /**
118          * Event observer for updated product data by administrators
119          * <p>
120          * @param event Updated product data event
121          */
122         public void afterProductUpdatedEvent (@Observes final ObservableProductUpdatedEvent event) {
123                 // Event and contained entity instance should not be null
124                 if (null == event) {
125                         // Throw NPE
126                         throw new NullPointerException("event is null"); //NOI18N
127                 } else if (event.getUpdatedProduct() == null) {
128                         // Throw NPE again
129                         throw new NullPointerException("event.updatedProduct is null"); //NOI18N
130                 } else if (event.getUpdatedProduct().getProductId() == null) {
131                         // userId is null
132                         throw new NullPointerException("event.updatedProduct.productId is null"); //NOI18N
133                 } else if (event.getUpdatedProduct().getProductId() < 1) {
134                         // Not avalid id
135                         throw new IllegalArgumentException(MessageFormat.format("userId of user={0} is not valid: {1}", event.getUpdatedProduct(), event.getUpdatedProduct().getProductId())); //NOI18N
136                 }
137
138                 // Add product instance only once
139                 this.addProduct(event.getUpdatedProduct());
140         }
141
142         @Override
143         public Product findProductById (final Long productId) throws ProductNotFoundException {
144                 // Validate parameter
145                 if (null == productId) {
146                         // Throw NPE
147                         throw new NullPointerException("productId is null"); //NOI18N
148                 } else if (productId < 1) {
149                         // Throw IAE
150                         throw new IllegalArgumentException(MessageFormat.format("productId={0} is invalid", productId)); //NOI18N
151                 } else if (!this.productCache.containsKey(productId)) {
152                         // Not found
153                         throw new ProductNotFoundException(productId);
154                 }
155
156                 // Get it from cache
157                 final Product product = this.productCache.get(productId);
158
159                 // Return it
160                 return product;
161         }
162
163         /**
164          * Some "getter" for a linked list of only available products
165          * <p>
166          * @return Only available products
167          */
168         @SuppressWarnings ("ReturnOfCollectionOrArrayField")
169         public List<Product> getAllProducts () {
170                 // Return it
171                 return this.allProducts;
172         }
173
174         /**
175          * Getter for filtered product list
176          * <p>
177          * @return Filtered product list
178          */
179         @SuppressWarnings ("ReturnOfCollectionOrArrayField")
180         public List<Product> getFilteredProducts () {
181                 return this.filteredProducts;
182         }
183
184         /**
185          * Setter for filtered product list
186          * <p>
187          * @param filteredProducts Filtered product list
188          */
189         @SuppressWarnings ("AssignmentToCollectionOrArrayFieldFromParameter")
190         public void setFilteredProducts (final List<Product> filteredProducts) {
191                 this.filteredProducts = filteredProducts;
192         }
193
194         /**
195          * Getter for selected product
196          * <p>
197          * @return Selected product
198          */
199         public Product getSelectedProduct () {
200                 return this.selectedProduct;
201         }
202
203         /**
204          * Setter for selected product
205          * <p>
206          * @param selectedProduct Selected product
207          */
208         public void setSelectedProduct (final Product selectedProduct) {
209                 this.selectedProduct = selectedProduct;
210         }
211
212         /**
213          * Initialization of this bean
214          */
215         @PostConstruct
216         public void initializeList () {
217                 // Is cache there?
218                 if (!this.productCache.iterator().hasNext()) {
219                         // "Walk" through all entries and add to cache
220                         for (final Product product : this.productBean.fetchAllGenericProducts()) {
221                                 // Add it by primary key
222                                 this.productCache.put(product.getProductId(), product);
223                         }
224                 }
225
226                 // Is the list empty, but filled cache?
227                 if (this.getAllProducts().isEmpty() && this.productCache.iterator().hasNext()) {
228                         // Build up list
229                         for (final Cache.Entry<Long, Product> currentEntry : this.productCache) {
230                                 // Add to list
231                                 this.getAllProducts().add(currentEntry.getValue());
232                         }
233
234                         // Sort list
235                         this.getAllProducts().sort(new Comparator<Product>() {
236                                 @Override
237                                 public int compare (final Product product1, final Product product2) {
238                                         return product1.getProductId() > product2.getProductId() ? 1 : product1.getProductId() < product2.getProductId() ? -1 : 0;
239                                 }
240                         });
241
242                         // Set whole list
243                         this.setFilteredProducts(this.getAllProducts());
244                 }
245         }
246
247         @Override
248         public boolean isProductI18nKeyAdded (final String productI18nKey) {
249                 // Validate parameter
250                 if (null == productI18nKey) {
251                         // Throw NPE
252                         throw new NullPointerException("productI18nKey is null"); //NOI18N
253                 } else if (productI18nKey.isEmpty()) {
254                         // Throw IAE
255                         throw new IllegalArgumentException("productI18nKey is empty"); //NOI18N
256                 }
257
258                 // Default is not the same
259                 boolean isFound = false;
260
261                 // Check all added,products
262                 for (final Product product : this.getAllProducts()) {
263                         // Is i18n key the same?
264                         if (Objects.equals(product.getProductI18nKey(), productI18nKey)) {
265                                 // Found it
266                                 isFound = true;
267                                 break;
268                         }
269                 }
270
271                 // Return flag
272                 return isFound;
273         }
274
275         /**
276          * Adds unique instance to product list. First any existing instance is
277          * being removed, then the new instance is added. It also updates the cache
278          * regardless if found or not.
279          * <p>
280          * @param product Product instance to add uniquely
281          */
282         private void addProduct (final Product product) {
283                 // Add product to list
284                 this.productCache.put(product.getProductId(), product);
285
286                 // Does the list contain it?
287                 if (this.getAllProducts().contains(product)) {
288                         // Yes, then remove it
289                         this.getAllProducts().remove(product);
290                 }
291
292                 // (Re-)add product
293                 this.getAllProducts().add(product);
294         }
295
296         /**
297          * Removes given product from all lists
298          * <p>
299          * @param product Product instance to remove
300          */
301         private void removeProduct (final Product product) {
302                 // Remove from general list
303                 this.productCache.remove(product.getProductId());
304         }
305
306 }