Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Licensed to the Apache Software Foundation (ASF) under one
   * or more contributor license agreements.  See the NOTICE file
   * distributed with this work for additional information
   * regarding copyright ownership.  The ASF licenses this file
   * to you 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.apache.myfaces.shared.util;
 
 
Utility class to support multilingual FacesMessages using ResourceBundles. Standard messages are stored at DEFAULT_BUNDLE.
The summary of the message is stored at the requested key value. The detail of the message is stored at <messageId>_detail.

Author(s):
Thomas Spiegl (latest modification by $Author: lu4242 $)
Manfred Geiler
Sean Schofield
Stpehan Strittmatter
Version:
$Revision: 1378434 $ $Date: 2012-08-28 22:19:55 -0500 (Tue, 28 Aug 2012) $
See also:
javax.faces.application.FacesMessage
java.util.ResourceBundle
 
 public final class MessageUtils
 {
    
Utility class, do not instatiate
 
     private MessageUtils()
     {
         // nope
     }

    
Default bundle for messages (javax.faces.Messages)
 
     private static final String DEFAULT_BUNDLE = "javax.faces.Messages";

    
Suffix for message details (_detail
 
     private static final String DETAIL_SUFFIX = "_detail";
     //private static Log log = LogFactory.getLog(MessageUtils.class);
     private static Logger log = Logger.getLogger(MessageUtils.class.getName());

    

Parameters:
severity serverity of message
messageId id of message
arg arument of message
Returns:
generated FacesMessage
 
     public static FacesMessage getMessage(FacesMessage.Severity severity,
                                           String messageId,
                                           Object arg)
     {
         return getMessage(severity,
                           messageId,
                           new Object[]{arg},
                           FacesContext.getCurrentInstance());
     }
     
     public static FacesMessage getMessage(String bundleBaseName
             FacesMessage.Severity severity,
             String messageId,
             Object arg)
     {
         return getMessage(bundleBaseName,
                           severity,
                           messageId,
                           new Object[]{arg},
                           FacesContext.getCurrentInstance());
     }

    

Parameters:
severity serverity of message
messageId id of message
args aruments of message
Returns:
generated FacesMessage
    public static FacesMessage getMessage(FacesMessage.Severity severity,
                                          String messageId,
                                          Object[] args)
    {
        return getMessage(severity,
                          messageId,
                          args,
                          FacesContext.getCurrentInstance());
    }
    
    public static FacesMessage getMessage(String bundleBaseName
            FacesMessage.Severity severity,
            String messageId,
            Object[] args)
    {
        return getMessage(bundleBaseName,
                          severity,
                          messageId,
                          args,
                          FacesContext.getCurrentInstance());
    }    
    public static FacesMessage getMessage(FacesMessage.Severity severity,
                                          String messageId,
                                          Object[] args,
                                          FacesContext facesContext)
    {
        FacesMessage message = getMessage(facesContextmessageIdargs);
        message.setSeverity(severity);
        return message;
    }
    public static FacesMessage getMessage(String bundleBaseName,
            FacesMessage.Severity severity,
            String messageId,
            Object[] args,
            FacesContext facesContext)
    {
        FacesMessage message = getMessage(bundleBaseNamefacesContextmessageIdargs);
        message.setSeverity(severity);
        
        return message;
    }
    public static void addMessage(FacesMessage.Severity severity,
                                  String messageId,
                                  Object[] args)
    {
        addMessage(severitymessageIdargsnull, FacesContext.getCurrentInstance());
    }
    public static void addMessage(String bundleBaseName
            FacesMessage.Severity severity,
            String messageId,
            Object[] args)
    {
        addMessage(bundleBaseNameseveritymessageIdargsnull, FacesContext.getCurrentInstance());
    }
    public static void addMessage(FacesMessage.Severity severity,
                                  String messageId,
                                  Object[] args,
                                  FacesContext facesContext)
    {
        addMessage(severitymessageIdargsnullfacesContext);
    }
    public static void addMessage(String bundleBaseName
            FacesMessage.Severity severity,
            String messageId,
            Object[] args,
            FacesContext facesContext)
    {
        addMessage(bundleBaseNameseveritymessageIdargsnullfacesContext);
    }
    public static void addMessage(FacesMessage.Severity severity,
                                  String messageId,
                                  Object[] args,
                                  String forClientId)
    {
        addMessage(severitymessageIdargsforClientId, FacesContext.getCurrentInstance());
    }
    public static void addMessage(String bundleBaseName,
            FacesMessage.Severity severity,
            String messageId,
            Object[] args,
            String forClientId)
    {
        addMessage(bundleBaseNameseveritymessageIdargsforClientId, FacesContext.getCurrentInstance());
    }
    public static void addMessage(FacesMessage.Severity severity,
                                  String messageId,
                                  Object[] args,
                                  String forClientId,
                                  FacesContext facesContext)
    {
        if(.isLoggable(.))
        {
          .finest("adding message " + messageId + " for clientId " + forClientId);
        }
        facesContext.addMessage(forClientId,
                                getMessage(severitymessageIdargsfacesContext));
    }
    public static void addMessage(String bundleBaseName,
            FacesMessage.Severity severity,
            String messageId,
            Object[] args,
            String forClientId,
            FacesContext facesContext)
    {
        if(.isLoggable(.))
        {
          .finest("adding message " + messageId + " for clientId " + forClientId);
        }
        facesContext.addMessage(forClientId,
                  getMessage(bundleBaseNameseveritymessageIdargsfacesContext));
    }

    
Uses MessageFormat and the supplied parameters to fill in the param placeholders in the String.

Parameters:
locale The Locale to use when performing the substitution.
msgtext The original parameterized String.
params The params to fill in the String with.
Returns:
The updated String.
    public static String substituteParams(Locale localeString msgtextObject params[])
    {
        String localizedStr = null;
        if(params == null || msgtext == null)
        {
            return msgtext;
        }
        if(locale != null)
        {
            MessageFormat mf = new MessageFormat(msgtext,locale);            
            localizedStr = mf.format(params);
        }
        return localizedStr;
    }
    public static FacesMessage getMessage(String messageIdObject params[])
    {
        Locale locale = getCurrentLocale();
        return getMessage(localemessageIdparams);
    }
    public static FacesMessage getMessageFromBundle(String bundleBaseNameString messageIdObject params[])
    {
        Locale locale = null;
        FacesContext context = FacesContext.getCurrentInstance();
        if(context != null && context.getViewRoot() != null)
        {
            locale = context.getViewRoot().getLocale();
            if(locale == null)
            {
                locale = Locale.getDefault();
            }
        }
        else
        {
            locale = Locale.getDefault();
        }
        return getMessageFromBundle(bundleBaseNamecontext , localemessageIdparams);
    }
    public static FacesMessage getMessage(Locale localeString messageIdObject params[])
    {
        String summary = null;
        String detail = null;
        String bundleName = getApplication().getMessageBundle();
        ResourceBundle bundle = null;
        if (bundleName != null)
        {
            try
            {
                bundle = ResourceBundle.getBundle(bundleNamelocale
                        org.apache.myfaces.shared.util.ClassUtils.getCurrentLoader(bundleName));
                summary = bundle.getString(messageId);
            }
            catch (MissingResourceException e)
            {
                // NoOp
            }
        }
        if (summary == null)
        {
            try
            {
                bundle = ResourceBundle.getBundle(locale
                        org.apache.myfaces.shared.util.ClassUtils.getCurrentLoader());
                if(bundle == null)
                {
                    throw new NullPointerException();
                }
                summary = bundle.getString(messageId);
            }
            catch(MissingResourceException e)
            {
                // NoOp
            }
        }
        if(summary == null)
        {
            summary = messageId;
        }
        if (bundle == null)
        {
            throw new NullPointerException(
                "Unable to locate ResourceBundle: bundle is null");
        }
        if (params != null && locale != null)
        {
            try
            {
                detail = bundle.getString(messageId + );
            }
            catch(MissingResourceException e)
            {
                // NoOp
            }
            return new ParametrizableFacesMessage(summarydetailparamslocale);
        }
        else
        {
            summary = substituteParams(localesummaryparams);
            try
            {
                detail = substituteParams(locale,
                    bundle.getString(messageId + ), params);
            }
            catch(MissingResourceException e)
            {
                // NoOp
            }
            return new FacesMessage(summarydetail);
        }
    }
    
    public static FacesMessage getMessageFromBundle(String bundleBaseName
            FacesContext contextLocale localeString messageIdObject params[])
    {
        String summary = null;
        String detail = null;
        String bundleName = context.getApplication().getMessageBundle();
        ResourceBundle bundle = null;
        if (bundleName != null)
        {
            try
            {
                bundle = ResourceBundle.getBundle(bundleNamelocale
                        org.apache.myfaces.shared.util.ClassUtils.getCurrentLoader(bundleName));
                summary = bundle.getString(messageId);
            }
            catch (MissingResourceException e)
            {
                // NoOp
            }
        }
        if (summary == null)
        {
            try
            {
                bundle = ResourceBundle.getBundle(bundleBaseNamelocale
                        org.apache.myfaces.shared.util.ClassUtils.getCurrentLoader(bundleBaseName));
                if(bundle == null)
                {
                    throw new NullPointerException();
                }
                summary = bundle.getString(messageId);
            }
            catch(MissingResourceException e)
            {
                // NoOp
            }
        }
        
        if (summary == null)
        {
            try
            {
                bundle = ResourceBundle.getBundle(locale
                        org.apache.myfaces.shared.util.ClassUtils.getCurrentLoader());
                if(bundle == null)
                {
                    throw new NullPointerException();
                }
                summary = bundle.getString(messageId);
            }
            catch(MissingResourceException e)
            {
                // NoOp
            }
        }
        if(summary == null)
        {
            summary = messageId;
        }
        if (bundle == null)
        {
            throw new NullPointerException(
                "Unable to locate ResourceBundle: bundle is null");
        }
        
        if (params != null && locale != null)
        {
            try
            {
                detail = bundle.getString(messageId + );
            }
            catch(MissingResourceException e)
            {
                // NoOp
            }
            return new ParametrizableFacesMessage(summarydetailparamslocale);
        }
        else
        {
            summary = substituteParams(localesummaryparams);
            try
            {
                detail = substituteParams(locale,
                    bundle.getString(messageId + ), params);
            }
            catch(MissingResourceException e)
            {
                // NoOp
            }
            return new FacesMessage(summarydetail);
        }
    }

    
Retrieve the message from a specific bundle. It does not look on application message bundle or default message bundle. If it is required to look on those bundles use getMessageFromBundle instead

Parameters:
bundleBaseName baseName of ResourceBundle to load localized messages
messageId id of message
params parameters to set at localized message
Returns:
generated FacesMessage
    public static FacesMessage getMessage(String bundleBaseNameString messageIdObject params[])
    {
        return getMessage(bundleBaseNamegetCurrentLocale(), messageIdparams);
    }
    
    

Returns:
currently applicable Locale for this request.
    public static Locale getCurrentLocale()
    {
        return getCurrentLocale(FacesContext.getCurrentInstance());
    }
    
    public static Locale getCurrentLocale(FacesContext context)
    {
        Locale locale;
        if(context != null && context.getViewRoot() != null)
        {
            locale = context.getViewRoot().getLocale();
            if(locale == null)
            {
                locale = Locale.getDefault();
            }
        }
        else
        {
            locale = Locale.getDefault();
        }
        
        return locale;
    }

    

Parameters:
severity severity of message
bundleBaseName baseName of ResourceBundle to load localized messages
messageId id of message
params parameters to set at localized message
Returns:
generated FacesMessage
    public static FacesMessage getMessage(FacesMessage.Severity severityString bundleBaseName
            String messageIdObject params[])
    {
      FacesMessage msg = getMessage(bundleBaseNamemessageIdparams);
      msg.setSeverity(severity);
      return msg;
    }

    
Retrieve the message from a specific bundle. It does not look on application message bundle or default message bundle. If it is required to look on those bundles use getMessageFromBundle instead

Parameters:
bundleBaseName baseName of ResourceBundle to load localized messages
locale current locale
messageId id of message
params parameters to set at localized message
Returns:
generated FacesMessage
    public static FacesMessage getMessage(String bundleBaseNameLocale localeString messageIdObject params[])
    {
      if (bundleBaseName == null)
      {
          throw new NullPointerException(
              "Unable to locate ResourceBundle: bundle is null");
      }
      ResourceBundle bundle = ResourceBundle.getBundle(bundleBaseNamelocale);
      return getMessage(bundlemessageIdparams);
    }
    

Parameters:
bundle ResourceBundle to load localized messages
messageId id of message
params parameters to set at localized message
Returns:
generated FacesMessage
    public static FacesMessage getMessage(ResourceBundle bundleString messageIdObject params[])
    {
      String summary = null;
      String detail = null;
      try
      {
          summary = bundle.getString(messageId);
      }
      catch (MissingResourceException e)
      {
        // NoOp
      }
      if(summary == null)
      {
          summary = messageId;
      }
      summary = substituteParams(bundle.getLocale(), summaryparams);
      try
      {
          detail = substituteParams(bundle.getLocale(),
              bundle.getString(messageId + ), params);
      }
      catch(MissingResourceException e)
      {
        // NoOp
      }
      return new FacesMessage(summarydetail);
    }

    

Parameters:
context
messageId
Returns:
generated FacesMessage
    public static FacesMessage getMessage(FacesContext contextString messageId)
    {
        return getMessage(contextmessageId, ((Object []) (null)));
    }
    
    public static FacesMessage getMessage(String bundleBaseNameFacesContext contextString messageId)
    {
        return getMessage(bundleBaseNamecontextmessageId, ((Object []) (null)));
    }

    

Parameters:
context
messageId
params
Returns:
generated FacesMessage
    public static FacesMessage getMessage(FacesContext contextString messageIdObject params[])
    {
        if(context == null || messageId == null)
        {
            throw new NullPointerException(" context " + context + " messageId " + messageId);
        }
        Locale locale = getCurrentLocale(context);
        if(null == locale)
        {
            throw new NullPointerException(" locale " + locale);
        }
        FacesMessage message = getMessage(localemessageIdparams);
        if(message != null)
        {
            return message;
        } 
        else
        {
            // TODO /FIX:  Note that this has fallback behavior to default Locale for message,
            // but similar behavior above does not.  The methods should probably behave
            locale = Locale.getDefault();
            return getMessage(localemessageIdparams);
        }
    }
    
    public static FacesMessage getMessage(String bundleBaseNameFacesContext context
            String messageIdObject params[])
    {
        if(context == null || messageId == null)
        {
            throw new NullPointerException(" context " + context + " messageId " + messageId);
        }
        Locale locale = getCurrentLocale(context);
        if(null == locale)
        {
            throw new NullPointerException(" locale " + locale);
        }
        FacesMessage message = getMessageFromBundle(bundleBaseNamecontextlocalemessageIdparams);
        if(message != null)
        {
            return message;
        } 
        else
        {
            // TODO /FIX:  Note that this has fallback behavior to default Locale for message,
            // but similar behavior above does not.  The methods should probably behave
            locale = Locale.getDefault();
            return getMessageFromBundle(bundleBaseNamecontextlocalemessageIdparams);
        }
    }
    
    public static Object getLabel(FacesContext facesContextUIComponent component)
    {
        Object label = component.getAttributes().get("label");
        ValueExpression expression = null;
        if (label != null && 
            label instanceof String && ((String)label).length() == 0 )
        {
            // Note component.getAttributes().get("label") internally try to 
            // evaluate the EL expression for the label, but in some cases, 
            // when PSS is disabled and f:loadBundle is used, when the view is 
            // restored the bundle is not set to the EL expression returns an 
            // empty String. It is not possible to check if there is a 
            // hardcoded label, but we can check if there is
            // an EL expression set, so the best in this case is use that, and if
            // there is an EL expression set, use it, otherwise use the hardcoded
            // value. See MYFACES-3591 for details.
            expression = component.getValueExpression("label");
            if (expression != null)
            {
                // Set the label to null and use the EL expression instead.
                label = null;
            }
        }
            
        if(label != null)
        {
            return label;
        }
        
        expression = (expression == null) ? component.getValueExpression("label") : expression;
        if(expression != null)
        {
            return expression;
        }
        
        //If no label is not specified, use clientId
        return component.getClientIdfacesContext );
    }
    private static Application getApplication()
    {
        FacesContext context = FacesContext.getCurrentInstance();
        if(context != null)
        {
            return context.getApplication();
        }
        else
        {
            ApplicationFactory afactory = (ApplicationFactory)FactoryFinder.getFactory(
                    "javax.faces.application.ApplicationFactory");
            return afactory.getApplication();
        }
    }
New to GrepCode? Check out our FAQ X