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

org.fryske_akademy.jsf.util.JsfUtil Maven / Gradle / Ivy

The newest version!
package org.fryske_akademy.jsf.util;

/*-
 * #%L
 * guiCrudApi
 * %%
 * Copyright (C) 2018 Fryske Akademy
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.fryske_akademy.Util;

public class JsfUtil {

    private static final Logger LOGGER = Logger.getLogger(JsfUtil.class.getName());

    /**
     * Calls {@link FacesContext#validationFailed() }, {@link #deepestCause(java.lang.Throwable)
     * } and {@link #addErrorMessage(java.lang.String) } with the prefix and the
     * localized message from the exception. rethrows the exception
     *
     * @param ex
     * @param prefix
     */
    public static void handleException(Exception ex, String prefix) throws Exception {
        FacesContext.getCurrentInstance().validationFailed();
        addErrorMessage(prefix + Util.deepestCause(ex).getLocalizedMessage());
        throw ex;
    }

    public static boolean isValidationFailed() {
        return FacesContext.getCurrentInstance().isValidationFailed();
    }

    public static void addErrorMessage(Exception ex, String defaultMsg) {
        String msg = ex.getLocalizedMessage();
        if (msg != null && msg.length() > 0) {
            addErrorMessage(msg);
        } else {
            addErrorMessage(defaultMsg);
        }
    }

    public static void addErrorMessages(List messages) {
        for (String message : messages) {
            addErrorMessage(message);
        }
    }

    /**
     * uses null as clientId
     *
     * @param msg
     */
    public static void addErrorMessage(String msg) {
        String cid = null;
        addErrorMessage(cid, msg);
    }

    public static void addErrorMessage(String clientId, String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
        FacesContext.getCurrentInstance().addMessage(clientId, facesMsg);
    }

    /**
     * Uses successInfo as client id
     *
     * @param msg
     */
    public static void addSuccessMessage(String msg) {
        addSuccessMessage("successInfo", msg);
    }

    public static void addSuccessMessage(String clientId, String msg) {
        FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
        FacesContext.getCurrentInstance().addMessage(clientId, facesMsg);
    }

    /**
     * Calls {@link #findInContext(java.lang.String, java.lang.Class) } with clazz.simpleName, first letter lowerCase
     * @param 
     * @param clazz
     * @return 
     */
    public static  T findInContext(Class clazz) {
        return findInContext(Character.toLowerCase(clazz.getSimpleName().charAt(0)) + clazz.getSimpleName().substring(1), clazz);
    }
    
    public static  T findInContext(String name, Class clazz) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        return (T) facesContext.getApplication().getELResolver().
                getValue(facesContext.getELContext(), null, name);
    }

    public static  T findOrCreateInContext(String name, Class clazz) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        return (T) facesContext.getApplication().evaluateExpressionGet(facesContext, name, clazz);
    }

    public static Converter getConverter(Class clazz) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        return facesContext.getApplication().createConverter(clazz);
    }

    /**
     * context path plus servlet path
     *
     * @return
     */
    public static String fullServletPath() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        return externalContext.getRequestContextPath() + externalContext.getRequestServletPath();
    }

    public static String contextPath() {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        return externalContext.getRequestContextPath();
    }
    
    public static void redirectToServletPath(String servletPath) throws IOException {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
        externalContext.redirect(externalContext.getRequestContextPath() + servletPath);
    }

    public static void logout() throws ServletException {
        FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
        ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).logout();
    }

    private static final ResourceBundle rootBundle = ResourceBundle.getBundle("EMPTY", Locale.ROOT);

    /**
     * return a resource for the current locale (from faces context or default locale), or an empty bundle
     *
     * @param bundle
     * @return
     */
    public static ResourceBundle getLocaleBundle(String bundle) {
        Locale loc = FacesContext.getCurrentInstance()!=null?FacesContext.getCurrentInstance().getViewRoot().getLocale():Locale.getDefault();
        try {
            return ResourceBundle.getBundle(bundle, loc);
        } catch (MissingResourceException e) {
            LOGGER.warning("resource not found: " + bundle + ", returning EMPTY");
            return rootBundle;
        }

    }
    
    public static String getFromBundle(ResourceBundle bundle, String key) {
        if (bundle.containsKey(key)) {
            return bundle.getString(key);
        } else {
            LOGGER.warning(String.format("%s not found in language bundle %s", key, bundle));
            return key;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy