]> git.mxchange.org Git - jcore-utils.git/blob - src/org/mxchange/jcoreee/bean/BaseBean.java
need to call super/default constructor, too.
[jcore-utils.git] / src / org / mxchange / jcoreee / bean / BaseBean.java
1 /*
2  * Copyright (C) 2017 Roland Häder
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;
18
19 import java.io.Serializable;
20 import java.security.Principal;
21 import java.text.MessageFormat;
22 import java.util.Locale;
23 import java.util.MissingResourceException;
24 import java.util.ResourceBundle;
25 import javax.faces.FacesException;
26 import javax.faces.application.FacesMessage;
27 import javax.faces.context.FacesContext;
28 import javax.jms.Connection;
29 import javax.jms.JMSException;
30 import javax.jms.MessageProducer;
31 import javax.jms.ObjectMessage;
32 import javax.jms.Queue;
33 import javax.jms.QueueConnectionFactory;
34 import javax.jms.Session;
35 import javax.naming.Context;
36 import javax.naming.InitialContext;
37 import javax.naming.NamingException;
38 import org.mxchange.jcoreeelogger.beans.local.logger.Log;
39 import org.mxchange.jcoreeelogger.beans.local.logger.LoggerBeanLocal;
40
41 /**
42  * A generic bean class
43  * <p>
44  * @author Roland Häder<roland@mxchange.org>
45  */
46 public abstract class BaseBean implements Serializable {
47
48         /**
49          * Serial number
50          */
51         private static final long serialVersionUID = 18_305_698_567_265L;
52
53         /**
54          * Connection
55          */
56         private Connection connection;
57
58         /**
59          * Logger instance
60          */
61         @Log
62         private LoggerBeanLocal loggerBeanLocal;
63
64         /**
65          * Message producer
66          */
67         private MessageProducer messageProducer;
68
69         /**
70          * Mailer message queue
71          */
72         private Queue queue;
73
74         /**
75          * Session instance
76          */
77         private Session session;
78
79         /**
80          * This class' default protected constructor. Please call
81          * super("jms/project-queue-factory", "jms/project-email-queue"); if you
82          * need to send emails.
83          */
84         protected BaseBean () {
85                 try {
86                         // Get initial context
87                         Context context = new InitialContext();
88
89                         // Lookup logger
90                         this.loggerBeanLocal = (LoggerBeanLocal) context.lookup("java:global/jcore-logger-ejb/logger!org.mxchange.jcoreeelogger.beans.local.logger.LoggerBeanLocal"); //NOI18N
91                 } catch (final NamingException ex) {
92                         // Continue to throw
93                         throw new RuntimeException(MessageFormat.format("context.lookup() failed: {0}", ex.getMessage()), ex); //NOI18N
94                 }
95         }
96
97         /**
98          * Constructor with queue factory JNDI and email-queue JNDI names
99          * <p>
100          * @param factoryJndi    JNDI name for queue factory
101          * @param emailQueueJndi JNDI name for email queue
102          */
103         protected BaseBean (final String factoryJndi, final String emailQueueJndi) {
104                 // Call default constructor
105                 this();
106
107                 // Try it out
108                 try {
109                         // Get initial context
110                         Context context = new InitialContext();
111
112                         // Get factory from JMS resource
113                         QueueConnectionFactory connectionFactory = (QueueConnectionFactory) context.lookup(factoryJndi); //NOI18N
114
115                         // Lookup queue
116                         this.queue = (Queue) context.lookup(emailQueueJndi); //NOI18N
117
118                         // Create connection
119                         this.connection = connectionFactory.createConnection();
120
121                         // Init session instance
122                         this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
123
124                         // And message producer
125                         this.messageProducer = this.session.createProducer(this.queue);
126                 } catch (final NamingException | JMSException e) {
127                         // Continued to throw
128                         throw new FacesException(e);
129                 }
130         }
131
132         /**
133          * Determines principal's name or returns null if no principal (security) is
134          * set.
135          * <p>
136          * @return Principal's name or null
137          */
138         protected String determinePrincipalName () {
139                 // Get principal
140                 Principal userPrincipal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
141
142                 // Init with null
143                 String principalName = null;
144
145                 // Is the principal set?
146                 if (userPrincipal instanceof Principal) {
147                         // Get principal's name
148                         principalName = userPrincipal.getName();
149                 }
150
151                 // Return it
152                 return principalName;
153         }
154
155         /**
156          * Returns given property key or throws an exception if not found.
157          * <p>
158          * @param parameterKey Property key
159          * <p>
160          * @return Property value
161          * <p>
162          * @throws NullPointerException If given key is not found
163          * @throws NumberFormatException If no number is given in context parameter
164          */
165         protected int getIntegerContextParameter (final String parameterKey) throws NullPointerException, NumberFormatException {
166                 // Get context parameter
167                 Integer contextValue = Integer.parseInt(this.getStringContextParameter(parameterKey));
168
169                 // Return it
170                 return contextValue;
171         }
172
173         /**
174          * Getter for loggerBeanLocal
175          * <p>
176          * @return Logger instance
177          */
178         protected LoggerBeanLocal getLoggerBeanLocal () {
179                 return this.loggerBeanLocal;
180         }
181
182         /**
183          * Getter for configured message producer instance
184          * <p>
185          * @return Message producer
186          */
187         protected MessageProducer getMessageProducer () {
188                 return this.messageProducer;
189         }
190
191         /**
192          * Getter for configured session instance
193          * <p>
194          * @return Session
195          */
196         protected Session getSession () {
197                 return this.session;
198         }
199
200         /**
201          * Returns given property key or throws an exception if not found.
202          * <p>
203          * @param parameterKey Property key
204          * <p>
205          * @return Property value
206          * <p>
207          * @throws NullPointerException If given key is not found
208          */
209         protected String getStringContextParameter (final String parameterKey) throws NullPointerException {
210                 // Get context parameter
211                 String contextValue = FacesContext.getCurrentInstance().getExternalContext().getInitParameter(parameterKey);
212
213                 // Is it null?
214                 if (null == contextValue) {
215                         // Throw NPE
216                         throw new NullPointerException(MessageFormat.format("parameterKey={0} is not set.", parameterKey)); //NOI18N
217                 }
218
219                 // Return it
220                 return contextValue;
221         }
222
223         /**
224          * Checks whether debug mode is enabled for given controller
225          * <p>
226          * @param controllerName Name of controller
227          * <p>
228          * @return Whether debug mode is enabled
229          */
230         protected boolean isDebugModeEnabled (final String controllerName) {
231                 // Parameters should be valid
232                 if (null == controllerName) {
233                         // Throw NPE
234                         throw new NullPointerException("controllerName is null"); //NOI18N
235                 } else if (controllerName.isEmpty()) {
236                         // Is empty
237                         throw new IllegalArgumentException("controllerName is empty"); //NOI18N
238                 }
239
240                 // Try to get context parameter
241                 String contextParameter = this.getStringContextParameter(String.format("is_debug_%s_enabled", controllerName)); //NOI18N
242
243                 // Is it set and true?
244                 boolean isEnabled = (Boolean.parseBoolean(contextParameter) == Boolean.TRUE);
245
246                 // Return it
247                 return isEnabled;
248         }
249
250         /**
251          * Sends given message to configured queue
252          * <p>
253          * @param message Message to send
254          * <p>
255          * @throws JMSException if something went wrong
256          */
257         protected void sendMessage (final ObjectMessage message) throws JMSException {
258                 // Trace message
259                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.sendMessage: message={1} - CALLED!", this.getClass().getSimpleName(), message)); //NOI18N
260
261                 // The parameter should be valid
262                 if (null == message) {
263                         // Throw NPE
264                         throw new NullPointerException("message is null"); //NOI18N
265                 } else if (null == this.getMessageProducer()) {
266                         // Throw NPE again
267                         throw new NullPointerException("this.messageProvider is null"); //NOI18N
268                 }
269
270                 // Send it
271                 this.getMessageProducer().send(message);
272
273                 // Trace message
274                 this.getLoggerBeanLocal().logTrace(MessageFormat.format("{0}.sendMessage: EXIT!", this.getClass().getSimpleName())); //NOI18N
275         }
276
277         /**
278          * Shows a faces message for given causing exception. The message from the
279          * exception is being inserted into the message.
280          * <p>
281          * @param clientId Client id to send message to
282          * @param cause    Causing exception
283          */
284         protected void showFacesMessage (final String clientId, final Throwable cause) {
285                 // Get context and add message
286                 this.showFacesMessage(clientId, cause.getMessage());
287         }
288
289         /**
290          * Shows a faces message with given message (i18n) key.
291          * <p>
292          * @param clientId Client id to send message to
293          * @param i18nKey  Message key
294          * <p>
295          * @throws NullPointerException If clientId or i18nKey is null
296          * @throws IllegalArgumentException If clientId or i18nKey is empty
297          */
298         protected void showFacesMessage (final String clientId, final String i18nKey) throws NullPointerException, IllegalArgumentException {
299                 // Both parameter must be valid
300                 if (null == clientId) {
301                         // Throw NPE
302                         throw new NullPointerException("clientId is null"); //NOI18N
303                 } else if (clientId.isEmpty()) {
304                         // Is empty
305                         throw new IllegalArgumentException("clientId is null"); //NOI18N
306                 } else if (null == i18nKey) {
307                         // Throw NPE
308                         throw new NullPointerException("i18nKey is null"); //NOI18N
309                 } else if (i18nKey.isEmpty()) {
310                         // Is empty
311                         throw new IllegalArgumentException("i18nKey is null"); //NOI18N
312                 }
313
314                 // Get current locale
315                 Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
316
317                 // Get bundle bundle
318                 ResourceBundle bundle = ResourceBundle.getBundle("org.mxchange.localization.bundle", locale);
319
320                 // Default is i18nKey
321                 String message = MessageFormat.format("!{0}!", i18nKey); //NOI18N
322
323                 // Try it
324                 try {
325                         // Get message
326                         message = bundle.getString(i18nKey);
327                 } catch (final MissingResourceException ex) {
328                         // Did not find it, ignored
329                 }
330
331                 // Get context and add message
332                 FacesContext.getCurrentInstance().addMessage(clientId, new FacesMessage(message));
333         }
334
335 }