Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
  //  ------------------------------------------------------------------------
  //  All rights reserved. This program and the accompanying materials
  //  are made available under the terms of the Eclipse Public License v1.0
  //  and Apache License v2.0 which accompanies this distribution.
  //
  //      The Eclipse Public License is available at
 //      http://www.eclipse.org/legal/epl-v10.html
 //
 //      The Apache License v2.0 is available at
 //      http://www.opensource.org/licenses/apache2.0.php
 //
 //  You may elect to redistribute this code under either of these licenses.
 //  ========================================================================
 //
 
 package org.eclipse.jetty.util;
 
 import java.net.URL;
 import java.util.List;
 
 
 
 /* ------------------------------------------------------------ */
TYPE Utilities. Provides various static utiltiy methods for manipulating types and their string representations.

Since:
Jetty 4.1
 
 public class TypeUtil
 {
     private static final Logger LOG = Log.getLogger(TypeUtil.class);
     public static int CR = '\015';
     public static int LF = '\012';
 
     /* ------------------------------------------------------------ */
     private static final HashMap<StringClass<?>> name2Class=new HashMap<StringClass<?>>();
     static
     {
         .put("boolean",...);
         .put("byte",...);
         .put("char",...);
         .put("double",...);
         .put("float",...);
         .put("int",...);
         .put("long",...);
         .put("short",...);
         .put("void",...);
 
         .put("java.lang.Boolean.TYPE",...);
         .put("java.lang.Byte.TYPE",...);
         .put("java.lang.Character.TYPE",...);
         .put("java.lang.Double.TYPE",...);
         .put("java.lang.Float.TYPE",...);
         .put("java.lang.Integer.TYPE",...);
         .put("java.lang.Long.TYPE",...);
         .put("java.lang.Short.TYPE",...);
         .put("java.lang.Void.TYPE",...);
 
         .put("java.lang.Boolean",java.lang.Boolean.class);
         .put("java.lang.Byte",java.lang.Byte.class);
         .put("java.lang.Character",java.lang.Character.class);
         .put("java.lang.Double",java.lang.Double.class);
         .put("java.lang.Float",java.lang.Float.class);
         .put("java.lang.Integer",java.lang.Integer.class);
         .put("java.lang.Long",java.lang.Long.class);
         .put("java.lang.Short",java.lang.Short.class);
 
         .put("Boolean",java.lang.Boolean.class);
         .put("Byte",java.lang.Byte.class);
         .put("Character",java.lang.Character.class);
         .put("Double",java.lang.Double.class);
         .put("Float",java.lang.Float.class);
         .put("Integer",java.lang.Integer.class);
         .put("Long",java.lang.Long.class);
         .put("Short",java.lang.Short.class);
 
         .put(null,...);
         .put("string",java.lang.String.class);
         .put("String",java.lang.String.class);
         .put("java.lang.String",java.lang.String.class);
     }
 
     /* ------------------------------------------------------------ */
    private static final HashMap<Class<?>, Stringclass2Name=new HashMap<Class<?>, String>();
    static
    {
        .put(...,"boolean");
        .put(...,"byte");
        .put(...,"char");
        .put(...,"double");
        .put(...,"float");
        .put(...,"int");
        .put(...,"long");
        .put(...,"short");
        .put(...,"void");
        .put(java.lang.Boolean.class,"java.lang.Boolean");
        .put(java.lang.Byte.class,"java.lang.Byte");
        .put(java.lang.Character.class,"java.lang.Character");
        .put(java.lang.Double.class,"java.lang.Double");
        .put(java.lang.Float.class,"java.lang.Float");
        .put(java.lang.Integer.class,"java.lang.Integer");
        .put(java.lang.Long.class,"java.lang.Long");
        .put(java.lang.Short.class,"java.lang.Short");
        .put(null,"void");
        .put(java.lang.String.class,"java.lang.String");
    }
    /* ------------------------------------------------------------ */
    private static final HashMap<Class<?>, Methodclass2Value=new HashMap<Class<?>, Method>();
    static
    {
        try
        {
            Class<?>[] s ={java.lang.String.class};
            .put(...,
                           java.lang.Boolean.class.getMethod("valueOf",s));
            .put(...,
                           java.lang.Byte.class.getMethod("valueOf",s));
            .put(...,
                           java.lang.Double.class.getMethod("valueOf",s));
            .put(...,
                           java.lang.Float.class.getMethod("valueOf",s));
            .put(...,
                           java.lang.Integer.class.getMethod("valueOf",s));
            .put(...,
                           java.lang.Long.class.getMethod("valueOf",s));
            .put(...,
                           java.lang.Short.class.getMethod("valueOf",s));
            .put(java.lang.Boolean.class,
                           java.lang.Boolean.class.getMethod("valueOf",s));
            .put(java.lang.Byte.class,
                           java.lang.Byte.class.getMethod("valueOf",s));
            .put(java.lang.Double.class,
                           java.lang.Double.class.getMethod("valueOf",s));
            .put(java.lang.Float.class,
                           java.lang.Float.class.getMethod("valueOf",s));
            .put(java.lang.Integer.class,
                           java.lang.Integer.class.getMethod("valueOf",s));
            .put(java.lang.Long.class,
                           java.lang.Long.class.getMethod("valueOf",s));
            .put(java.lang.Short.class,
                           java.lang.Short.class.getMethod("valueOf",s));
        }
        catch(Exception e)
        {
            throw new Error(e);
        }
    }
    /* ------------------------------------------------------------ */
    
Array to List.

Works like java.util.Arrays.asList(java.lang.Object[]), but handles null arrays.

Returns:
a list backed by the array.
    public static <T> List<T> asList(T[] a
    {
        if (a==null)
            return Collections.emptyList();
        return Arrays.asList(a);
    }
    
    /* ------------------------------------------------------------ */
    
Class from a canonical name for a type.

Parameters:
name A class or type name.
Returns:
A class , which may be a primitive TYPE field..
    public static Class<?> fromName(String name)
    {
        return .get(name);
    }
    /* ------------------------------------------------------------ */
    
Canonical name for a type.

Parameters:
type A class , which may be a primitive TYPE field.
Returns:
Canonical name.
    public static String toName(Class<?> type)
    {
        return .get(type);
    }
    /* ------------------------------------------------------------ */
    
Convert String value to instance.

Parameters:
type The class of the instance, which may be a primitive TYPE field.
value The value as a string.
Returns:
The value as an Object.
    public static Object valueOf(Class<?> typeString value)
    {
        try
        {
            if (type.equals(java.lang.String.class))
                return value;
            Method m = .get(type);
            if (m!=null)
                return m.invoke(nullvalue);
            if (type.equals(...) ||
                type.equals(java.lang.Character.class))
                return new Character(value.charAt(0));
            Constructor<?> c = type.getConstructor(java.lang.String.class);
            return c.newInstance(value);
        }
        catch(NoSuchMethodException e)
        {
            // LogSupport.ignore(log,e);
        }
        catch(IllegalAccessException e)
        {
            // LogSupport.ignore(log,e);
        }
        catch(InstantiationException e)
        {
            // LogSupport.ignore(log,e);
        }
        catch(InvocationTargetException e)
        {
            if (e.getTargetException() instanceof Error)
                throw (Error)(e.getTargetException());
            // LogSupport.ignore(log,e);
        }
        return null;
    }
    /* ------------------------------------------------------------ */
    
Convert String value to instance.

Parameters:
type classname or type (eg int)
value The value as a string.
Returns:
The value as an Object.
    public static Object valueOf(String typeString value)
    {
        return valueOf(fromName(type),value);
    }
    /* ------------------------------------------------------------ */
    
Parse an int from a substring. Negative numbers are not handled.

Parameters:
s String
offset Offset within string
length Length of integer or -1 for remainder of string
base base of the integer
Returns:
the parsed integer
Throws:
java.lang.NumberFormatException if the string cannot be parsed
    public static int parseInt(String sint offsetint lengthint base)
        throws NumberFormatException
    {
        int value=0;
        if (length<0)
            length=s.length()-offset;
        for (int i=0;i<length;i++)
        {
            char c=s.charAt(offset+i);
            int digit=c-'0';
            if (digit<0 || digit>=base || digit>=10)
            {
                digit=10+c-'A';
                if (digit<10 || digit>=base)
                    digit=10+c-'a';
            }
            if (digit<0 || digit>=base)
                throw new NumberFormatException(s.substring(offset,offset+length));
            value=value*base+digit;
        }
        return value;
    }
    /* ------------------------------------------------------------ */
    
Parse an int from a byte array of ascii characters. Negative numbers are not handled.

Parameters:
b byte array
offset Offset within string
length Length of integer or -1 for remainder of string
base base of the integer
Returns:
the parsed integer
Throws:
java.lang.NumberFormatException if the array cannot be parsed into an integer
    public static int parseInt(byte[] bint offsetint lengthint base)
        throws NumberFormatException
    {
        int value=0;
        if (length<0)
            length=b.length-offset;
        for (int i=0;i<length;i++)
        {
            char c=(char)(0xff&b[offset+i]);
            int digit=c-'0';
            if (digit<0 || digit>=base || digit>=10)
            {
                digit=10+c-'A';
                if (digit<10 || digit>=base)
                    digit=10+c-'a';
            }
            if (digit<0 || digit>=base)
                throw new NumberFormatException(new String(b,offset,length));
            value=value*base+digit;
        }
        return value;
    }
    /* ------------------------------------------------------------ */
    public static byte[] parseBytes(String sint base)
    {
        byte[] bytes=new byte[s.length()/2];
        for (int i=0;i<s.length();i+=2)
            bytes[i/2]=(byte)TypeUtil.parseInt(s,i,2,base);
        return bytes;
    }
    /* ------------------------------------------------------------ */
    public static String toString(byte[] bytesint base)
    {
        StringBuilder buf = new StringBuilder();
        for (byte b : bytes)
        {
            int bi=0xff&b;
            int c='0'+(bi/base)%base;
            if (c>'9')
                c'a'+(c-'0'-10);
            buf.append((char)c);
            c='0'+bi%base;
            if (c>'9')
                c'a'+(c-'0'-10);
            buf.append((char)c);
        }
        return buf.toString();
    }
    /* ------------------------------------------------------------ */
    

Parameters:
b An ASCII encoded character 0-9 a-f A-F
Returns:
The byte value of the character 0-16.
    public static byte convertHexDigitbyte b )
    {
        if ((b >= '0') && (b <= '9')) return (byte)(b - '0');
        if ((b >= 'a') && (b <= 'f')) return (byte)(b - 'a' + 10);
        if ((b >= 'A') && (b <= 'F')) return (byte)(b - 'A' + 10);
        throw new IllegalArgumentException("!hex:"+Integer.toHexString(0xff&b));
    }
    /* ------------------------------------------------------------ */
    public static void toHex(byte b,Appendable buf)
    {
        try
        {
            int bi=0xff&b;
            int c='0'+(bi/16)%16;
            if (c>'9')
                c'A'+(c-'0'-10);
            buf.append((char)c);
            c='0'+bi%16;
            if (c>'9')
                c'A'+(c-'0'-10);
            buf.append((char)c);
        }
        catch(IOException e)
        {
            throw new RuntimeException(e);
        }
    }
    /* ------------------------------------------------------------ */
    public static String toHexString(byte b)
    {
        return toHexString(new byte[]{b}, 0, 1);
    }
    
    /* ------------------------------------------------------------ */
    public static String toHexString(byte[] b)
    {
        return toHexString(b, 0, b.length);
    }
    /* ------------------------------------------------------------ */
    public static String toHexString(byte[] b,int offset,int length)
    {
        StringBuilder buf = new StringBuilder();
        for (int i=offset;i<offset+length;i++)
        {
            int bi=0xff&b[i];
            int c='0'+(bi/16)%16;
            if (c>'9')
                c'A'+(c-'0'-10);
            buf.append((char)c);
            c='0'+bi%16;
            if (c>'9')
                c'a'+(c-'0'-10);
            buf.append((char)c);
        }
        return buf.toString();
    }
    /* ------------------------------------------------------------ */
    public static byte[] fromHexString(String s)
    {
        if (s.length()%2!=0)
            throw new IllegalArgumentException(s);
        byte[] array = new byte[s.length()/2];
        for (int i=0;i<array.length;i++)
        {
            int b = Integer.parseInt(s.substring(i*2,i*2+2),16);
            array[i]=(byte)(0xff&b);
        }
        return array;
    }
    public static void dump(Class<?> c)
    {
        ..println("Dump: "+c);
        dump(c.getClassLoader());
    }
    public static void dump(ClassLoader cl)
    {
        ..println("Dump Loaders:");
        while(cl!=null)
        {
            ..println("  loader "+cl);
            cl = cl.getParent();
        }
    }
    /* ------------------------------------------------------------ */
    public static byte[] readLine(InputStream inthrows IOException
    {
        byte[] buf = new byte[256];
        int i=0;
        int loops=0;
        int ch=0;
        while (true)
        {
            ch=in.read();
            if (ch<0)
                break;
            loops++;
            // skip a leading LF's
            if (loops==1 && ch==)
                continue;
            if (ch== || ch==)
                break;
            if (i>=buf.length)
            {
                byte[] old_buf=buf;
                buf=new byte[old_buf.length+256];
                System.arraycopy(old_buf, 0, buf, 0, old_buf.length);
            }
            buf[i++]=(byte)ch;
        }
        if (ch==-1 && i==0)
            return null;
        // skip a trailing LF if it exists
        if (ch== && in.available()>=1 && in.markSupported())
        {
            in.mark(1);
            ch=in.read();
            if (ch!=)
                in.reset();
        }
        byte[] old_buf=buf;
        buf=new byte[i];
        System.arraycopy(old_buf, 0, buf, 0, i);
        return buf;
    }
    public static URL jarFor(String className)
    {
        try
        {
            className=className.replace('.','/')+".class";
            // hack to discover jstl libraries
            URL url = Loader.getResource(null,className,false);
            String s=url.toString();
            if (s.startsWith("jar:file:"))
                return new URL(s.substring(4,s.indexOf("!/")));
        }
        catch(Exception e)
        {
            .ignore(e);
        }
        return null;
    }
    
    public static Object call(Class<?> oClassString methodObject objObject[] arg
    {
        // Lets just try all methods for now
        Method[] methods = oClass.getMethods();
        for (int c = 0; methods != null && c < methods.lengthc++)
        {
            if (!methods[c].getName().equals(method))
                continue;
            if (methods[c].getParameterTypes().length != arg.length)
                continue;
            if (Modifier.isStatic(methods[c].getModifiers()) != (obj == null))
                continue;
            if ((obj == null) && methods[c].getDeclaringClass() != oClass)
                continue;
            try
            {
                return methods[c].invoke(obj,arg);
            }
            catch (IllegalAccessException e)
            {
                .ignore(e);
            }
            catch (IllegalArgumentException e)
            {
                .ignore(e);
            }
        }
        throw new NoSuchMethodException(method);
    }
New to GrepCode? Check out our FAQ X