Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   *  jDTAUS - DTAUS fileformat.
   *  Copyright (c) 2005 Christian Schulte <cs@schulte.it>
   *
   *  This library is free software; you can redistribute it and/or
   *  modify it under the terms of the GNU Lesser General Public
   *  License as published by the Free Software Foundation; either
   *  version 2.1 of the License, or any later version.
   *
  *  This library 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
  *  Lesser General Public License for more details.
  *
  *  You should have received a copy of the GNU Lesser General Public
  *  License along with this library; if not, write to the Free Software
  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
  *
  */
 package org.jdtaus.core.nio.util;
 
 import java.net.URL;
 import java.util.List;
 import java.util.Map;

Charset coder and decoder utility.

This class extends the former charset provider implementations which cannot be used in every environment (e.g. WebStart, Maven) without installation in the JRE extensions directory where they are available to the system classloader. It uses the same service provider files as the platform implementation (java.nio.charset.spi.CharsetProvider) but is capable of using the current thread's classloader before falling back to the system classloader for loading CharsetProvider classes.

Author(s):
Christian Schulte
Version:
$Id: Charsets.java 4080 2007-07-29 22:15:05Z schulte2005 $
 
 public class Charsets
 {
     //--Charsets----------------------------------------------------------------
 
    
Cached CharsetProvider instances.
 
     private static final List providers = new LinkedList();

    
Cached Charset instances by name.
 
     private static final Map charsets = new HashMap(100);

    
Private constructor.
 
     private Charsets()
     {
         super();
     }

    
Gets a charset for the given name.

Parameters:
name the name of the charset to return.
Returns:
a Charset corresponding to name or null if no such Charset is available.
Throws:
java.io.IOException if reading the service provider files fails.
java.lang.ClassNotFoundException if a service provider file defines a class which cannot be loaded.
java.lang.InstantiationException if creating an instance of a CharsetProvider fails.
java.lang.IllegalAccessException if a CharsetProvider class does not define a public no-arg constructor.
java.nio.charset.IllegalCharsetNameException if name is no valid charset name.
java.nio.charset.UnsupportedCharsetException if name is not supported.
 
     private static Charset getCharset(final String namethrows IOException,
     {
         // Populate the provider list with available providers if it is empty.
         if(.size() == 0)
         {
             synchronized(Charsets.class)
             {
                 // Use the current thread's context classloader if available or
                 // fall back to the system classloader.
                 ClassLoader classLoader = Thread.currentThread().
                     getContextClassLoader();
 
                if(classLoader == null)
                {
                    classLoader = ClassLoader.getSystemClassLoader();
                }
                assert classLoader != null :
                    "Expected system classloader to always be available.";
                // Read all service provider files and load all defined
                // provider classes.
                final Enumeration providerFiles = classLoader.getResources(
                    "META-INF/services/java.nio.charset.spi.CharsetProvider");
                if(providerFiles != null)
                {
                    for(;providerFiles.hasMoreElements();)
                    {
                        final URL url = (URLproviderFiles.nextElement();
                        final InputStream in = url.openStream();
                        try
                        {
                            String line;
                            final BufferedReader reader = new BufferedReader(
                                new InputStreamReader(in"UTF-8"));
                            while((line = reader.readLine()) != null)
                            {
                                // Check that the line denotes a valid Java
                                // classname and load that class using
                                // reflection.
                                if(line.indexOf('#') < 0)
                                {
                                    .add(classLoader.loadClass(line).
                                        newInstance());
                                }
                            }
                        }
                        finally
                        {
                            in.close();
                        }
                    }
                }
            }
        }
        // Search cached charsets.
        Charset charset = (Charset.get(name);
        if(charset == null)
        {
            synchronized(Charsets.class)
            {
                // Search all available providers for a charset matching "name".
                for(Iterator it = .iterator(); it.hasNext();)
                {
                    charset = ((CharsetProviderit.next()).
                        charsetForName(name);
                    if(charset != null)
                    {
                        .put(namecharset);
                        break;
                    }
                }
            }
        }
        // Fall back to platform charsets if nothing is found so far.
        if(charset == null)
        {
            synchronized(Charsets.class)
            {
                charset = Charset.forName(name);
                .put(namecharset);
            }
        }
        return charset;
    }

    
Encodes a given string to an array of bytes representing the characters of the string in a given charset.

Parameters:
str the string to encode.
charset the name of the charset to use.
Throws:
java.lang.NullPointerException if str or charset is null.
java.nio.charset.IllegalCharsetNameException if charset is no valid charset name.
java.nio.charset.UnsupportedCharsetException if charset is not supported.
    public static byte[] encode(final String strfinal String charset)
    {
        if(str == null)
        {
            throw new NullPointerException("str");
        }
        if(charset == null)
        {
            throw new NullPointerException("charset");
        }
        final byte[] ret;
        try
        {
            final Charset cset = Charsets.getCharset(charset);
            final ByteBuffer buf = cset.encode(str);
            if(buf.hasArray())
            {
                if(buf.array().length == buf.limit())
                {
                    ret = buf.array();
                }
                else
                {
                    ret = new byte[buf.limit()];
                    System.arraycopy(buf.array(), buf.arrayOffset(),
                        ret, 0, ret.length);
                }
            }
            else
            {
                ret = new byte[buf.limit()];
                buf.rewind();
                buf.get(ret);
            }
        }
        catch(ClassNotFoundException e)
        {
            throw new AssertionError(e);
        }
        catch(InstantiationException e)
        {
            throw new AssertionError(e);
        }
        catch(IllegalAccessException e)
        {
            throw new AssertionError(e);
        }
        catch(IOException e)
        {
            throw new AssertionError(e);
        }
        return ret;
    }

    
Decodes the bytes of a given array to a string.

Parameters:
bytes the bytes to decode.
charset the name of the charset to use.
Throws:
java.lang.NullPointerException if bytes or charset is null.
java.nio.charset.IllegalCharsetNameException if charset is no valid charset name.
java.nio.charset.UnsupportedCharsetException if charset is not supported.
    public static String decode(final byte[] bytesfinal String charset)
    {
        if(bytes == null)
        {
            throw new NullPointerException("bytes");
        }
        if(charset == null)
        {
            throw new NullPointerException("charset");
        }
        final String ret;
        try
        {
            final Charset cset = Charsets.getCharset(charset);
            final CharBuffer buf = cset.decode(ByteBuffer.wrap(bytes));
            if(buf.hasArray())
            {
                ret = String.valueOf(buf.array(), buf.arrayOffset(),
                    buf.length());
            }
            else
            {
                final char[] c = new char[buf.length()];
                buf.rewind();
                buf.get(c);
                ret = String.valueOf(c);
            }
        }
        catch(ClassNotFoundException e)
        {
            throw new AssertionError(e);
        }
        catch(InstantiationException e)
        {
            throw new AssertionError(e);
        }
        catch(IllegalAccessException e)
        {
            throw new AssertionError(e);
        }
        catch(IOException e)
        {
            throw new AssertionError(e);
        }
        return ret;
    }

    
Decodes the bytes of a given array to a string.

Parameters:
bytes the bytes to decode.
off the offset from where to start decoding.
count the number of bytes to decode starting at offset.
charset the name of the charset to use.
Throws:
java.lang.NullPointerException if bytes or charset is null.
java.lang.IndexOutOfBoundsException if off is negative or greater than the length of bytes or off + count is negative or greater than the length of bytes.
java.nio.charset.IllegalCharsetNameException if charset is no valid charset name.
java.nio.charset.UnsupportedCharsetException if charset is not supported.
    public static String decode(final byte[] bytesfinal int off,
        final int countfinal String charset)
    {
        if(bytes == null)
        {
            throw new NullPointerException("bytes");
        }
        if(charset == null)
        {
            throw new NullPointerException("charset");
        }
        if(off < 0 || off >= bytes.length)
        {
            throw new ArrayIndexOutOfBoundsException(off);
        }
        if(count < 0 || off + count >= bytes.length)
        {
            throw new ArrayIndexOutOfBoundsException(count + off);
        }
        final String ret;
        try
        {
            final Charset cset = Charsets.getCharset(charset);
            final CharBuffer buf = cset.decode(
                ByteBuffer.wrap(bytesoffcount));
            if(buf.hasArray())
            {
                ret = String.valueOf(buf.array(), buf.arrayOffset(),
                    buf.length());
            }
            else
            {
                final char[] c = new char[buf.length()];
                buf.rewind();
                buf.get(c);
                ret = String.valueOf(c);
            }
        }
        catch(ClassNotFoundException e)
        {
            throw new AssertionError(e);
        }
        catch(InstantiationException e)
        {
            throw new AssertionError(e);
        }
        catch(IllegalAccessException e)
        {
            throw new AssertionError(e);
        }
        catch(IOException e)
        {
            throw new AssertionError(e);
        }
        return ret;
    }
    //----------------------------------------------------------------Charsets--
New to GrepCode? Check out our FAQ X