Source for java.nio.charset.Charset

   1: /* Charset.java -- 
   2:    Copyright (C) 2002, 2004, 2005  Free Software Foundation, Inc.
   3: 
   4: This file is part of GNU Classpath.
   5: 
   6: GNU Classpath is free software; you can redistribute it and/or modify
   7: it under the terms of the GNU General Public License as published by
   8: the Free Software Foundation; either version 2, or (at your option)
   9: any later version.
  10: 
  11: GNU Classpath is distributed in the hope that it will be useful, but
  12: WITHOUT ANY WARRANTY; without even the implied warranty of
  13: MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  14: General Public License for more details.
  15: 
  16: You should have received a copy of the GNU General Public License
  17: along with GNU Classpath; see the file COPYING.  If not, write to the
  18: Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  19: 02110-1301 USA.
  20: 
  21: Linking this library statically or dynamically with other modules is
  22: making a combined work based on this library.  Thus, the terms and
  23: conditions of the GNU General Public License cover the whole
  24: combination.
  25: 
  26: As a special exception, the copyright holders of this library give you
  27: permission to link this library with independent modules to produce an
  28: executable, regardless of the license terms of these independent
  29: modules, and to copy and distribute the resulting executable under
  30: terms of your choice, provided that you also meet, for each linked
  31: independent module, the terms and conditions of the license of that
  32: module.  An independent module is a module which is not derived from
  33: or based on this library.  If you modify this library, you may extend
  34: this exception to your version of the library, but you are not
  35: obligated to do so.  If you do not wish to do so, delete this
  36: exception statement from your version. */
  37: 
  38: 
  39: package java.nio.charset;
  40: 
  41: import gnu.classpath.ServiceFactory;
  42: import gnu.classpath.SystemProperties;
  43: import gnu.java.nio.charset.Provider;
  44: 
  45: import java.io.BufferedReader;
  46: import java.io.InputStreamReader;
  47: import java.net.URL;
  48: import java.nio.ByteBuffer;
  49: import java.nio.CharBuffer;
  50: import java.nio.charset.spi.CharsetProvider;
  51: import java.util.Collections;
  52: import java.util.Enumeration;
  53: import java.util.HashSet;
  54: import java.util.Iterator;
  55: import java.util.LinkedHashSet;
  56: import java.util.Locale;
  57: import java.util.Set;
  58: import java.util.SortedMap;
  59: import java.util.TreeMap;
  60: 
  61: /**
  62:  * @author Jesse Rosenstock
  63:  * @since 1.4
  64:  */
  65: public abstract class Charset implements Comparable
  66: {
  67:   private CharsetEncoder cachedEncoder;
  68:   private CharsetDecoder cachedDecoder;
  69:  
  70:   /**
  71:    * Charset providers.
  72:    */
  73:   private static CharsetProvider[] providers;
  74:   
  75:   private final String canonicalName;
  76:   private final String[] aliases;
  77:   
  78:   protected Charset (String canonicalName, String[] aliases)
  79:   {
  80:     checkName (canonicalName);
  81:     if (aliases != null)
  82:       {
  83:         int n = aliases.length;
  84:         for (int i = 0; i < n; ++i)
  85:             checkName (aliases[i]);
  86:       }
  87: 
  88:     cachedEncoder = null;
  89:     cachedDecoder = null;
  90:     this.canonicalName = canonicalName;
  91:     this.aliases = aliases;
  92:   }
  93: 
  94:   /**
  95:    * @throws IllegalCharsetNameException  if the name is illegal
  96:    */
  97:   private static void checkName (String name)
  98:   {
  99:     int n = name.length ();
 100: 
 101:     if (n == 0)
 102:       throw new IllegalCharsetNameException (name);
 103: 
 104:     char ch = name.charAt (0);
 105:     if (!(('A' <= ch && ch <= 'Z')
 106:           || ('a' <= ch && ch <= 'z')
 107:           || ('0' <= ch && ch <= '9')))
 108:       throw new IllegalCharsetNameException (name);
 109: 
 110:     for (int i = 1; i < n; ++i)
 111:       {
 112:         ch = name.charAt (i);
 113:         if (!(('A' <= ch && ch <= 'Z')
 114:               || ('a' <= ch && ch <= 'z')
 115:               || ('0' <= ch && ch <= '9')
 116:               || ch == '-' || ch == '.' || ch == ':' || ch == '_'))
 117:           throw new IllegalCharsetNameException (name);
 118:       }
 119:   }
 120: 
 121:   /**
 122:    * Returns the system default charset.
 123:    *
 124:    * This may be set by the user or VM with the file.encoding
 125:    * property.
 126:    *
 127:    * @since 1.5
 128:    */
 129:   public static Charset defaultCharset()
 130:   {
 131:     String encoding;
 132:     
 133:     try 
 134:       {
 135:     encoding = SystemProperties.getProperty("file.encoding");
 136:       }
 137:     catch(SecurityException e)
 138:       {
 139:     // Use fallback.
 140:     encoding = "ISO-8859-1";
 141:       }
 142:     catch(IllegalArgumentException e)
 143:       {
 144:     // Use fallback.
 145:     encoding = "ISO-8859-1";
 146:       }
 147: 
 148:     try
 149:       {
 150:     return forName(encoding);
 151:       }
 152:     catch(UnsupportedCharsetException e)
 153:       {
 154:     // Ignore.
 155:       }
 156:     catch(IllegalCharsetNameException e)
 157:       {
 158:     // Ignore.
 159:       }
 160:     catch(IllegalArgumentException e)
 161:       {
 162:     // Ignore.
 163:       }
 164:     
 165:     throw new IllegalStateException("Can't get default charset!");
 166:   }
 167: 
 168:   public static boolean isSupported (String charsetName)
 169:   {
 170:     return charsetForName (charsetName) != null;
 171:   }
 172: 
 173:   /**
 174:    * Returns the Charset instance for the charset of the given name.
 175:    * 
 176:    * @param charsetName
 177:    * @return
 178:    * @throws UnsupportedCharsetException if this VM does not support
 179:    * the charset of the given name.
 180:    * @throws IllegalCharsetNameException if the given charset name is
 181:    * legal.
 182:    * @throws IllegalArgumentException if <code>charsetName</code> is null.
 183:    */
 184:   public static Charset forName (String charsetName)
 185:   {
 186:     // Throws IllegalArgumentException as the JDK does.
 187:     if(charsetName == null)
 188:         throw new IllegalArgumentException("Charset name must not be null.");
 189:     
 190:     Charset cs = charsetForName (charsetName);
 191:     if (cs == null)
 192:       throw new UnsupportedCharsetException (charsetName);
 193:     return cs;
 194:   }
 195: 
 196:   /**
 197:    * Retrieves a charset for the given charset name.
 198:    *
 199:    * @return A charset object for the charset with the specified name, or
 200:    * <code>null</code> if no such charset exists.
 201:    *
 202:    * @throws IllegalCharsetNameException  if the name is illegal
 203:    */
 204:   private static Charset charsetForName(String charsetName)
 205:   {
 206:     checkName (charsetName);
 207:     // Try the default provider first
 208:     // (so we don't need to load external providers unless really necessary)
 209:     // if it is an exotic charset try loading the external providers.
 210:     Charset cs = provider().charsetForName(charsetName);
 211:     if (cs == null)
 212:       {
 213:     CharsetProvider[] providers = providers2();
 214:     for (int i = 0; i < providers.length; i++)
 215:       {
 216:         cs = providers[i].charsetForName(charsetName);
 217:         if (cs != null)
 218:           break;
 219:       }
 220:       }
 221:     return cs;
 222:   }
 223: 
 224:   public static SortedMap availableCharsets()
 225:   {
 226:     TreeMap charsets = new TreeMap(String.CASE_INSENSITIVE_ORDER);
 227:     for (Iterator i = provider().charsets(); i.hasNext(); )
 228:       {
 229:     Charset cs = (Charset) i.next();
 230:     charsets.put(cs.name(), cs);
 231:       }
 232: 
 233:     CharsetProvider[] providers = providers2();
 234:     for (int j = 0; j < providers.length; j++)
 235:       {
 236:         for (Iterator i = providers[j].charsets(); i.hasNext(); )
 237:           {
 238:             Charset cs = (Charset) i.next();
 239:             charsets.put(cs.name(), cs);
 240:           }
 241:       }
 242: 
 243:     return Collections.unmodifiableSortedMap(charsets);
 244:   }
 245: 
 246:   private static CharsetProvider provider()
 247:   {
 248:     try
 249:       {
 250:     String s = System.getProperty("charset.provider");
 251:     if (s != null)
 252:       {
 253:         CharsetProvider p =
 254:           (CharsetProvider) ((Class.forName(s)).newInstance());
 255:         return p;
 256:       }
 257:       }
 258:     catch (Exception e)
 259:       {
 260:     // Ignore.
 261:       }
 262:     
 263:     return Provider.provider();
 264:   }
 265: 
 266:   /**
 267:    * We need to support multiple providers, reading them from
 268:    * java.nio.charset.spi.CharsetProvider in the resource directory
 269:    * META-INF/services. This returns the "extra" charset providers.
 270:    */
 271:   private static CharsetProvider[] providers2()
 272:   {
 273:     if (providers == null)
 274:       {
 275:         try
 276:           {
 277:             Iterator i = ServiceFactory.lookupProviders(CharsetProvider.class);
 278:             LinkedHashSet set = new LinkedHashSet();
 279:             while (i.hasNext())
 280:               set.add(i.next());
 281: 
 282:             providers = new CharsetProvider[set.size()];
 283:             set.toArray(providers);
 284:           }
 285:         catch (Exception e)
 286:           {
 287:             throw new RuntimeException(e);
 288:           }
 289:       }
 290:     return providers;
 291:   }
 292: 
 293:   public final String name ()
 294:   {
 295:     return canonicalName;
 296:   }
 297: 
 298:   public final Set aliases ()
 299:   {
 300:     if (aliases == null)
 301:       return Collections.EMPTY_SET;
 302: 
 303:     // should we cache the aliasSet instead?
 304:     int n = aliases.length;
 305:     HashSet aliasSet = new HashSet (n);
 306:     for (int i = 0; i < n; ++i)
 307:         aliasSet.add (aliases[i]);
 308:     return Collections.unmodifiableSet (aliasSet);
 309:   }
 310: 
 311:   public String displayName ()
 312:   {
 313:     return canonicalName;
 314:   }
 315: 
 316:   public String displayName (Locale locale)
 317:   {
 318:     return canonicalName;
 319:   }
 320: 
 321:   public final boolean isRegistered ()
 322:   {
 323:     return (!canonicalName.startsWith ("x-")
 324:             && !canonicalName.startsWith ("X-"));
 325:   }
 326: 
 327:   public abstract boolean contains (Charset cs);
 328: 
 329:   public abstract CharsetDecoder newDecoder ();
 330: 
 331:   public abstract CharsetEncoder newEncoder ();
 332: 
 333:   public boolean canEncode ()
 334:   {
 335:     return true;
 336:   }
 337: 
 338:   // NB: This implementation serializes different threads calling
 339:   // Charset.encode(), a potential performance problem.  It might
 340:   // be better to remove the cache, or use ThreadLocal to cache on
 341:   // a per-thread basis.
 342:   public final synchronized ByteBuffer encode (CharBuffer cb)
 343:   {
 344:     try
 345:       {
 346:     if (cachedEncoder == null)
 347:       {
 348:         cachedEncoder = newEncoder ()
 349:           .onMalformedInput (CodingErrorAction.REPLACE)
 350:           .onUnmappableCharacter (CodingErrorAction.REPLACE);
 351:       } else
 352:       cachedEncoder.reset();
 353:     return cachedEncoder.encode (cb);
 354:       }
 355:     catch (CharacterCodingException e)
 356:       {
 357:         throw new AssertionError (e);
 358:       }
 359:   }
 360:   
 361:   public final ByteBuffer encode (String str)
 362:   {
 363:     return encode (CharBuffer.wrap (str));
 364:   }
 365: 
 366:   // NB: This implementation serializes different threads calling
 367:   // Charset.decode(), a potential performance problem.  It might
 368:   // be better to remove the cache, or use ThreadLocal to cache on
 369:   // a per-thread basis.
 370:   public final synchronized CharBuffer decode (ByteBuffer bb)
 371:   {
 372:     try
 373:       {
 374:     if (cachedDecoder == null)
 375:       {
 376:         cachedDecoder = newDecoder ()
 377:           .onMalformedInput (CodingErrorAction.REPLACE)
 378:           .onUnmappableCharacter (CodingErrorAction.REPLACE);
 379:       } else
 380:       cachedDecoder.reset();
 381: 
 382:     return cachedDecoder.decode (bb);
 383:       }
 384:     catch (CharacterCodingException e)
 385:       {
 386:         throw new AssertionError (e);
 387:       }
 388:   }
 389: 
 390:   public final int compareTo (Object ob)
 391:   {
 392:     return canonicalName.compareToIgnoreCase (((Charset) ob).canonicalName);
 393:   }
 394: 
 395:   public final int hashCode ()
 396:   {
 397:     return canonicalName.hashCode ();
 398:   }
 399: 
 400:   public final boolean equals (Object ob)
 401:   {
 402:     if (ob instanceof Charset)
 403:       return canonicalName.equalsIgnoreCase (((Charset) ob).canonicalName);
 404:     else
 405:       return false;
 406:   }
 407: 
 408:   public final String toString ()
 409:   {
 410:     return canonicalName;
 411:   }
 412: }