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

org.xlcloud.console.controllers.i18n.MessageController Maven / Gradle / Ivy

The newest version!
/*
 * Copyright 2012 AMG.lab, a Bull Group Company
 * 
 * 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.
 */
package org.xlcloud.console.controllers.i18n;

import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.MissingResourceException;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;
import javax.inject.Named;

import org.apache.log4j.Logger;
import org.xlcloud.rest.exception.BaseException;

/**
 * This class is meant to give (simplify) an access to resource bundle messages.
 * 
 * @author Piotr Kulasek-Szwed, AMG.net
 * @author "Konrad Król", AMG.net
 * @author Krzysztof Szafrański, AMG.net
 */
@Named
public class MessageController implements Serializable, MessageResolver {
    
    private static final String PREVENT_MESSAGES_AUTO_UPDATE_ATTRIBUTE = "preventMessagesAutoUpdate";
    private static final String MESSAGES_TO_PREVENT = "messagesToPrevent";
    
    /**
     * Documentation serialVersionUID
     */
    private static final long serialVersionUID = 1L;

    private static Logger LOG = Logger.getLogger(MessageController.class);

    public static final String RESOURCE_BUNDLE_VAR = "msg";

    /**
     * Adds message to markup. Usually accessible via
     * {@code }
     * 
     * @param key
     *            resource bundle key
     */
    public void addMessage(String key) {
        FacesMessage facesMessage = getFacesMessage(key);
        /*
         * workaround for facesMessages that are rendered with same
         * details and summary (without that, same message bundle is presented
         * twice)
         */
        if (facesMessage.getDetail() == null || facesMessage.getDetail().equals(facesMessage.getSummary())) {
            facesMessage.setDetail("");
        }
        this.getFacesContext().addMessage(null, facesMessage);
    }

    /**
     * Adds message to markup. Usually accessible via
     * {@code }
     * 
     * @param key
     *            resource bundle key
     */
    public void addMessage(String key, String... messageParams) {
        FacesMessage facesMessage = getFacesMessage(key, messageParams);

        if (facesMessage.getDetail() == null || facesMessage.getDetail().equals(facesMessage.getSummary())) {
            facesMessage.setDetail("");
        }
        this.getFacesContext().addMessage(null, facesMessage);
    }

    /**
     * Adds an error message to current faces context.
     * 
     * @param message
     *            error message
     */
    public void addError(String message) {
        addError(getValue("error"), message);
    }

    public void addLocalizedError(BaseException exception) {
        addLocalizedError(exception, null);
    }
    
    public void addLocalizedError(BaseException exception, String errorKey) {
        LocalizedExceptionResolver localizedExceptionResolver = new LocalizedExceptionResolver(this, exception, errorKey);
        addError(localizedExceptionResolver.getErrorText(), localizedExceptionResolver.getDetailsText());
    }

    /**
     * Adds warning message to current faces context.
     * 
     * @param message
     *            warning message
     */
    public void addWarning(String message) {
        this.getFacesContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, getValue("warn"), message));
        LOG.warn(message);
    }

    /**
     * Adds an error message to current faces context.
     * 
     * @param message
     *            error message
     * @param details
     *            error details
     */
    public void addError(String message, String details) {
        if (details != null) {
            this.getFacesContext().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, details));
        } else {
            this.addError(message);
        }

        LOG.error(message);
    }

    /**
     * Adds an error message to current faces context. The message is identified
     * by specified key.
     * 
     * @param key
     *            key of the error message
     */
    public void addErrorMessage(String key) {
        addError(getValue(key));
    }

    /**
     * Adds an error message to current faces context. The message is identified
     * by specified key.
     * 
     * @param key
     *            - key of the error message
     * @param details
     *            - eror message details
     */
    public void addErrorMessage(String key, String details) {
        addError(getValue(key), details);
    }

    /**
     * Adds error message with parameters. Replaces all "{}" with paramerers in
     * order of occurance
     * 
     * @param key
     * @param params
     */
    public void addErrorMessageWithParams(String key, String... params) {
        String message = getValue(key);
        message = applyParams(message, params);
        addError(message);
    }

    /**
     * @param message
     * @param params
     * @return
     */
    public String applyParams(String message, String... params) {
        MessageFormat messageFormat = new MessageFormat(message);
        return messageFormat.format(params);
    }

    /**
     * Adds a warning message to current faces context. Message must be defined
     * in i18n bundle
     * 
     * @param key
     *            key for warning message bundle
     */
    public void addWarningMessage(String key) {
        addWarning(getValue(key));
    }

    @Override
    public String getValue(String key) {
        return getValue(key, true);
    }
    
    public String getValue(String key, boolean useDefault) {
        try {
            return this.getFacesContext().getApplication().getResourceBundle(this.getFacesContext(), RESOURCE_BUNDLE_VAR).getString(key);
        } catch(MissingResourceException e) {
            if(useDefault) {
                return "???"+key+"???";
            } else {
                throw e;
            }
        }
    }

    /**
     * It allows to keep current flash messages, when messages autoUpdate is enabled.
     * 
     * It prevents autoupdate of the following components:
     *  - global messages component identified by {@link #MESSAGES_COMPONTENT_ID}
     *  - messages components identified by ids registered in {@link MessageComponentBean}
     *  
     * Any other messages component will be updated.
     */
    public void preventMessagesAutoUpdate() {
        this.getFacesContext().getAttributes().put(PREVENT_MESSAGES_AUTO_UPDATE_ATTRIBUTE, Boolean.TRUE);
    }
    
    /**
     * This method is called by f:event tags associated with p:messages components.
     * @param event
     */
    public void messagesPostAddToView(ComponentSystemEvent event) {
        Map attributes = getFacesContext().getAttributes();
        @SuppressWarnings( "unchecked" )
        List messagesToPrevent = (List) attributes.get(MESSAGES_TO_PREVENT);
        if (messagesToPrevent == null) {
            messagesToPrevent = new ArrayList<>();
            attributes.put(MESSAGES_TO_PREVENT, messagesToPrevent);
        }
        
        messagesToPrevent.add(event.getComponent().getClientId());
    }

    /**
     * This method is called by f:event tag associated with the f:view component.
     * @param event
     */
    public void messagesPreRenderView(ComponentSystemEvent event) {
        FacesContext faces = getFacesContext();
        if (Boolean.TRUE.equals(faces.getAttributes().get(PREVENT_MESSAGES_AUTO_UPDATE_ATTRIBUTE))) {
            @SuppressWarnings( "unchecked" )
            List messagesToPrevent = (List) faces.getAttributes().get(MESSAGES_TO_PREVENT);
            if (messagesToPrevent != null) {
                for (String message : messagesToPrevent) {
                    faces.getPartialViewContext().getRenderIds().remove(message);
                }
            }
        }
    }

    private FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

    private FacesMessage getFacesMessage(String key, String... messageParams) {
        String message = getValue(key);
        message = applyParams(message, messageParams);
        return new FacesMessage(message);
    }

    /**
     * TODO Documentation
     * 
     * @param string
     * @param string2
     */
    public void addErrorMessageFor(String key, String messageFor) {
        addErrorFor(getValue(key), messageFor);
    }

    /**
     * Adds an error message to current faces context for object.
     * 
     * @param message
     *            error message
     */
    public void addErrorFor(String message, String messageFor) {
        this.getFacesContext().addMessage(messageFor, new FacesMessage(FacesMessage.SEVERITY_ERROR, getValue("error"), message));
        LOG.error(message);
    }

    /**
     * Adds an message to current faces context for object.
     * 
     * @param object
     * @param keypairMissingMessage
     */
    public void addMessageFor(String message, String messageFor) {
        this.getFacesContext().addMessage(messageFor, new FacesMessage(FacesMessage.SEVERITY_INFO, getValue("error"), message));
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy