Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2000-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code 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
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.lang;
 
Utility class for string encoding and decoding.
 
 
 class StringCoding {
 
     private StringCoding() { }
 
     /* The cached coders for each thread
      */
     private static ThreadLocal decoder = new ThreadLocal();
     private static ThreadLocal encoder = new ThreadLocal();
 
     private static boolean warnUnsupportedCharset = true;
 
     private static Object deref(ThreadLocal tl) {
         SoftReference sr = (SoftReference)tl.get();
         if (sr == null)
             return null;
         return sr.get();
     }
 
     private static void set(ThreadLocal tlObject ob) {
         tl.set(new SoftReference(ob));
     }
 
     // Trim the given byte array to the given length
     //
     private static byte[] safeTrim(byte[] baint lenCharset cs) {
         if (len == ba.length
             && (System.getSecurityManager() == null
                 || cs.getClass().getClassLoader0() == null))
             return ba;
         else
             return Arrays.copyOf(balen);
     }
 
     // Trim the given char array to the given length
     //
     private static char[] safeTrim(char[] caint lenCharset cs) {
         if (len == ca.length
             && (System.getSecurityManager() == null
                 || cs.getClass().getClassLoader0() == null))
             return ca;
         else
             return Arrays.copyOf(calen);
     }
 
     private static int scale(int lenfloat expansionFactor) {
         // We need to perform double, not float, arithmetic; otherwise
         // we lose low order bits when len is larger than 2**24.
         return (int)(len * (double)expansionFactor);
    }
    private static Charset lookupCharset(String csn) {
        if (Charset.isSupported(csn)) {
            try {
                return Charset.forName(csn);
            } catch (UnsupportedCharsetException x) {
                throw new Error(x);
            }
        }
        return null;
    }
    private static void warnUnsupportedCharset(String csn) {
        if () {
            // Use sun.misc.MessageUtils rather than the Logging API or
            // System.err since this method may be called during VM
            // initialization before either is available.
            MessageUtils.err("WARNING: Default charset " + csn +
                             " not supported, using ISO-8859-1 instead");
             = false;
        }
    }
    // -- Decoding --
    private static class StringDecoder {
        private final String requestedCharsetName;
        private final Charset cs;
        private final CharsetDecoder cd;
        private StringDecoder(Charset csString rcn) {
            this. = rcn;
            this. = cs;
            this. = cs.newDecoder()
                .onMalformedInput(.)
                .onUnmappableCharacter(.);
        }
        String charsetName() {
            if ( instanceof HistoricallyNamedCharset)
                return ((HistoricallyNamedCharset)).historicalName();
            return .name();
        }
        final String requestedCharsetName() {
            return ;
        }
        char[] decode(byte[] baint offint len) {
            int en = scale(len.maxCharsPerByte());
            char[] ca = new char[en];
            if (len == 0)
                return ca;
            .reset();
            ByteBuffer bb = ByteBuffer.wrap(baofflen);
            CharBuffer cb = CharBuffer.wrap(ca);
            try {
                CoderResult cr = .decode(bbcbtrue);
                if (!cr.isUnderflow())
                    cr.throwException();
                cr = .flush(cb);
                if (!cr.isUnderflow())
                    cr.throwException();
            } catch (CharacterCodingException x) {
                // Substitution is always enabled,
                // so this shouldn't happen
                throw new Error(x);
            }
            return safeTrim(cacb.position(), );
        }
    }
    static char[] decode(String charsetNamebyte[] baint offint len)
        throws UnsupportedEncodingException
    {
        StringDecoder sd = (StringDecoder)deref();
        String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;
        if ((sd == null) || !(csn.equals(sd.requestedCharsetName())
                              || csn.equals(sd.charsetName()))) {
            sd = null;
            try {
                Charset cs = lookupCharset(csn);
                if (cs != null)
                    sd = new StringDecoder(cscsn);
            } catch (IllegalCharsetNameException x) {}
            if (sd == null)
                throw new UnsupportedEncodingException(csn);
            set(sd);
        }
        return sd.decode(baofflen);
    }
    static char[] decode(Charset csbyte[] baint offint len) {
        StringDecoder sd = new StringDecoder(cscs.name());
        byte[] b = Arrays.copyOf(baba.length);
        return sd.decode(bofflen);
    }
    static char[] decode(byte[] baint offint len) {
        String csn = Charset.defaultCharset().name();
        try {
            return decode(csnbaofflen);
        } catch (UnsupportedEncodingException x) {
            warnUnsupportedCharset(csn);
        }
        try {
            return decode("ISO-8859-1"baofflen);
        } catch (UnsupportedEncodingException x) {
            // If this code is hit during VM initialization, MessageUtils is
            // the only way we will be able to get any kind of error message.
            MessageUtils.err("ISO-8859-1 charset not available: "
                             + x.toString());
            // If we can not find ISO-8859-1 (a required encoding) then things
            // are seriously wrong with the installation.
            System.exit(1);
            return null;
        }
    }
    // -- Encoding --
    private static class StringEncoder {
        private Charset cs;
        private CharsetEncoder ce;
        private final String requestedCharsetName;
        private StringEncoder(Charset csString rcn) {
            this. = rcn;
            this. = cs;
            this. = cs.newEncoder()
                .onMalformedInput(.)
                .onUnmappableCharacter(.);
        }
        String charsetName() {
            if ( instanceof HistoricallyNamedCharset)
                return ((HistoricallyNamedCharset)).historicalName();
            return .name();
        }
        final String requestedCharsetName() {
            return ;
        }
        byte[] encode(char[] caint offint len) {
            int en = scale(len.maxBytesPerChar());
            byte[] ba = new byte[en];
            if (len == 0)
                return ba;
            .reset();
            ByteBuffer bb = ByteBuffer.wrap(ba);
            CharBuffer cb = CharBuffer.wrap(caofflen);
            try {
                CoderResult cr = .encode(cbbbtrue);
                if (!cr.isUnderflow())
                    cr.throwException();
                cr = .flush(bb);
                if (!cr.isUnderflow())
                    cr.throwException();
            } catch (CharacterCodingException x) {
                // Substitution is always enabled,
                // so this shouldn't happen
                throw new Error(x);
            }
            return safeTrim(babb.position(), );
        }
    }
    static byte[] encode(String charsetNamechar[] caint offint len)
        throws UnsupportedEncodingException
    {
        StringEncoder se = (StringEncoder)deref();
        String csn = (charsetName == null) ? "ISO-8859-1" : charsetName;
        if ((se == null) || !(csn.equals(se.requestedCharsetName())
                              || csn.equals(se.charsetName()))) {
            se = null;
            try {
                Charset cs = lookupCharset(csn);
                if (cs != null)
                    se = new StringEncoder(cscsn);
            } catch (IllegalCharsetNameException x) {}
            if (se == null)
                throw new UnsupportedEncodingException (csn);
            set(se);
        }
        return se.encode(caofflen);
    }
    static byte[] encode(Charset cschar[] caint offint len) {
        StringEncoder se = new StringEncoder(cscs.name());
        char[] c = Arrays.copyOf(caca.length);
        return se.encode(cofflen);
    }
    static byte[] encode(char[] caint offint len) {
        String csn = Charset.defaultCharset().name();
        try {
            return encode(csncaofflen);
        } catch (UnsupportedEncodingException x) {
            warnUnsupportedCharset(csn);
        }
        try {
            return encode("ISO-8859-1"caofflen);
        } catch (UnsupportedEncodingException x) {
            // If this code is hit during VM initialization, MessageUtils is
            // the only way we will be able to get any kind of error message.
            MessageUtils.err("ISO-8859-1 charset not available: "
                             + x.toString());
            // If we can not find ISO-8859-1 (a required encoding) then things
            // are seriously wrong with the installation.
            System.exit(1);
            return null;
        }
    }
New to GrepCode? Check out our FAQ X