Read ResourceBundles with custom encodings : ResourceBundle « I18N « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JDK 6
25.JNDI LDAP
26.JPA
27.JSP
28.JSTL
29.Language Basics
30.Network Protocol
31.PDF RTF
32.Reflection
33.Regular Expressions
34.Scripting
35.Security
36.Servlets
37.Spring
38.Swing Components
39.Swing JFC
40.SWT JFace Eclipse
41.Threads
42.Tiny Application
43.Velocity
44.Web Services SOA
45.XML
Java » I18N » ResourceBundleScreenshots 
Read ResourceBundles with custom encodings
  
/*
 * This file is part of aion-emu <aion-emu.com>.
 *
 * aion-emu is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * aion-emu 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with aion-emu.  If not, see <http://www.gnu.org/licenses/>.
 */
//package com.aionemu.commons.utils.i18n;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * This class allows us to read ResourceBundles with custom encodings, so we don't have write \\uxxxx symbols and use
 * utilities like native2ascii to convert files.
 * <p/>
 * <br>
 
 * Usage: For instance we want to load resource bundle "test" from current deirectory and use english locale. If locale
 * not found, we will use default file (and ignore default locale).
 
 * <pre>
 * URLClassLoader loader = new URLClassLoader(new URL[] { new File(&quot;.&quot;).toURI().toURL() });
 
 * ResourceBundle rb = ResourceBundle.getBundle(&quot;test&quot;, Locale.ENGLISH, loader, new ResourceBundleControl(&quot;UTF-8&quot;));
 
 * // English locale not found, use default
 * if(!rb.getLocale().equals(Locale.ENGLISH))
 * {
 *   rb = ResourceBundle.getBundle(&quot;test&quot;, Locale.ROOT, loader, new ResourceBundleControl(&quot;UTF-8&quot;));
 * }
 
 * System.out.println(rb.getString(&quot;test&quot;));
 * </pre>
 
 @author SoulKeeper
 */
public class ResourceBundleControl extends ResourceBundle.Control
{
  /**
   * Encoding which will be used to read resource bundle, by defaults it's 8859_1
   */
  private String  encoding  = "UTF-8";

  /**
   * Just empty default constructor
   */
  public ResourceBundleControl()
  {
  }

  /**
   * This constructor allows to set encoding that will be used while reading resource bundle
   
   @param encoding
   *            encoding to use
   */
  public ResourceBundleControl(String encoding)
  {
    this.encoding = encoding;
  }

  /**
   * This code is just copy-paste with usage {@link java.io.Reader} instead of {@link java.io.InputStream} to read
   * properties.<br>
   * <br>
   
   * {@inheritDoc}
   */
  @Override
  public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reloadthrows IllegalAccessException,
      InstantiationException, IOException
  {
    String bundleName = toBundleName(baseName, locale);
    ResourceBundle bundle = null;
    if (format.equals("java.class"))
    {
      try
      {
        @SuppressWarnings(
        "unchecked" })
        Class<? extends ResourceBundle> bundleClass = (Class<? extends ResourceBundle>loader.loadClass(bundleName);

        // If the class isn't a ResourceBundle subclass, throw a
        // ClassCastException.
        if (ResourceBundle.class.isAssignableFrom(bundleClass))
        {
          bundle = bundleClass.newInstance();
        }
        else
        {
          throw new ClassCastException(bundleClass.getName() " cannot be cast to ResourceBundle");
        }
      }
      catch (ClassNotFoundException ignored)
      {
      }
    }
    else if (format.equals("java.properties"))
    {
      final String resourceName = toResourceName(bundleName, "properties");
      final ClassLoader classLoader = loader;
      final boolean reloadFlag = reload;
      InputStreamReader isr = null;
      InputStream stream;
      try
      {
        stream = AccessController.doPrivileged(new PrivilegedExceptionAction<InputStream>()
        {
          @Override
          public InputStream run() throws IOException
          {
            InputStream is = null;
            if (reloadFlag)
            {
              URL url = classLoader.getResource(resourceName);
              if (url != null)
              {
                URLConnection connection = url.openConnection();
                if (connection != null)
                {
                  // Disable caches to get fresh data for
                  // reloading.
                  connection.setUseCaches(false);
                  is = connection.getInputStream();
                }
              }
            }
            else
            {
              is = classLoader.getResourceAsStream(resourceName);
            }
            return is;
          }
        });
        if (stream != null)
        {
          isr = new InputStreamReader(stream, encoding);
        }
      }
      catch (PrivilegedActionException e)
      {
        throw (IOExceptione.getException();
      }
      if (isr != null)
      {
        try
        {
          bundle = new PropertyResourceBundle(isr);
        }
        finally
        {
          isr.close();
        }
      }
    }
    else
    {
      throw new IllegalArgumentException("unknown format: " + format);
    }
    return bundle;
  }

  /**
   * Returns encoding that will be used to read .properties resource bundles
   
   @return encoding
   */
  public String getEncoding()
  {
    return encoding;
  }

  /**
   * Sets the encoding that will be used to read properties resource bundles
   
   @param encoding
   *            encoding that will be used for properties
   */
  public void setEncoding(String encoding)
  {
    this.encoding = encoding;
  }
}

   
    
  
Related examples in the same category
1.Java I18N: IntroductionJava I18N: Introduction
2.Load resource with ResourceBundle.getBundle
3.Load a Resource Bundle
4.Localizing Messages with a property-file type resource bundle
5.Matching Line Boundaries in a Regular Expression
6.Convert ResourceBundle to Properties
7.Get resource bundle for a certain localeGet resource bundle for a certain locale
8.Convert ResourceBundle to Map
9.Use ResourceBundle for i18n
10.Load resources based upon client environment at startup
11.Load resources via a resources file
12.Java file based resource bundle
13.Resource Bundle by Locale
14.Resource Bundle in Java code
15.List Resource Bundle Creator
16.Simple Resource Bundle based on Java code
17.Create one button, internationalizedly
18.Java Internationalization: load string from properties Java Internationalization: load string from properties
19.Isolating Locale-Specific Data with Resource Bundles Isolating Locale-Specific Data with Resource Bundles
20.Property To List Resource Bundle
21.Which Bundle Comes First
22.Localized JOptionPane
23.Big Demo for I18N
24.Popup in FrenchPopup in French
25.ResourceBundle with ParametersResourceBundle with Parameters
26.ResourceBundle with parameter positionResourceBundle with parameter position
27.Load a given resource.
28.Helper class for constructing messages from bundles
29.Methods for receving messages from resource bundles
30.Convert Class To Resource Path
31.Transform the class-relative resource name into a global name by appending it to the classes package name.
32.ResourceBundle: avoid a performance penalty by superfluous resource (and classes loaded by Class.forName) lookups on web server in applets.
33.Method to convert a ResourceBundle to a Map object.
34.Method to convert a ResourceBundle to a Properties object.
35.Resource utils
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.