All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.evasion.common.Utils Maven / Gradle / Ivy

/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package com.evasion.common;

import java.lang.reflect.Field;
import java.security.Principal;
import java.text.MessageFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import javax.el.ValueExpression;
import javax.faces.FacesException;
import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.component.ValueHolder;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;

/**
 *
 * @author sebastien.glon
 */
public final class Utils {

    /**
     * LOGGER.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(
            Utils.class);

    /**
     * Constructeur de classe utilitaire.
     */
    private Utils() {
    }

    public static boolean isEmpty(final String var) {
        return (var == null || var.equals(""));
    }

    public static String getUserName() {
        return (String) getPrincipalProperty("name");
    }

    private static Object getPrincipalProperty(String property) {
        Object result = null;
        Principal user = getPrincipal();
        if (user == null) {
            return null;
        }

        try {
            LOGGER.debug("Principal type: " + user);
            BeanWrapperImpl wrapper = new BeanWrapperImpl(user);
            result = wrapper.getPropertyValue(property);
        } catch (BeansException e) {
            throw new javax.faces.FacesException(e);
        }
        escapeEntities(String.valueOf(result));
        return result;
    }

    public static Date getUserLastLogin() {
        Calendar date = new GregorianCalendar();
        if (getPrincipalProperty("lastLogin") != null) {
            date.setTime((Date) getPrincipalProperty("lastLogin"));
        }
        return date.getTime();
    }

    private static Principal glassfishWorkAround(HttpServletRequest request) {
        Principal evPrincipal = null;
        try {

            Principal webPrincipal = request.getUserPrincipal();
            if (webPrincipal != null) {
                LOGGER.debug("UserPrincipâl type: {}", webPrincipal.getClass().getName());
                Class clazzGlassfish = Class.forName("com.sun.enterprise.security.web.integration.WebPrincipal");
                Class clazzEvasion = Class.forName("com.evasion.sam.jaas.EvasionPrincipal");
                if (clazzEvasion.isInstance(webPrincipal)) {
                    evPrincipal = webPrincipal;
                } else if (clazzGlassfish.isInstance(webPrincipal)) {
                    Field customPrincipal = clazzGlassfish.getDeclaredField("customPrincipal");
                    customPrincipal.setAccessible(true);
                    evPrincipal = (Principal) customPrincipal.get(webPrincipal);

                }
            }
        } catch (IllegalArgumentException ex) {
            LOGGER.error("glassfishWorkAround", ex);
        } catch (IllegalAccessException ex) {
            LOGGER.error("glassfishWorkAround", ex);
        } catch (NoSuchFieldException ex) {
            LOGGER.error("glassfishWorkAround", ex);
        } catch (SecurityException ex) {
            LOGGER.error("glassfishWorkAround", ex);
        } catch (ClassNotFoundException ex) {
            LOGGER.error("glassfishWorkAround", ex);
        }
        return evPrincipal;
    }

    public static Principal getPrincipal() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        ExternalContext extContext = ctx.getExternalContext();
        return glassfishWorkAround((HttpServletRequest) extContext.getRequest());
    }

    public static boolean isDebugMode() {
//@TODO créer une gestion de debug pour les messages et le debug jsf.
        return false;
    }

    public static boolean ifAuthenticated(Boolean ifAuthenticated) {
        return ifAuthenticated.equals(getPrincipal() != null);
    }

    public static boolean ifUserInRole(String var) {
        FacesContext ctx = FacesContext.getCurrentInstance();
        ExternalContext extContext = ctx.getExternalContext();
        return ((HttpServletRequest) extContext.getRequest()).isUserInRole(var);
    }

    public static void setSessionAttribut(String key, Object object) {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        request.getSession().setAttribute(key, object);
    }

    public static Object getSessionAttribut(String key) {
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
        return request.getSession().getAttribute(key);
    }

    protected static ClassLoader getCurrentClassLoader(Object defaultObject) {

        ClassLoader loader = Thread.currentThread().getContextClassLoader();

        if (loader == null) {
            loader = defaultObject.getClass().getClassLoader();
        }

        return loader;
    }

    public static String getMessageResourceString(String key, Object params[]) {
        FacesContext context = FacesContext.getCurrentInstance();
        String bundleName = context.getApplication().getMessageBundle();
        return getMessageResourceString(bundleName, key, params, null);
    }

    public static String getMessageResourceString(String bundleName, String key,
            Object params[],
            Locale locale) {

        String text = null;

        if (locale == null) {
            FacesContext context = FacesContext.getCurrentInstance();
            locale = context.getViewRoot().getLocale();
        }
        ResourceBundle bundle =
                ResourceBundle.getBundle(bundleName, locale,
                getCurrentClassLoader(params));

        try {
            text = bundle.getString(key);
        } catch (MissingResourceException e) {
            text = "?? key " + key + " not found ??";
        }

        if (params != null) {
            MessageFormat mf = new MessageFormat(text, locale);
            text = mf.format(params, new StringBuffer(), null).toString();
        }

        return text;
    }

    public static String escapeEntities(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c == '<') {
                sb.append("<");
            } else if (c == '>') {
                sb.append(">");
            } else if (c == '"') {
                sb.append(""");
            } else if (c == '\'') {
                sb.append("'");
            } else if (c == '&') {
                sb.append("&");
            } else {
                sb.append(c);
            }
        }

        return sb.toString();
    }

    public static UIComponent findParentForm(FacesContext context, UIComponent component) {
        UIComponent parent = component.getParent();
        while (parent != null) {
            if (parent instanceof UIForm) {
                return parent;
            }
            parent = parent.getParent();
        }
        return null;
    }

    public static String formatKeywords(FacesContext facesContext, UIComponent component, String processRequest) {
        String process = processRequest;

        if (process.indexOf("@this") != -1) {
            process = process.replaceFirst("@this", component.getClientId(facesContext));
        }
        if (process.indexOf("@form") != -1) {
            UIComponent form = Utils.findParentForm(facesContext, component);
            if (form == null) {
                throw new FacesException("Component " + component.getClientId(facesContext) + " needs to be enclosed in a form");
            }

            process = process.replaceFirst("@form", form.getClientId(facesContext));
        }
        if (process.indexOf("@parent") != -1) {
            process = process.replaceFirst("@parent", component.getParent().getClientId(facesContext));
        }

        return process;
    }

    public static String findClientIds(FacesContext facesContext, UIComponent component, String list) {
        if (list == null) {
            return "@none";
        }

        String formattedList = formatKeywords(facesContext, component, list);
        String[] ids = formattedList.split("[,\\s]+");
        StringBuilder buffer = new StringBuilder();

        for (int i = 0; i < ids.length; i++) {
            if (i != 0) {
                buffer.append(" ");
            }

            String id = ids[i].trim();

            if (id.equals("@all") || id.equals("@none")) {
                buffer.append(id);
            } else {
                UIComponent comp = component.findComponent(id);
                if (comp != null) {
                    buffer.append(comp.getClientId(facesContext));
                } else {
                    buffer.append(id);
                }
            }
        }

        return buffer.toString();
    }
    
    	/**
	 * Resolves the end text to render by using a specified value
	 * 
	 * @param context			FacesContext instance
	 * @param component			UIComponent instance whose value will be returned
	 * @return					End text
	 */
	public static String getStringValueToRender(FacesContext facesContext, UIComponent component, Object value) {
		if(value == null || !ValueHolder.class.isInstance(component))
			return null;
		
		ValueHolder valueHolder = (ValueHolder) component;
		
		Converter converter = valueHolder.getConverter();
		if(converter != null) {
			return converter.getAsString(facesContext, component, value);
		}
		else {
			ValueExpression expr = component.getValueExpression("value");
			if(expr != null) {
				Class valueType = expr.getType(facesContext.getELContext());
				Converter converterForType = facesContext.getApplication().createConverter(valueType);
				
				if(converterForType != null)
					return converterForType.getAsString(facesContext, component, value);
			}
		}
		
		return value.toString();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy