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