]> git.mxchange.org Git - jcoreee.git/blob - src/org/mxchange/jcoreee/bean/faces/BaseFacesBean.java
Continued:
[jcoreee.git] / src / org / mxchange / jcoreee / bean / faces / BaseFacesBean.java
1 /*
2  * Copyright (C) 2017, 2018 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 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.jcoreee.bean.faces;
18
19 import java.io.Serializable;
20 import java.math.BigDecimal;
21 import java.security.Principal;
22 import java.text.MessageFormat;
23 import java.util.ArrayList;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.MissingResourceException;
27 import java.util.ResourceBundle;
28 import javax.faces.application.FacesMessage;
29 import javax.faces.context.FacesContext;
30
31 /**
32  * An abstract bean for faces (web) projects.
33  * <p>
34  * @author Roland Häder<roland@mxchange.org>
35  */
36 public abstract class BaseFacesBean implements Serializable {
37
38         /**
39          * Loaded resource bundles ("cached")
40          */
41         private static final List<ResourceBundle> RESOURCE_BUNDLES;
42
43         /**
44          * Serial number
45          */
46         private static final long serialVersionUID = 18_605_498_672_261L;
47
48         /**
49          * Static initializer
50          */
51         static {
52                 // Init resource bundle list
53                 RESOURCE_BUNDLES = new ArrayList<>(3);
54         }
55
56         /**
57          * Removes all bundles from web application. Typically you want to invoke
58          * this method in a ServletContextListener implementation on the
59          * contextDestroyed() method.
60          */
61         public static void removeBundles () {
62                 // Clear bundles
63                 RESOURCE_BUNDLES.clear();
64         }
65
66         /**
67          * Getter for resource bundle list
68          * <p>
69          * @return Resource bundle list
70          */
71         @SuppressWarnings ("ReturnOfCollectionOrArrayField")
72         protected static List<ResourceBundle> getBundles () {
73                 return RESOURCE_BUNDLES;
74         }
75
76         /**
77          * Protected constructor
78          */
79         protected BaseFacesBean () {
80                 // Call super constructor
81                 super();
82         }
83
84         /**
85          * A filter for prices
86          * <p>
87          * @param value  Actual value to check
88          * @param filter Filter value to check against {@code value}
89          * @param locale Locale
90          * <p>
91          * @return Whether price ({@code value}) is at least {@code filter}
92          *
93          * @see https://www.primefaces.org/showcase/ui/data/datatable/filter.xhtml
94          */
95         @SuppressWarnings ("unchecked")
96         public boolean filterByPrice (final Object value, final Object filter, final Locale locale) {
97                 // Get trimmed string or NULL
98                 final String filterText = (filter == null) ? null : filter.toString().trim();
99
100                 // Is null or empty?
101                 if (filterText == null || filterText.isEmpty()) {
102                         // Then return TRUE
103                         return true;
104                 }
105
106                 // Is value NULL or not castable?
107                 if (value == null) {
108                         // Return FALSE
109                         return false;
110                 } else if (!(value instanceof Comparable)) {
111                         // Not castable
112                         throw new ClassCastException("value is not instance of Comparable");
113                 }
114
115                 // Do the cast and compare
116                 return ((Comparable<BigDecimal>) value).compareTo(BigDecimal.valueOf(Double.valueOf(filterText))) > 0;
117         }
118
119         /**
120          * Determines principal's name or returns null if no principal (security) is
121          * set.
122          * <p>
123          * @return Principal's name or null
124          */
125         protected String determinePrincipalName () {
126                 // Get principal
127                 final Principal userPrincipal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
128
129                 // Init with null
130                 String principalName = null;
131
132                 // Is the principal set?
133                 if (userPrincipal instanceof Principal) {
134                         // Get principal's name
135                         principalName = userPrincipal.getName();
136                 }
137
138                 // Return it
139                 return principalName;
140         }
141
142         /**
143          * Returns given property key or throws an exception if not found.
144          * <p>
145          * @param parameterKey Property key
146          * <p>
147          * @return Property value
148          */
149         protected int getIntegerContextParameter (final String parameterKey) throws NullPointerException, NumberFormatException {
150                 // Get context parameter
151                 final Integer contextValue = Integer.parseInt(this.getStringContextParameter(parameterKey));
152
153                 // Return it
154                 return contextValue;
155         }
156
157         /**
158          * Returns a message based on given i18nKey or puts it into three question
159          * marks each side when not found.
160          * <p>
161          * @param i18nKey I18n key
162          * <p>
163          * @return Localized message
164          * <p>
165          * @throws NullPointerException If the parameter is null
166          * @throws IllegalArgumentException If the parameter is empty
167          */
168         protected String getMessageFromBundle (final String i18nKey) {
169                 // Validate parameter
170                 if (null == i18nKey) {
171                         // Throw NPE
172                         throw new NullPointerException("i18nKey is null"); //NOI18N
173                 } else if (i18nKey.isEmpty()) {
174                         // Is empty
175                         throw new IllegalArgumentException("i18nKey is empty"); //NOI18N
176                 }
177
178                 // Get current locale
179                 final Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
180
181                 // Get bundle bundle
182                 this.loadResourceBundles(locale);
183
184                 // Default is i18nKey
185                 String message = MessageFormat.format("???{0}???", i18nKey); //NOI18N
186
187                 // Loop through all
188                 for (final ResourceBundle bundle : getBundles()) {
189                         // Found message?
190                         // Try it
191                         try {
192                                 // Get message
193                                 message = bundle.getString(i18nKey);
194                                 break;
195                         } catch (final MissingResourceException ex) {
196                                 // Did not find it, ignored
197                         }
198                 }
199
200                 // Return it
201                 return message;
202         }
203
204         /**
205          * Returns given property key or throws an exception if not found.
206          * <p>
207          * @param parameterKey Property key
208          * <p>
209          * @return Property value
210          * <p>
211          * @throws NullPointerException If given key is not found
212          */
213         protected String getStringContextParameter (final String parameterKey) throws NullPointerException {
214                 // Get context parameter
215                 final String contextValue = FacesContext.getCurrentInstance().getExternalContext().getInitParameter(parameterKey);
216
217                 // Is it null?
218                 if (null == contextValue) {
219                         // Throw NPE
220                         throw new NullPointerException(MessageFormat.format("parameterKey={0} is not set.", parameterKey)); //NOI18N
221                 }
222
223                 // Return it
224                 return contextValue;
225         }
226
227         /**
228          * Checks whether debug mode is enabled for given controller
229          * <p>
230          * @param controllerName Name of controller
231          * <p>
232          * @return Whether debug mode is enabled
233          */
234         protected boolean isDebugModeEnabled (final String controllerName) {
235                 // Parameters should be valid
236                 if (null == controllerName) {
237                         // Throw NPE
238                         throw new NullPointerException("controllerName is null"); //NOI18N
239                 } else if (controllerName.isEmpty()) {
240                         // Is empty
241                         throw new IllegalArgumentException("controllerName is empty"); //NOI18N
242                 }
243
244                 // Try to get context parameter
245                 final String contextParameter = this.getStringContextParameter(String.format("is_debug_%s_enabled", controllerName)); //NOI18N
246
247                 // Is it set and true?
248                 final boolean isEnabled = Boolean.parseBoolean(contextParameter) == Boolean.TRUE;
249
250                 // Return it
251                 return isEnabled;
252         }
253
254         /**
255          * Loads resource bundles for given locale. This must be implemented per
256          * project so all projects can still customize their methods. Calling
257          * ResourceBundleloadBundle() in this class means that also the bundle files
258          * must be present here.
259          * <p>
260          * @param locale Locale from e.g. FacesContext
261          */
262         protected abstract void loadResourceBundles (final Locale locale);
263
264         /**
265          * Shows a faces message for given causing exception. The message from the
266          * exception is being inserted into the message.
267          * <p>
268          * @param clientId Client id to send message to
269          * @param cause    Causing exception
270          */
271         protected void showFacesMessage (final String clientId, final Throwable cause) {
272                 // Get context and add message
273                 this.showFacesMessage(clientId, cause.getMessage());
274         }
275
276         /**
277          * Shows a faces message with given message (i18n) key.
278          * <p>
279          * @param clientId Client id to send message to
280          * @param i18nKey  Message key
281          * <p>
282          * @throws NullPointerException If clientId or i18nKey is null
283          * @throws IllegalArgumentException If clientId or i18nKey is empty
284          */
285         protected void showFacesMessage (final String clientId, final String i18nKey) throws NullPointerException, IllegalArgumentException {
286                 // Both parameter must be valid
287                 if (null == clientId) {
288                         // Throw NPE
289                         throw new NullPointerException("clientId is null"); //NOI18N
290                 } else if (clientId.isEmpty()) {
291                         // Is empty
292                         throw new IllegalArgumentException("clientId is null"); //NOI18N
293                 } else if (null == i18nKey) {
294                         // Throw NPE
295                         throw new NullPointerException("i18nKey is null"); //NOI18N
296                 } else if (i18nKey.isEmpty()) {
297                         // Is empty
298                         throw new IllegalArgumentException("i18nKey is null"); //NOI18N
299                 }
300
301                 // Get message from bundle
302                 final String message = this.getMessageFromBundle(i18nKey);
303
304                 // Get context and add message
305                 FacesContext.getCurrentInstance().addMessage(clientId, new FacesMessage(message));
306         }
307
308 }