+ /**
+ * Generates a secure, unique hash for given email address change. This
+ * requires to check if the hash is really not there.
+ * <p>
+ * @param emailAddress Email address change
+ */
+ private void generateSecureHash (final ChangeableEmailAddress emailAddress) {
+ // Email address change should be valid
+ if (null == emailAddress) {
+ // Abort here
+ throw new NullPointerException("emailAddress is null"); //NOI18N
+ } else if (emailAddress.getEmailAddress().trim().isEmpty()) {
+ // Email address is empty
+ throw new IllegalArgumentException("emailAddress.emaiLAddress is empty."); //NOI18N
+ }
+
+ // Initialize loop with null
+ String hash = null;
+
+ // Default is not used
+ boolean isUsed = true;
+
+ // Search for free hash
+ while (isUsed) {
+ // Generate hash, there is already in UserUtils a nice method that can be used for this purpose.
+ hash = UserUtils.encryptPassword(String.format("%s:%s", emailAddress.getEmailAddress(), emailAddress.toString())); //NOI18N
+
+ // The hash *may* be unique, better test it
+ Query query = this.getEntityManager().createNamedQuery("SearchEmailChangeByHash", EmailAddressChange.class); //NOI18N
+
+ // Set hash as parameter
+ query.setParameter("hash", hash); //NOI18N
+
+ // Try to get single result
+ try {
+ // Get single result
+ ChangeableEmailAddress dummy = (ChangeableEmailAddress) query.getSingleResult();
+ } catch (final NoResultException ex) {
+ // Not found
+ isUsed = false;
+ }
+ }
+
+ // hash should not be null and set
+ assert (hash != null) : "hash is null"; //NOI18N
+ assert (!hash.isEmpty()) : "hash is empty"; //NOI18N
+
+ // Set it in email change
+ emailAddress.setEmailChangeHash(hash);
+ }
+