1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.util;
16  
17  import com.liferay.portal.kernel.log.Log;
18  import com.liferay.portal.kernel.log.LogFactoryUtil;
19  
20  import java.text.MessageFormat;
21  
22  import java.util.Locale;
23  import java.util.ResourceBundle;
24  
25  /**
26   * <a href="ResourceBundleUtil.java.html"><b><i>View Source</i></b></a>
27   *
28   * <p>
29   * This class provides a convenience routine named getString() that gets the
30   * value of a ResourceBundle key, but also provides the ability to perform
31   * search & replace on tokens within the value of the key.
32   * </p>
33   *
34   * @author Neil Griffin
35   */
36  public class ResourceBundleUtil {
37  
38      public static String getString(
39          ResourceBundle bundle, Locale locale, String key, Object[] args) {
40  
41          String value = null;
42  
43          if (bundle == null) {
44              if (_log.isErrorEnabled()) {
45                  _log.error("Resource bundle is null");
46              }
47          }
48          else {
49  
50              // Get the value associated with the specified key, and substitute
51              // any arguuments like {0}, {1}, {2}, etc. with the specified
52              // argument values.
53  
54              value = bundle.getString(key);
55  
56              if (value == null) {
57                  if (_log.isWarnEnabled()) {
58                      _log.warn("No value found for key " + key);
59                  }
60              }
61              else {
62                  if ((args != null) && (args.length > 0)) {
63                      MessageFormat format = new MessageFormat(value, locale);
64  
65                      value = format.format(args);
66                  }
67              }
68          }
69  
70          if (value == null) {
71              value = key;
72          }
73  
74          return value;
75      }
76  
77      private static Log _log = LogFactoryUtil.getLog(ResourceBundleUtil.class);
78  
79  }