ResourceBundle String manager : URL « Network Protocol « Java






ResourceBundle String manager

    

/*
 * Copyright (C) 2003 Colin Bell
 * colbell@users.sourceforge.net
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.net.URLClassLoader;
import java.net.URL;

/**
 * This class defines i18nized strings. These strings are stored in a file
 * with a base name I18NStrings.properties in each package directory.
 *
 * @author <A HREF="mailto:colbell@users.sourceforge.net">Colin Bell</A>
 */
public class StringManager
{

  /** Contains the localised strings. */
  private ResourceBundle _rsrcBundle;
  private String _bundleBaseName;
  private URL[] _bundleLoaderUrLs = new URL[0];
  
  /** a flag to indicate whether or not to throw exception for missing resource string */
  private static boolean _testMode = false;

  /**
   * Ctor specifying the package name. Attempt to load a resource bundle
   * from the package directory.
   *
   * @param packageName Name of package
   * @param classLoader Class loader to use
   */
  StringManager(String packageName, ClassLoader loader)
  {
    super();
    _bundleBaseName = packageName + ".I18NStrings";
    _rsrcBundle = ResourceBundle.getBundle(_bundleBaseName, Locale.getDefault(), loader);

    if(loader instanceof URLClassLoader)
    {
      _bundleLoaderUrLs = ((URLClassLoader) loader).getURLs();
    }


  }

  /**
   * Retrieve the localized string for the passed key. If it isn't found
   * an error message is returned instead.
   *
   * @param key   Key to retrieve string for.
   *
   * @return  Localized string or error message.
   *
   * @throws  IllegalArgumentException
   *      Thrown if <TT>null</TT> <TT>key</TT> passed.
   */
  public String getString(String key)
  {
    if (key == null)
    {
      throw new IllegalArgumentException("key == null");
    }

    try
    {
      return _rsrcBundle.getString(key);
    }
    catch (MissingResourceException ex)
    {
      StringBuilder sb = new StringBuilder();
      sb.append("No resource string found for key '" + key + "' in bundle " + _bundleBaseName + "\n\n");

      if(0 < _bundleLoaderUrLs.length)
      {
        sb.append("The following classpath entries are available to the bundle loader:\n");
        for (int i = 0; i < _bundleLoaderUrLs.length; i++)
        {
          sb.append(_bundleLoaderUrLs[i]).append("\n");
        }
      }
     
      if (_testMode) {
        throw new IllegalStateException(sb.toString());
      }
      return "No resource found for key " + key;
    }
  }

    /**
     * Retrieve the localized string for the passed key and format it with the
     * passed arguments.
     *
     * @param   key     Key to retrieve string for.
     * @param   args    Any string arguments that should be used as values to 
     *                  parameters found in the localized string.
     *                   
     * @return  Localized string or error message.
     *
     * @throws  IllegalArgumentException
     *          Thrown if <TT>null</TT> <TT>key</TT> passed.
     */    
    public String getString(String key, String[] args) 
    {
        return getString(key, (Object[])args);
    }
    
  /**
   * Retrieve the localized string for the passed key and format it with the
   * passed arguments.
   *
   * @param key   Key to retrieve string for.
     * @param   args    Any string arguments that should be used as values to 
     *                  parameters found in the localized string. 
   *
   * @return  Localized string or error message.
   *
   * @throws  IllegalArgumentException
   *      Thrown if <TT>null</TT> <TT>key</TT> passed.
   */
  public String getString(String key, Object... args)
  {
    if (key == null)
    {
      throw new IllegalArgumentException("key == null");
    }

    if (args == null)
    {
      args = new Object[0];
    }

    final String str = getString(key);
    try
    {
      return MessageFormat.format(str, args);
    }
    catch (IllegalArgumentException ex)
    {
      String msg = "Error formatting i18 string. Key is '" + key + "'";
  
      return msg + ": " + ex.toString();
    }
  }
  
  /**
   * Allows the caller to enable/disable test mode which results in an exception being thrown for no 
   * resource string defined. 
   * 
   * @param enabled 
   */
  public static void setTestMode(boolean enabled) {
    _testMode = enabled;
  }
}

   
    
    
    
  








Related examples in the same category

1.Creating a URL with a single string.
2.Creating a URL With components
3.Converting Between a Filename Path and a URL
4.URL Constructor Test
5.URL Encode Test
6.Get URL Content
7.Get URL Parts
8.Read from a URL
9.Convert a URL to a URI
10.Converting Between a URL and a URI
11.Convert an absolute URI to a URL
12.URL Equality
13.Parsing a URL
14.URL Request
15.URL Get
16.A URL Retrieval Example
17.URL Reader
18.URL Connection ReaderURL Connection Reader
19.Using URLConnection
20.Parse URLParse URL
21.Resolve a relative URL
22.sends e-mail using a mailto: URLsends e-mail using a mailto: URL
23.Convert the absolute URI to a URL object
24.Convert URI to URL
25.Get parts of a url
26.Checks, whether the URL uses a file based protocol.
27.Add Parameter to URL
28.Returns the anchor value of the given URL
29.Extracts the file name from the URL.
30.Creates a relative url by stripping the common parts of the the url.
31.Checks, whether the URL points to the same service. A service is equal if the protocol, host and port are equal.
32.Extracts the base URL from the given URL by stripping the query and anchor part.
33.Returns true if the URL represents a path, and false otherwise.
34.Parse Port
35.Parse Host
36.Given a URL check if its a jar url(jar:!/archive) and if it is, extract the archive entry into the given dest directory and return a file URL to its location
37.check the validity of url pattern according to the spec.
38.A collection of File, URL and filename utility methods
39.Build Relative URL Path
40.Checks that the protocol://host:port part of two URLs are equal
41.Create valid URL from a system id
42.Extract URL File Name
43.Extract the URL page name from the given path
44.Get Domain Name
45.Get Locale From String
46.Get URL Last Modified
47.Get the name of the parent of the given URL path
48.Get the parent of the given URL path
49.Has URLContent Changed
50.Is URL a local file
51.Normalize an URL
52.Normalizes an URL
53.Resolve a relative URL string against an absolute URL string
54.Save URL contents to a file
55.URL Path: standardize the creation of mutation of path-like structures
56.Utility class for building URLs
57.Add Default Port to a URL If Missing
58.Get Relative Path To URL
59.Download from a URL and save to a file