util.java

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

JAVA
2,058
字号
//  	if(timeout <= 0) {//  	    while(true) {//  		try {//  		    obj=channel.peek(0);//  		    if(obj == null || !(obj instanceof View))//  			break;//  		    else {//  			retval=(View)channel.receive(0);//  			num++;//  			if(num >= number_of_views)//  			    break;//  		    }//  		}//  		catch(Exception ex) {//  		    break;//  		}//  	    }//  	}//  	else {//  	    while(timeout > 0) {//  		try {//  		    obj=channel.peek(timeout);//  		    if(obj == null || !(obj instanceof View))//  			break;//  		    else {//  			retval=(View)channel.receive(timeout);//  			num++;//  			if(num >= number_of_views)//  			    break;//  		    }//  		}//  		catch(Exception ex) {//  		    break;//  		}//  		timeout=timeout - (System.currentTimeMillis() - start_time);//  	    }//  	}//  	return retval;//      }    public static String array2String(long[] array) {        StringBuffer ret=new StringBuffer("[");        if(array != null) {            for(int i=0; i < array.length; i++)                ret.append(array[i]).append(" ");        }        ret.append(']');        return ret.toString();    }    public static String array2String(int[] array) {        StringBuffer ret=new StringBuffer("[");        if(array != null) {            for(int i=0; i < array.length; i++)                ret.append(array[i]).append(" ");        }        ret.append(']');        return ret.toString();    }    public static String array2String(boolean[] array) {        StringBuffer ret=new StringBuffer("[");        if(array != null) {            for(int i=0; i < array.length; i++)                ret.append(array[i]).append(" ");        }        ret.append(']');        return ret.toString();    }    public static String array2String(Object[] array) {        StringBuffer ret=new StringBuffer("[");        if(array != null) {            for(int i=0; i < array.length; i++)                ret.append(array[i]).append(" ");        }        ret.append(']');        return ret.toString();    }    /** Returns true if all elements of c match obj */    public static boolean all(Collection c, Object obj) {        for(Iterator iterator=c.iterator(); iterator.hasNext();) {            Object o=iterator.next();            if(!o.equals(obj))                return false;        }        return true;    }    /**     * Selects a random subset of members according to subset_percentage and returns them.     * Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member.     */    public static Vector pickSubset(Vector members, double subset_percentage) {        Vector ret=new Vector(), tmp_mbrs;        int num_mbrs=members.size(), subset_size, index;        if(num_mbrs == 0) return ret;        subset_size=(int)Math.ceil(num_mbrs * subset_percentage);        tmp_mbrs=(Vector)members.clone();        for(int i=subset_size; i > 0 && tmp_mbrs.size() > 0; i--) {            index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size());            ret.addElement(tmp_mbrs.elementAt(index));            tmp_mbrs.removeElementAt(index);        }        return ret;    }    public static Object pickRandomElement(Vector list) {        if(list == null) return null;        int size=list.size();        int index=(int)((Math.random() * size * 10) % size);        return list.get(index);    }    /**     * Returns all members that left between 2 views. All members that are element of old_mbrs but not element of     * new_mbrs are returned.     */    public static Vector determineLeftMembers(Vector old_mbrs, Vector new_mbrs) {        Vector retval=new Vector();        Object mbr;        if(old_mbrs == null || new_mbrs == null)            return retval;        for(int i=0; i < old_mbrs.size(); i++) {            mbr=old_mbrs.elementAt(i);            if(!new_mbrs.contains(mbr))                retval.addElement(mbr);        }        return retval;    }    public static String printMembers(Vector v) {        StringBuffer sb=new StringBuffer("(");        boolean first=true;        Object el;        if(v != null) {            for(int i=0; i < v.size(); i++) {                if(!first)                    sb.append(", ");                else                    first=false;                el=v.elementAt(i);                if(el instanceof Address)                    sb.append(el);                else                    sb.append(el);            }        }        sb.append(')');        return sb.toString();    }    /**     Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,     but before we send data). Two writes ensure that, if the peer closed the connection, the first write     will send the peer from FIN to RST state, and the second will cause a signal (IOException).     */    public static void doubleWrite(byte[] buf, OutputStream out) throws Exception {        if(buf.length > 1) {            out.write(buf, 0, 1);            out.write(buf, 1, buf.length - 1);        }        else {            out.write(buf, 0, 0);            out.write(buf);        }    }    /**     Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,     but before we send data). Two writes ensure that, if the peer closed the connection, the first write     will send the peer from FIN to RST state, and the second will cause a signal (IOException).     */    public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception {        if(length > 1) {            out.write(buf, offset, 1);            out.write(buf, offset+1, length - 1);        }        else {            out.write(buf, offset, 0);            out.write(buf, offset, length);        }    }    /**    * if we were to register for OP_WRITE and send the remaining data on    * readyOps for this channel we have to either block the caller thread or    * queue the message buffers that may arrive while waiting for OP_WRITE.    * Instead of the above approach this method will continuously write to the    * channel until the buffer sent fully.    */    public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException {        int written = 0;        int toWrite = buf.limit();        while (written < toWrite) {            written += out.write(buf);        }    }//    /* double writes are not required.*///	public static void doubleWriteBuffer(//		ByteBuffer buf,//		WritableByteChannel out)//		throws Exception//	{//		if (buf.limit() > 1)//		{//			int actualLimit = buf.limit();//			buf.limit(1);//			writeFully(buf,out);//			buf.limit(actualLimit);//			writeFully(buf,out);//		}//		else//		{//			buf.limit(0);//			writeFully(buf,out);//			buf.limit(1);//			writeFully(buf,out);//		}//	}    public static long sizeOf(String classname) {        Object inst;        byte[] data;        try {            inst=Util.loadClass(classname, null).newInstance();            data=Util.objectToByteBuffer(inst);            return data.length;        }        catch(Exception ex) {            return -1;        }    }    public static long sizeOf(Object inst) {        byte[] data;        try {            data=Util.objectToByteBuffer(inst);            return data.length;        }        catch(Exception ex) {            return -1;        }    }    public static long sizeOf(Streamable inst) {        byte[] data;        ByteArrayOutputStream output;        DataOutputStream out;        try {            output=new ByteArrayOutputStream();            out=new DataOutputStream(output);            inst.writeTo(out);            out.flush();            data=output.toByteArray();            return data.length;        }        catch(Exception ex) {            return -1;        }    }    /**     * Tries to load the class from the current thread's context class loader. If     * not successful, tries to load the class from the current instance.     * @param classname Desired class.     * @param clazz Class object used to obtain a class loader     * 				if no context class loader is available.     * @return Class, or null on failure.     */    public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException {        ClassLoader loader;        try {            loader=Thread.currentThread().getContextClassLoader();            if(loader != null) {                return loader.loadClass(classname);            }        }        catch(Throwable t) {        }        if(clazz != null) {            try {                loader=clazz.getClassLoader();                if(loader != null) {                    return loader.loadClass(classname);                }            }            catch(Throwable t) {            }        }        try {            loader=ClassLoader.getSystemClassLoader();            if(loader != null) {                return loader.loadClass(classname);            }        }        catch(Throwable t) {        }        throw new ClassNotFoundException(classname);    }    public static InputStream getResourceAsStream(String name, Class clazz) {        ClassLoader loader;        try {            loader=Thread.currentThread().getContextClassLoader();            if(loader != null) {                return loader.getResourceAsStream(name);            }        }        catch(Throwable t) {        }        if(clazz != null) {            try {                loader=clazz.getClassLoader();                if(loader != null) {                    return loader.getResourceAsStream(name);                }            }            catch(Throwable t) {            }        }        try {            loader=ClassLoader.getSystemClassLoader();            if(loader != null) {                return loader.getResourceAsStream(name);            }        }        catch(Throwable t) {        }        return null;    }    /** Checks whether 2 Addresses are on the same host */    public static boolean sameHost(Address one, Address two) {        InetAddress a, b;        String host_a, host_b;        if(one == null || two == null) return false;        if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) {            return false;        }        a=((IpAddress)one).getIpAddress();        b=((IpAddress)two).getIpAddress();        if(a == null || b == null) return false;        host_a=a.getHostAddress();        host_b=b.getHostAddress();        // System.out.println("host_a=" + host_a + ", host_b=" + host_b);        return host_a.equals(host_b);    }    public static boolean fileExists(String fname) {        return (new File(fname)).exists();    }    /**     * Parses comma-delimited longs; e.g., 2000,4000,8000.     * Returns array of long, or null.     */    public static long[] parseCommaDelimitedLongs(String s) {        StringTokenizer tok;        Vector v=new Vector();        Long l;        long[] retval=null;        if(s == null) return null;

⌨️ 快捷键说明

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