com.miserablemind.butter.helpers.Utilities.java Source code

Java tutorial

Introduction

Here is the source code for com.miserablemind.butter.helpers.Utilities.java

Source

/*
 * Miserable Mind
 * http://www.butter.miserablemind.com
 * The MIT License (MIT)
 */

package com.miserablemind.butter.helpers;

import com.miserablemind.butter.domain.model.user.user.AppUser;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * A helper class of static methods that do not fall under any domain.
 *
 * @author miserablemind
 */

public class Utilities {

    /**
     * Gets Authenticated User Id from {@link SecurityContext}. Intended use: DAO for "updaterId" audit field population in database.
     *
     * @return {@code 0} if no context, no principal or principal is {@code anonymousUser}, otherwise UserId.
     */
    public static long getAuthUserId() {

        SecurityContext securityContext = Utilities.getSecurityContext();
        if (securityContext == null)
            return 0;
        Object principal = securityContext.getAuthentication().getPrincipal();
        if (principal == null || principal == "anonymousUser")
            return 0;
        AppUser user = (AppUser) principal;
        return user.getId();
    }

    /**
     * Gets {@link SecurityContext} From Active HTTP Session.
     *
     * @return {@link SecurityContext}
     */
    public static SecurityContext getSecurityContext() {
        HttpSession session = Utilities.getSession();
        return (SecurityContext) session.getAttribute("SPRING_SECURITY_CONTEXT");
    }

    /**
     * Gets Active Session from {@link RequestContextHolder}.
     *
     * @return {@link HttpSession}
     */
    public static HttpSession getSession() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return attr.getRequest().getSession(true);
    }

    /**
     * Centralized method for the system to validate e-mail addresses. The pattern is {@code .+@.+\.[a-z]+}.
     *
     * @param email e-mail address to validate
     * @return {@code true} if e-mail address format is correct
     */
    public static boolean isEmailValid(String email) {
        Pattern emailPattern = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher matcher = emailPattern.matcher(email);
        return matcher.matches();
    }

    /**
     * Generates random UUID with removed dashes.
     *
     * @return 32 Character Unique String
     */
    public static String generateUUID() {
        return java.util.UUID.randomUUID().toString().replace("-", "");
    }

}