util.java

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

JAVA
2,058
字号
    public static byte[] collectionToByteBuffer(Collection c) throws Exception {        byte[] result=null;        synchronized(out_stream) {            out_stream.reset();            DataOutputStream out=new DataOutputStream(out_stream);            Util.writeAddresses(c, out);            result=out_stream.toByteArray();            out.close();        }        return result;    }    public static int size(Address addr) {        int retval=Global.BYTE_SIZE; // presence byte        if(addr != null)            retval+=addr.size() + Global.BYTE_SIZE; // plus type of address        return retval;    }    public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{        Util.writeString(token.getName(), out);        token.writeTo(out);    }    public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {        try{            String type = Util.readString(in);            Object obj = Class.forName(type).newInstance();            AuthToken token = (AuthToken) obj;            token.readFrom(in);            return token;        }        catch(ClassNotFoundException cnfe){            return null;        }    }    public static void writeAddress(Address addr, DataOutputStream out) throws IOException {        if(addr == null) {            out.writeBoolean(false);            return;        }        out.writeBoolean(true);        if(addr instanceof IpAddress) {            // regular case, we don't need to include class information about the type of Address, e.g. JmsAddress            out.writeBoolean(true);            addr.writeTo(out);        }        else {            out.writeBoolean(false);            writeOtherAddress(addr, out);        }    }    public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {        Address addr=null;        if(in.readBoolean() == false)            return null;        if(in.readBoolean()) {            addr=new IpAddress();            addr.readFrom(in);        }        else {            addr=readOtherAddress(in);        }        return addr;    }    private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {        ClassConfigurator conf=null;        try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {}        int b=in.read();        int magic_number;        String classname;        Class cl=null;        Address addr;        if(b == 1) {            magic_number=in.readInt();            cl=conf.get(magic_number);        }        else {            classname=in.readUTF();            cl=conf.get(classname);        }        addr=(Address)cl.newInstance();        addr.readFrom(in);        return addr;    }    private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException {        ClassConfigurator conf=null;        try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {}        int magic_number=conf != null? conf.getMagicNumber(addr.getClass()) : -1;        // write the class info        if(magic_number == -1) {            out.write(0);            out.writeUTF(addr.getClass().getName());        }        else {            out.write(1);            out.writeInt(magic_number);        }        // write the data itself        addr.writeTo(out);    }    /**     * Writes a Vector of Addresses. Can contain 65K addresses at most     * @param v A Collection<Address>     * @param out     * @throws IOException     */    public static void writeAddresses(Collection v, DataOutputStream out) throws IOException {        if(v == null) {            out.writeShort(-1);            return;        }        out.writeShort(v.size());        Address addr;        for(Iterator it=v.iterator(); it.hasNext();) {            addr=(Address)it.next();            Util.writeAddress(addr, out);        }    }    /**     *     * @param in     * @param cl The type of Collection, e.g. Vector.class     * @return Collection of Address objects     * @throws IOException     * @throws IllegalAccessException     * @throws InstantiationException     */    public static Collection readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException {        short length=in.readShort();        if(length < 0) return null;        Collection retval=(Collection)cl.newInstance();        Address addr;        for(int i=0; i < length; i++) {            addr=Util.readAddress(in);            retval.add(addr);        }        return retval;    }    /**     * Returns the marshalled size of a Collection of Addresses.     * <em>Assumes elements are of the same type !</em>     * @param addrs Collection<Address>     * @return long size     */    public static long size(Collection addrs) {        int retval=Global.SHORT_SIZE; // number of elements        if(addrs != null && addrs.size() > 0) {            Address addr=(Address)addrs.iterator().next();            retval+=size(addr) * addrs.size();        }        return retval;    }    public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException {        if(obj == null) {            out.writeBoolean(false);            return;        }        out.writeBoolean(true);        obj.writeTo(out);    }    public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {        Streamable retval=null;        if(in.readBoolean() == false)            return null;        retval=(Streamable)clazz.newInstance();        retval.readFrom(in);        return retval;    }    public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException {        int magic_number;        String classname;        if(obj == null) {            out.write(0);            return;        }        try {            out.write(1);            magic_number=ClassConfigurator.getInstance(false).getMagicNumber(obj.getClass());            // write the magic number or the class name            if(magic_number == -1) {                out.write(0);                classname=obj.getClass().getName();                out.writeUTF(classname);            }            else {                out.write(1);                out.writeInt(magic_number);            }            // write the contents            obj.writeTo(out);        }        catch(ChannelException e) {            throw new IOException("failed writing object of type " + obj.getClass() + " to stream: " + e.toString());        }    }    public static Streamable readGenericStreamable(DataInputStream in) throws IOException {        Streamable retval=null;        int b=in.read();        if(b == 0)            return null;        int use_magic_number=in.read(), magic_number;        String classname;        Class clazz;        try {            if(use_magic_number == 1) {                magic_number=in.readInt();                clazz=ClassConfigurator.getInstance(false).get(magic_number);                if (clazz==null) {                   throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found.");                }            }            else {                classname=in.readUTF();                clazz=ClassConfigurator.getInstance(false).get(classname);                if (clazz==null) {                   throw new ClassNotFoundException(classname);                }            }            retval=(Streamable)clazz.newInstance();            retval.readFrom(in);            return retval;        }        catch(Exception ex) {            throw new IOException("failed reading object: " + ex.toString());        }    }    public static void writeObject(Object obj, DataOutputStream out) throws Exception {       if(obj == null || !(obj instanceof Streamable)) {           byte[] buf=objectToByteBuffer(obj);           out.writeShort(buf.length);           out.write(buf, 0, buf.length);       }       else {           out.writeShort(-1);           writeGenericStreamable((Streamable)obj, out);       }    }    public static Object readObject(DataInputStream in) throws Exception {        short len=in.readShort();        Object retval=null;        if(len == -1) {            retval=readGenericStreamable(in);        }        else {            byte[] buf=new byte[len];            in.readFully(buf, 0, len);            retval=objectFromByteBuffer(buf);        }        return retval;    }    public static void writeString(String s, DataOutputStream out) throws IOException {        if(s != null) {            out.write(1);            out.writeUTF(s);        }        else {            out.write(0);        }    }    public static String readString(DataInputStream in) throws IOException {        int b=in.read();        if(b == 1)            return in.readUTF();        return null;    }    public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException {        if(buf != null) {            out.write(1);            out.writeInt(buf.length);            out.write(buf, 0, buf.length);        }        else {            out.write(0);        }    }    public static byte[] readByteBuffer(DataInputStream in) throws IOException {        int b=in.read();        if(b == 1) {            b=in.readInt();            byte[] buf=new byte[b];            in.read(buf, 0, buf.length);            return buf;        }        return null;    }    /**       * Marshalls a list of messages.       * @param xmit_list LinkedList<Message>       * @return Buffer       * @throws IOException       */    public static Buffer msgListToByteBuffer(LinkedList xmit_list) throws IOException {        ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);        DataOutputStream out=new DataOutputStream(output);        Message msg;        Buffer retval=null;        out.writeInt(xmit_list.size());        for(Iterator it=xmit_list.iterator(); it.hasNext();) {            msg=(Message)it.next();            msg.writeTo(out);        }        out.flush();        retval=new Buffer(output.getRawBuffer(), 0, output.size());        out.close();        output.close();        return retval;    }    public static LinkedList byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception {        LinkedList retval=null;        ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length);        DataInputStream in=new DataInputStream(input);        int size=in.readInt();        if(size == 0)            return null;        Message msg;        retval=new LinkedList();        for(int i=0; i < size; i++) {            msg=new Message(false); // don't create headers, readFrom() will do this            msg.readFrom(in);            retval.add(msg);        }        return retval;    }    public static boolean match(Object obj1, Object obj2) {        if(obj1 == null && obj2 == null)            return true;        if(obj1 != null)            return obj1.equals(obj2);        else            return obj2.equals(obj1);    }    public static boolean match(long[] a1, long[] a2) {        if(a1 == null && a2 == null)            return true;        if(a1 == null || a2 == null)            return false;        if(a1 == a2) // identity            return true;        // at this point, a1 != null and a2 != null        if(a1.length != a2.length)            return false;        for(int i=0; i < a1.length; i++) {            if(a1[i] != a2[i])                return false;        }        return true;    }    /** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */    public static void sleep(long timeout) {        try {            Thread.sleep(timeout);        }        catch(Throwable e) {        }    }

⌨️ 快捷键说明

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