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: import gnu.java.nio.charset.iconv.IconvProvider;
  45: 
  46: import java.nio.ByteBuffer;
  47: import java.nio.CharBuffer;
  48: import java.nio.charset.spi.CharsetProvider;
  49: import java.util.Collections;
  50: import java.util.HashSet;
  51: import java.util.Iterator;
  52: import java.util.LinkedHashSet;
  53: import java.util.Locale;
  54: import java.util.Set;
  55: import java.util.SortedMap;
  56: import java.util.TreeMap;
  57: 
  58: /**
  59:  * @author Jesse Rosenstock
  60:  * @since 1.4
  61:  * @status updated to 1.5
  62:  */
  63: public abstract class Charset implements Comparable
  64: {
  65:   private CharsetEncoder cachedEncoder;
  66:   private CharsetDecoder cachedDecoder;
  67:   
  68:   /**
  69:    * Extra Charset providers.
  70:    */
  71:   private static CharsetProvider[] providers;
  72:   
  73:   private final String canonicalName;
  74:   private final String[] aliases;
  75:   
  76:   protected Charset (String canonicalName, String[] aliases)
  77:   {
  78:     checkName (canonicalName);
  79:     if (aliases != null)
  80:       {
  81:         int n = aliases.length;
  82:         for (int i = 0; i < n; ++i)
  83:             checkName (aliases[i]);
  84:       }
  85: 
  86:     cachedEncoder = null;
  87:     cachedDecoder = null;
  88:     this.canonicalName = canonicalName;
  89:     this.aliases = aliases;
  90:   }
  91: 
  92:   /**
  93:    * @throws IllegalCharsetNameException  if the name is illegal
  94:    */
  95:   private static void checkName (String name)
  96:   {
  97:     int n = name.length ();
  98: 
  99:     if (n == 0)
 100:       throw new IllegalCharsetNameException (name);
 101: 
 102:     char ch = name.charAt (0);
 103:     if (!(('A' <= ch && ch <= 'Z')
 104:           || ('a' <= ch && ch <= 'z')
 105:           || ('0' <= ch && ch <= '9')))
 106:       throw new IllegalCharsetNameException (name);
 107: 
 108:     for (int i = 1; i < n; ++i)
 109:       {
 110:         ch = name.charAt (i);
 111:         if (!(('A' <= ch && ch <= 'Z')
 112:               || ('a' <= ch && ch <= 'z')
 113:               || ('0' <= ch && ch <= '9')
 114:               || ch == '-' || ch == '.' || ch == ':' || ch == '_'))
 115:           throw new IllegalCharsetNameException (name);
 116:       }
 117:   }
 118: 
 119:   /**
 120:    * Returns the system default charset.
 121:    *
 122:    * This may be set by the user or VM with the file.encoding
 123:    * property.
 124:    * 
 125:    * @since 1.5
 126:    */
 127:   public static Charset defaultCharset()
 128:   {
 129:     String encoding;
 130:     
 131:     try 
 132:       {
 133:     encoding = SystemProperties.getProperty("file.encoding");
 134:       }
 135:     catch(SecurityException e)
 136:       {
 137:     // Use fallback.
 138:     encoding = "ISO-8859-1";
 139:       }
 140:     catch(IllegalArgumentException e)
 141:       {
 142:     // Use fallback.
 143:     encoding = "ISO-8859-1";
 144:       }
 145: 
 146:     try
 147:       {
 148:     return forName(encoding);
 149:       }
 150:     catch(UnsupportedCharsetException e)
 151:       {
 152:     // Ignore.
 153:       }
 154:     catch(IllegalCharsetNameException e)
 155:       {
 156:     // Ignore.
 157:       }
 158:     catch(IllegalArgumentException e)
 159:       {
 160:     // Ignore.
 161:       }
 162:     
 163:     throw new IllegalStateException("Can't get default charset!");
 164:   }
 165: 
 166:   public static boolean isSupported (String charsetName)
 167:   {
 168:     return charsetForName (charsetName) != null;
 169:   }
 170: 
 171:   /**
 172:    * Returns the Charset instance for the charset of the given name.
 173:    * 
 174:    * @param charsetName
 175:    * @return the Charset instance for the indicated charset
 176:    * @throws UnsupportedCharsetException if this VM does not support
 177:    * the charset of the given name.
 178:    * @throws IllegalCharsetNameException if the given charset name is
 179:    * legal.
 180:    * @throws IllegalArgumentException if <code>charsetName</code> is null.
 181:    */
 182:   public static Charset forName (String charsetName)
 183:   {
 184:     // Throws IllegalArgumentException as the JDK does.
 185:     if(charsetName == null)
 186:         throw new IllegalArgumentException("Charset name must not be null.");
 187:     
 188:     Charset cs = charsetForName (charsetName);
 189:     if (cs == null)
 190:       throw new UnsupportedCharsetException (charsetName);
 191:     return cs;
 192:   }
 193: 
 194:   /**
 195:    * Retrieves a charset for the given charset name.
 196:    *
 197:    * @return A charset object for the charset with the specified name, or
 198:    * <code>null</code> if no such charset exists.
 199:    *
 200:    * @throws IllegalCharsetNameException  if the name is illegal
 201:    */
 202:   private static Charset charsetForName(String charsetName)
 203:   {
 204:     checkName (charsetName);
 205:     // Try the default provider first
 206:     // (so we don't need to load external providers unless really necessary)
 207:     // if it is an exotic charset try loading the external providers.
 208:     Charset cs = provider().charsetForName(charsetName);
 209:     if (cs == null)
 210:       {
 211:     CharsetProvider[] providers = providers2();
 212:     for (int i = 0; i < providers.length; i++)
 213:       {
 214:         cs = providers[i].charsetForName(charsetName);
 215:         if (cs != null)
 216:           break;
 217:       }
 218:       }
 219:     return cs;
 220:   }
 221: 
 222:   public static SortedMap availableCharsets()
 223:   {
 224:     TreeMap charsets = new TreeMap(String.CASE_INSENSITIVE_ORDER);
 225:     for (Iterator i = provider().charsets(); i.hasNext(); )
 226:       {
 227:     Charset cs = (Charset) i.next();
 228:     charsets.put(cs.name(), cs);
 229:       }
 230: 
 231:     CharsetProvider[] providers = providers2();
 232:     for (int j = 0; j < providers.length; j++)
 233:       {
 234:         for (Iterator i = providers[j].charsets(); i.hasNext(); )
 235:           {
 236:             Charset cs = (Charset) i.next();
 237:             charsets.put(cs.name(), cs);
 238:           }
 239:       }
 240: 
 241:     return Collections.unmodifiableSortedMap(charsets);
 242:   }
 243: 
 244:   private static CharsetProvider provider()
 245:   {
 246:     String useIconv = SystemProperties.getProperty
 247:       ("gnu.classpath.nio.charset.provider.iconv");
 248: 
 249:     if (useIconv != null)
 250:       return IconvProvider.provider();
 251: 
 252:     return Provider.provider();
 253:   }
 254: 
 255:   /**
 256:    * We need to support multiple providers, reading them from
 257:    * java.nio.charset.spi.CharsetProvider in the resource directory
 258:    * META-INF/services. This returns the "extra" charset providers.
 259:    */
 260:   private static CharsetProvider[] providers2()
 261:   {
 262:     if (providers == null)
 263:       {
 264:         try
 265:           {
 266:             Iterator i = ServiceFactory.lookupProviders(CharsetProvider.class);
 267:             LinkedHashSet set = new LinkedHashSet();
 268:             while (i.hasNext())
 269:               set.add(i.next());
 270: 
 271:             providers = new CharsetProvider[set.size()];
 272:             set.toArray(providers);
 273:           }
 274:         catch (Exception e)
 275:           {
 276:             throw new RuntimeException(e);
 277:           }
 278:       }
 279:     return providers;
 280:   }
 281: 
 282:   public final String name ()
 283:   {
 284:     return canonicalName;
 285:   }
 286: 
 287:   public final Set aliases ()
 288:   {
 289:     if (aliases == null)
 290:       return Collections.EMPTY_SET;
 291: 
 292:     // should we cache the aliasSet instead?
 293:     int n = aliases.length;
 294:     HashSet aliasSet = new HashSet (n);
 295:     for (int i = 0; i < n; ++i)
 296:         aliasSet.add (aliases[i]);
 297:     return Collections.unmodifiableSet (aliasSet);
 298:   }
 299: 
 300:   public String displayName ()
 301:   {
 302:     return canonicalName;
 303:   }
 304: 
 305:   public String displayName (Locale locale)
 306:   {
 307:     return canonicalName;
 308:   }
 309: 
 310:   public final boolean isRegistered ()
 311:   {
 312:     return (!canonicalName.startsWith ("x-")
 313:             && !canonicalName.startsWith ("X-"));
 314:   }
 315: 
 316:   public abstract boolean contains (Charset cs);
 317: 
 318:   public abstract CharsetDecoder newDecoder ();
 319: 
 320:   public abstract CharsetEncoder newEncoder ();
 321: 
 322:   public boolean canEncode ()
 323:   {
 324:     return true;
 325:   }
 326: 
 327:   // NB: This implementation serializes different threads calling
 328:   // Charset.encode(), a potential performance problem.  It might
 329:   // be better to remove the cache, or use ThreadLocal to cache on
 330:   // a per-thread basis.
 331:   public final synchronized ByteBuffer encode (CharBuffer cb)
 332:   {
 333:     try
 334:       {
 335:     if (cachedEncoder == null)
 336:       {
 337:         cachedEncoder = newEncoder ()
 338:           .onMalformedInput (CodingErrorAction.REPLACE)
 339:           .onUnmappableCharacter (CodingErrorAction.REPLACE);
 340:       } else
 341:       cachedEncoder.reset();
 342:     return cachedEncoder.encode (cb);
 343:       }
 344:     catch (CharacterCodingException e)
 345:       {
 346:         throw new AssertionError (e);
 347:       }
 348:   }
 349:   
 350:   public final ByteBuffer encode (String str)
 351:   {
 352:     return encode (CharBuffer.wrap (str));
 353:   }
 354: 
 355:   // NB: This implementation serializes different threads calling
 356:   // Charset.decode(), a potential performance problem.  It might
 357:   // be better to remove the cache, or use ThreadLocal to cache on
 358:   // a per-thread basis.
 359:   public final synchronized CharBuffer decode (ByteBuffer bb)
 360:   {
 361:     try
 362:       {
 363:     if (cachedDecoder == null)
 364:       {
 365:         cachedDecoder = newDecoder ()
 366:           .onMalformedInput (CodingErrorAction.REPLACE)
 367:           .onUnmappableCharacter (CodingErrorAction.REPLACE);
 368:       } else
 369:       cachedDecoder.reset();
 370: 
 371:     return cachedDecoder.decode (bb);
 372:       }
 373:     catch (CharacterCodingException e)
 374:       {
 375:         throw new AssertionError (e);
 376:       }
 377:   }
 378: 
 379:   public final int compareTo (Object ob)
 380:   {
 381:     return canonicalName.compareToIgnoreCase (((Charset) ob).canonicalName);
 382:   }
 383: 
 384:   public final int hashCode ()
 385:   {
 386:     return canonicalName.hashCode ();
 387:   }
 388: 
 389:   public final boolean equals (Object ob)
 390:   {
 391:     if (ob instanceof Charset)
 392:       return canonicalName.equalsIgnoreCase (((Charset) ob).canonicalName);
 393:     else
 394:       return false;
 395:   }
 396: 
 397:   public final String toString ()
 398:   {
 399:     return canonicalName;
 400:   }
 401: }