util.java

来自「JGRoups源码」· Java 代码 · 共 2,058 行 · 第 1/5 页

JAVA
2,058
字号
package org.jgroups.util;import org.apache.commons.logging.LogFactory;import org.jgroups.*;import org.jgroups.auth.AuthToken;import org.jgroups.conf.ClassConfigurator;import org.jgroups.protocols.FD;import org.jgroups.protocols.PingHeader;import org.jgroups.protocols.UdpHeader;import org.jgroups.protocols.pbcast.NakAckHeader;import org.jgroups.stack.IpAddress;import javax.management.MBeanServer;import javax.management.MBeanServerFactory;import java.io.*;import java.net.*;import java.nio.ByteBuffer;import java.nio.channels.WritableByteChannel;import java.text.NumberFormat;import java.util.*;import java.util.List;import EDU.oswego.cs.dl.util.concurrent.Sync;/** * Collection of various utility routines that can not be assigned to other classes. * @author Bela Ban * @version $Id: Util.java,v 1.105 2006/10/23 13:42:30 belaban Exp $ */public class Util {    private static final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);    private static  NumberFormat f;    private static Map PRIMITIVE_TYPES=new HashMap(10);    private static final byte TYPE_NULL         =  0;    private static final byte TYPE_STREAMABLE   =  1;    private static final byte TYPE_SERIALIZABLE =  2;    private static final byte TYPE_BOOLEAN      = 10;    private static final byte TYPE_BYTE         = 11;    private static final byte TYPE_CHAR         = 12;    private static final byte TYPE_DOUBLE       = 13;    private static final byte TYPE_FLOAT        = 14;    private static final byte TYPE_INT          = 15;    private static final byte TYPE_LONG         = 16;    private static final byte TYPE_SHORT        = 17;    private static final byte TYPE_STRING       = 18;    // constants    public static final int MAX_PORT=65535; // highest port allocatable    public static final String DIAG_GROUP="DIAG_GROUP-BELA-322649"; // unique    static boolean resolve_dns=false;    static boolean      JGROUPS_COMPAT=false;    /**     * Global thread group to which all (most!) JGroups threads belong     */    private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups threads") {        public void uncaughtException(Thread t, Throwable e) {            LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e);        }    };    public static ThreadGroup getGlobalThreadGroup() {        return GLOBAL_GROUP;    }    static {        /* Trying to get value of resolve_dns. PropertyPermission not granted if        * running in an untrusted environment  with JNLP */        try {            resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue();        }        catch (SecurityException ex){            resolve_dns=false;        }        f=NumberFormat.getNumberInstance();        f.setGroupingUsed(false);        f.setMaximumFractionDigits(2);        try {            String tmp=Util.getProperty(new String[]{Global.MARSHALLING_COMPAT}, null, null, false, "false");            JGROUPS_COMPAT=Boolean.valueOf(tmp).booleanValue();        }        catch (SecurityException ex){        }        PRIMITIVE_TYPES.put(Boolean.class, new Byte(TYPE_BOOLEAN));        PRIMITIVE_TYPES.put(Byte.class, new Byte(TYPE_BYTE));        PRIMITIVE_TYPES.put(Character.class, new Byte(TYPE_CHAR));        PRIMITIVE_TYPES.put(Double.class, new Byte(TYPE_DOUBLE));        PRIMITIVE_TYPES.put(Float.class, new Byte(TYPE_FLOAT));        PRIMITIVE_TYPES.put(Integer.class, new Byte(TYPE_INT));        PRIMITIVE_TYPES.put(Long.class, new Byte(TYPE_LONG));        PRIMITIVE_TYPES.put(Short.class, new Byte(TYPE_SHORT));        PRIMITIVE_TYPES.put(String.class, new Byte(TYPE_STRING));    }    public static void close(InputStream inp) {        if(inp != null)            try {inp.close();} catch(IOException e) {}    }    public static void close(OutputStream out) {        if(out != null) {            try {out.close();} catch(IOException e) {}        }    }    public static void close(Socket s) {        if(s != null) {            try {s.close();} catch(Exception ex) {}        }    }     public static void close(DatagramSocket my_sock) {        if(my_sock != null) {            try {my_sock.close();} catch(Throwable t) {}        }    }    public static boolean acquire(Sync sync) {        try {            sync.acquire();            return true;        }        catch(InterruptedException e) {            return false;        }    }    public static void release(Sync sync) {        if(sync != null) {            try {                sync.release();            }            catch(Throwable t) {            }        }    }    /**     * Creates an object from a byte buffer     */    public static Object objectFromByteBuffer(byte[] buffer) throws Exception {        if(buffer == null) return null;        if(JGROUPS_COMPAT)            return oldObjectFromByteBuffer(buffer);        return objectFromByteBuffer(buffer, 0, buffer.length);    }    public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception {        if(buffer == null) return null;        if(JGROUPS_COMPAT)            return oldObjectFromByteBuffer(buffer, offset, length);        Object retval=null;        InputStream in=null;        ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);        byte b=(byte)in_stream.read();        try {            switch(b) {                case TYPE_NULL:                    return null;                case TYPE_STREAMABLE:                    in=new DataInputStream(in_stream);                    retval=readGenericStreamable((DataInputStream)in);                    break;                case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable                    in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)                    retval=((ContextObjectInputStream)in).readObject();                    break;                case TYPE_BOOLEAN:                    in=new DataInputStream(in_stream);                    retval=Boolean.valueOf(((DataInputStream)in).readBoolean());                    break;                case TYPE_BYTE:                    in=new DataInputStream(in_stream);                    retval=new Byte(((DataInputStream)in).readByte());                    break;                case TYPE_CHAR:                    in=new DataInputStream(in_stream);                    retval=new Character(((DataInputStream)in).readChar());                    break;                case TYPE_DOUBLE:                    in=new DataInputStream(in_stream);                    retval=new Double(((DataInputStream)in).readDouble());                    break;                case TYPE_FLOAT:                    in=new DataInputStream(in_stream);                    retval=new Float(((DataInputStream)in).readFloat());                    break;                case TYPE_INT:                    in=new DataInputStream(in_stream);                    retval=new Integer(((DataInputStream)in).readInt());                    break;                case TYPE_LONG:                    in=new DataInputStream(in_stream);                    retval=new Long(((DataInputStream)in).readLong());                    break;                case TYPE_SHORT:                    in=new DataInputStream(in_stream);                    retval=new Short(((DataInputStream)in).readShort());                    break;                case TYPE_STRING:                    in=new DataInputStream(in_stream);                    retval=((DataInputStream)in).readUTF();                    break;                default:                    throw new IllegalArgumentException("type " + b + " is invalid");            }            return retval;        }        finally {            Util.close(in);        }    }    /**     * Serializes/Streams an object into a byte buffer.     * The object has to implement interface Serializable or Externalizable     * or Streamable.  Only Streamable objects are interoperable w/ jgroups-me     */    public static byte[] objectToByteBuffer(Object obj) throws Exception {        if(JGROUPS_COMPAT)            return oldObjectToByteBuffer(obj);        byte[] result=null;        synchronized(out_stream) {            out_stream.reset();            if(obj == null) {                out_stream.write(TYPE_NULL);                out_stream.flush();                return out_stream.toByteArray();            }            OutputStream out=null;            Byte type;            try {                if(obj instanceof Streamable) {  // use Streamable if we can                    out_stream.write(TYPE_STREAMABLE);                    out=new DataOutputStream(out_stream);                    writeGenericStreamable((Streamable)obj, (DataOutputStream)out);                }                else if((type=(Byte)PRIMITIVE_TYPES.get(obj.getClass())) != null) {                    out_stream.write(type.byteValue());                    out=new DataOutputStream(out_stream);                    switch(type.byteValue()) {                        case TYPE_BOOLEAN:                            ((DataOutputStream)out).writeBoolean(((Boolean)obj).booleanValue());                            break;                        case TYPE_BYTE:                            ((DataOutputStream)out).writeByte(((Byte)obj).byteValue());                            break;                        case TYPE_CHAR:                            ((DataOutputStream)out).writeChar(((Character)obj).charValue());                            break;                        case TYPE_DOUBLE:                            ((DataOutputStream)out).writeDouble(((Double)obj).doubleValue());                            break;                        case TYPE_FLOAT:                            ((DataOutputStream)out).writeFloat(((Float)obj).floatValue());                            break;                        case TYPE_INT:                            ((DataOutputStream)out).writeInt(((Integer)obj).intValue());                            break;                        case TYPE_LONG:                            ((DataOutputStream)out).writeLong(((Long)obj).longValue());                            break;                        case TYPE_SHORT:                            ((DataOutputStream)out).writeShort(((Short)obj).shortValue());                            break;                        case TYPE_STRING:                            ((DataOutputStream)out).writeUTF((String)obj);                            break;                        default:                            throw new IllegalArgumentException("type " + type + " is invalid");                    }                }                else { // will throw an exception if object is not serializable                    out_stream.write(TYPE_SERIALIZABLE);                    out=new ObjectOutputStream(out_stream);                    ((ObjectOutputStream)out).writeObject(obj);                }            }            finally {                Util.close(out);            }            result=out_stream.toByteArray();        }        return result;    }    /** For backward compatibility in JBoss 4.0.2 */    public static Object oldObjectFromByteBuffer(byte[] buffer) throws Exception {        if(buffer == null) return null;        return oldObjectFromByteBuffer(buffer, 0, buffer.length);    }    public static Object oldObjectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception {        if(buffer == null) return null;        Object retval=null;        try {  // to read the object as an Externalizable            ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);            ObjectInputStream in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)            retval=in.readObject();            in.close();        }        catch(StreamCorruptedException sce) {            try {  // is it Streamable?                ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);                DataInputStream in=new DataInputStream(in_stream);                retval=readGenericStreamable(in);                in.close();            }            catch(Exception ee) {                IOException tmp=new IOException("unmarshalling failed");                tmp.initCause(ee);                throw tmp;            }        }        if(retval == null)            return null;        return retval;    }    /**     * Serializes/Streams an object into a byte buffer.     * The object has to implement interface Serializable or Externalizable     * or Streamable.  Only Streamable objects are interoperable w/ jgroups-me     */    public static byte[] oldObjectToByteBuffer(Object obj) throws Exception {        byte[] result=null;        synchronized(out_stream) {            out_stream.reset();            if(obj instanceof Streamable) {  // use Streamable if we can                DataOutputStream out=new DataOutputStream(out_stream);                writeGenericStreamable((Streamable)obj, out);                out.close();            }            else {                ObjectOutputStream out=new ObjectOutputStream(out_stream);                out.writeObject(obj);                out.close();            }            result=out_stream.toByteArray();        }        return result;    }    public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception {        if(buffer == null) return null;        Streamable retval=null;        ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);        DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)        retval=(Streamable)cl.newInstance();        retval.readFrom(in);        in.close();        if(retval == null)            return null;        return retval;    }    public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception {        if(buffer == null) return null;        Streamable retval=null;        ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);        DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)        retval=(Streamable)cl.newInstance();        retval.readFrom(in);        in.close();        if(retval == null)            return null;        return retval;    }    public static byte[] streamableToByteBuffer(Streamable obj) throws Exception {        byte[] result=null;        synchronized(out_stream) {            out_stream.reset();            DataOutputStream out=new DataOutputStream(out_stream);            obj.writeTo(out);            result=out_stream.toByteArray();            out.close();        }        return result;    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?