]> git.mxchange.org Git - jjobs-war.git/blob - src/java/org/mxchange/jjobs/validator/emailaddress/JobsEmailAddressValidator.java
c6bf66ae5daf15fcbd4c5c8bb00523467f9806a4
[jjobs-war.git] / src / java / org / mxchange / jjobs / validator / emailaddress / JobsEmailAddressValidator.java
1 /*
2  * Copyright (C) 2016, 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 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.jjobs.validator.emailaddress;
18
19 import java.text.MessageFormat;
20 import java.util.regex.Pattern;
21 import javax.faces.application.FacesMessage;
22 import javax.faces.component.UIComponent;
23 import javax.faces.context.FacesContext;
24 import javax.faces.validator.FacesValidator;
25 import javax.faces.validator.Validator;
26 import javax.faces.validator.ValidatorException;
27 import javax.naming.Context;
28 import javax.naming.InitialContext;
29 import javax.naming.NamingException;
30 import org.mxchange.jcontacts.contact.ContactSessionBeanRemote;
31 import org.mxchange.jcoreee.validator.string.BaseStringValidator;
32
33 /**
34  * A validator for email address validation
35  * <p>
36  * @author Roland Häder<roland@mxchange.org>
37  */
38 @FacesValidator ("EmailAddressValidator")
39 public class JobsEmailAddressValidator extends BaseStringValidator implements Validator {
40
41         /**
42          * Contact session-scoped bean
43          */
44         private static ContactSessionBeanRemote CONTACT_BEAN;
45
46         /**
47          * Pattern matcher
48          */
49         private static final Pattern EMAIL_PATTERN = Pattern.compile(JobsEmailAddressValidator.EMAIL_REGEX);
50
51         /**
52          * Email pattern
53          */
54         private static final String EMAIL_REGEX = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"; //NOI18N
55
56         /**
57          * Serial number
58          */
59         private static final long serialVersionUID = 187_536_745_607_192L;
60
61         /**
62          * Default constructor
63          */
64         public JobsEmailAddressValidator () {
65         }
66
67         @Override
68         public void validate (final FacesContext context, final UIComponent component, final Object value) throws ValidatorException {
69                 System.out.println("validate: value=" + value); //NOI18N
70                 // The required field
71                 String[] requiredFields = {"emailAddress", "emailAddressRepeat", "resendEmailAddress"}; //NOI18N
72
73                 // Default is to reject empty email address fields
74                 Boolean allowEmptyEmail = Boolean.FALSE;
75
76                 // Is attribute "allowEmptyEmail" set?
77                 if (component.getAttributes().containsKey("allowEmptyEmail")) { //NOI18N
78                         // Get attribute
79                         Object attribute = component.getAttributes().get("allowEmptyEmail"); //NOI18N
80                         System.out.println("attribute=" + attribute); //NOI18N
81
82                         // Make sure, it is Boolean as no String is accepted anymore
83                         if (!(attribute instanceof String)) {
84                                 // Not valid attribute, please use "true" or "false" (default)
85                                 throw new IllegalArgumentException("allowEmptyEmail must be of type String. Please use \"true\" or \"false\" for f:attribute value."); //NOI18N
86                         }
87
88                         // Securely cast it
89                         allowEmptyEmail = Boolean.parseBoolean((String) attribute);
90                 }
91
92                 // Pre-validation (example: not null, not a string, empty string ...)
93                 super.preValidate(context, component, value, requiredFields, allowEmptyEmail);
94
95                 // Is the email address empty and allowed?
96                 if (null == value && allowEmptyEmail) {
97                         // Then accept this here
98                         return;
99                 } else if (null == value) {
100                         // Abort here
101                         throw new ValidatorException(new FacesMessage("No empty email address allowed.")); //NOI18N
102                 }
103
104                 // Get string from object ... ;-)
105                 // @TODO Add IDN support (GNU lib?) Search for emailAddressRepeat
106                 String emailAddress = String.valueOf(value).trim();
107
108                 // Checks if the email address matches a regex ("low-level" check)
109                 // @TODO Should also be done by <f:validatorRegex />)
110                 boolean matches = EMAIL_PATTERN.matcher(emailAddress).matches(); //NOI18N
111
112                 // Is the email address valid?
113                 if (!matches) {
114                         // Generate message
115                         String message = MessageFormat.format("Email address {0} does not match regular expression.", emailAddress); //NOI18N
116
117                         // Not matching
118                         throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, message, message));
119                 }
120
121                 // Is the bean not yet set?
122                 // @TODO Requires this synchronization or is it (sync) confusing the container?
123                 if (null == JobsEmailAddressValidator.CONTACT_BEAN) {
124                         // Try it
125                         try {
126                                 // Get initial context
127                                 Context initialContext = new InitialContext();
128
129                                 // Try to lookup
130                                 JobsEmailAddressValidator.CONTACT_BEAN = (ContactSessionBeanRemote) initialContext.lookup("java:global/jjobs-ejb/contact!org.mxchange.jcontacts.contact.ContactSessionBeanRemote"); //NOI18N
131                         } catch (final NamingException ex) {
132                                 // Continue to throw it
133                                 throw new ValidatorException(new FacesMessage(MessageFormat.format("initialContext.lookup() failed: {0}", ex.getMessage())), ex); //NOI18N
134                         }
135                 }
136
137                 // Get client id (aka form id)
138                 String clientId = component.getClientId();
139
140                 // Is it registered?
141                 Boolean isRegistered = JobsEmailAddressValidator.CONTACT_BEAN.isEmailAddressRegistered(emailAddress);
142
143                 // Is the email address already registered?
144                 if ((!clientId.endsWith("resendEmailAddress")) && (isRegistered)) { //NOI18N
145                         // Generate message
146                         String message = MessageFormat.format("Email address {0} is already registered.", emailAddress); //NOI18N
147
148                         // No, then abort here
149                         throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_INFO, message, message));
150                 } else if ((clientId.endsWith("resendEmailAddress")) && (!isRegistered)) { //NOI18N
151                         // Generate message
152                         String message = MessageFormat.format("Email address {0} is not registered.", emailAddress); //NOI18N
153
154                         // No, then abort here
155                         throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_INFO, message, message));
156                 }
157         }
158
159 }