1 3 package org.jgroups.util; 4 5 import org.apache.commons.logging.Log; 6 import org.apache.commons.logging.LogFactory; 7 import org.jgroups.*; 8 import org.jgroups.protocols.FD; 9 import org.jgroups.protocols.PingHeader; 10 import org.jgroups.protocols.UdpHeader; 11 import org.jgroups.protocols.pbcast.NakAckHeader; 12 import org.jgroups.conf.ClassConfigurator; 13 import org.jgroups.stack.IpAddress; 14 15 import java.io.*; 16 import java.net.BindException ; 17 import java.net.DatagramSocket ; 18 import java.net.InetAddress ; 19 import java.net.ServerSocket ; 20 import java.util.*; 21 22 23 26 public class Util { 27 private static final Object mutex=new Object (); 28 private static final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512); 29 30 protected static final Log log=LogFactory.getLog(Util.class); 31 32 public static final int MAX_PORT=65535; public static final String DIAG_GROUP="DIAG_GROUP-BELA-322649"; static boolean resolve_dns=false; 36 37 static { 38 40 try { 41 resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue(); 42 } 43 catch (SecurityException ex){ 44 resolve_dns=false; 45 } 46 } 47 48 49 public static void closeInputStream(InputStream inp) { 50 if(inp != null) 51 try {inp.close();} catch(IOException e) {} 52 } 53 54 public static void closeOutputStream(OutputStream out) { 55 if(out != null) { 56 try {out.close();} catch(IOException e) {} 57 } 58 } 59 60 61 64 public static Object objectFromByteBuffer(byte[] buffer) throws Exception { 65 synchronized(mutex) { 66 if(buffer == null) return null; 67 Object retval=null; 68 ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer); 69 ObjectInputStream in=new ContextObjectInputStream(in_stream); retval=in.readObject(); 71 in.close(); 72 if(retval == null) 73 return null; 74 return retval; 75 } 76 } 77 78 82 public static byte[] objectToByteBuffer(Object obj) throws Exception { 83 byte[] result=null; 84 synchronized(out_stream) { 85 out_stream.reset(); 86 ObjectOutputStream out=new ObjectOutputStream(out_stream); 87 out.writeObject(obj); 88 result=out_stream.toByteArray(); 89 out.close(); 90 } 91 return result; 92 } 93 94 95 public static void writeAddress(Address addr, DataOutputStream out) throws IOException { 96 if(addr == null) { 97 out.writeBoolean(false); 98 return; 99 } 100 101 out.writeBoolean(true); 102 if(addr instanceof IpAddress) { 103 out.writeBoolean(true); 105 addr.writeTo(out); 106 } 107 else { 108 out.writeBoolean(false); 109 writeOtherAddress(addr, out); 110 } 111 } 112 113 114 115 public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException , InstantiationException { 116 Address addr=null; 117 if(in.readBoolean() == false) 118 return null; 119 if(in.readBoolean()) { 120 addr=new IpAddress(); 121 addr.readFrom(in); 122 } 123 else { 124 addr=readOtherAddress(in); 125 } 126 return addr; 127 } 128 129 private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException , InstantiationException { 130 ClassConfigurator conf=null; 131 try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {} 132 int b=in.read(); 133 int magic_number; 134 String classname; 135 Class cl=null; 136 Address addr; 137 if(b == 1) { 138 magic_number=in.readInt(); 139 cl=conf.get(magic_number); 140 } 141 else { 142 classname=in.readUTF(); 143 cl=conf.get(classname); 144 } 145 addr=(Address)cl.newInstance(); 146 addr.readFrom(in); 147 return addr; 148 } 149 150 private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException { 151 ClassConfigurator conf=null; 152 try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {} 153 int magic_number=conf != null? conf.getMagicNumber(addr.getClass()) : -1; 154 155 if(magic_number == -1) { 157 out.write(0); 158 out.writeUTF(addr.getClass().getName()); 159 } 160 else { 161 out.write(1); 162 out.writeInt(magic_number); 163 } 164 165 addr.writeTo(out); 167 } 168 169 170 public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException { 171 if(obj == null) { 172 out.writeBoolean(false); 173 return; 174 } 175 out.writeBoolean(true); 176 obj.writeTo(out); 177 } 178 179 180 public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException , InstantiationException { 181 Streamable retval=null; 182 if(in.readBoolean() == false) 183 return null; 184 retval=(Streamable)clazz.newInstance(); 185 retval.readFrom(in); 186 return retval; 187 } 188 189 190 public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException { 191 int magic_number; 192 String classname; 193 194 if(obj == null) { 195 out.write(0); 196 return; 197 } 198 199 try { 200 out.write(1); 201 magic_number=ClassConfigurator.getInstance(false).getMagicNumber(obj.getClass()); 202 if(magic_number == -1) { 204 out.write(0); 205 classname=obj.getClass().getName(); 206 out.writeUTF(classname); 207 } 208 else { 209 out.write(1); 210 out.writeInt(magic_number); 211 } 212 213 obj.writeTo(out); 215 } 216 catch(ChannelException e) { 217 throw new IOException("failed writing object of type " + obj.getClass() + " to stream: " + e.toString()); 218 } 219 } 220 221 222 223 public static Streamable readGenericStreamable(DataInputStream in) throws IOException { 224 Streamable retval=null; 225 int b=in.read(); 226 if(b == 0) 227 return null; 228 229 int use_magic_number=in.read(), magic_number; 230 String classname; 231 Class clazz; 232 233 try { 234 if(use_magic_number == 1) { 235 magic_number=in.readInt(); 236 clazz=ClassConfigurator.getInstance(false).get(magic_number); 237 } 238 else { 239 classname=in.readUTF(); 240 clazz=ClassConfigurator.getInstance(false).get(classname); 241 } 242 243 retval=(Streamable)clazz.newInstance(); 244 retval.readFrom(in); 245 return retval; 246 } 247 catch(Exception ex) { 248 throw new IOException("failed reading object: " + ex.toString()); 249 } 250 } 251 252 253 public static void writeString(String s, DataOutputStream out) throws IOException { 254 if(s != null) { 255 out.write(1); 256 out.writeUTF(s); 257 } 258 else { 259 out.write(0); 260 } 261 } 262 263 public static String readString(DataInputStream in) throws IOException { 264 int b=in.read(); 265 if(b == 1) 266 return in.readUTF(); 267 return null; 268 } 269 270 public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException { 271 if(buf != null) { 272 out.write(1); 273 out.writeInt(buf.length); 274 out.write(buf, 0, buf.length); 275 } 276 else { 277 out.write(0); 278 } 279 } 280 281 public static byte[] readByteBuffer(DataInputStream in) throws IOException { 282 int b=in.read(); 283 if(b == 1) { 284 b=in.readInt(); 285 byte[] buf=new byte[b]; 286 in.read(buf, 0, buf.length); 287 return buf; 288 } 289 return null; 290 } 291 292 293 299 public static Buffer msgListToByteBuffer(LinkedList xmit_list) throws IOException { 300 ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512); 301 DataOutputStream out=new DataOutputStream(output); 302 Message msg; 303 Buffer retval=null; 304 305 out.writeInt(xmit_list.size()); 306 for(Iterator it=xmit_list.iterator(); it.hasNext();) { 307 msg=(Message)it.next(); 308 msg.writeTo(out); 309 } 310 out.flush(); 311 retval=new Buffer(output.getRawBuffer(), 0, output.size()); 312 out.close(); 313 output.close(); 314 return retval; 315 } 316 317 public static LinkedList byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception { 318 LinkedList retval=null; 319 ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length); 320 DataInputStream in=new DataInputStream(input); 321 int size=in.readInt(); 322 323 if(size == 0) 324 return null; 325 326 Message msg; 327 retval=new LinkedList(); 328 for(int i=0; i < size; i++) { 329 msg=new Message(); 330 msg.readFrom(in); 331 retval.add(msg); 332 } 333 334 return retval; 335 } 336 337 338 339 340 341 public static boolean match(Object obj1, Object obj2) { 342 if(obj1 == null && obj2 == null) 343 return true; 344 if(obj1 != null) 345 return obj1.equals(obj2); 346 else 347 return obj2.equals(obj1); 348 } 349 350 351 public static boolean match(long[] a1, long[] a2) { 352 if(a1 == null && a2 == null) 353 return true; 354 if(a1 == null || a2 == null) 355 return false; 356 357 if(a1 == a2) return true; 359 360 if(a1.length != a2.length) 362 return false; 363 364 for(int i=0; i < a1.length; i++) { 365 if(a1[i] != a2[i]) 366 return false; 367 } 368 return true; 369 } 370 371 372 public static void sleep(long timeout) { 373 try { 374 Thread.sleep(timeout); 375 } 376 catch(Exception e) { 377 } 378 } 379 380 381 386 public static void sleep(long msecs, boolean busy_sleep) { 387 if(!busy_sleep) { 388 sleep(msecs); 389 return; 390 } 391 392 long start=System.currentTimeMillis(); 393 long stop=start + msecs; 394 395 while(stop > start) { 396 start=System.currentTimeMillis(); 397 } 398 } 399 400 401 402 public static long random(long range) { 403 return (long)((Math.random() * 100000) % range) + 1; 404 } 405 406 407 408 public static void sleepRandom(long timeout) { 409 if(timeout <= 0) { 410 log.error("timeout must be > 0 !"); 411 return; 412 } 413 414 long r=(int)((Math.random() * 100000) % timeout) + 1; 415 sleep(r); 416 } 417 418 419 423 public static boolean tossWeightedCoin(double probability) { 424 long r=random(100); 425 long cutoff=(long)(probability * 100); 426 if(r < cutoff) 427 return true; 428 else 429 return false; 430 } 431 432 433 public static String getHostname() { 434 try { 435 return InetAddress.getLocalHost().getHostName(); 436 } 437 catch(Exception ex) { 438 } 439 return "localhost"; 440 } 441 442 443 public static void dumpStack(boolean exit) { 444 try { 445 throw new Exception ("Dumping stack:"); 446 } 447 catch(Exception e) { 448 e.printStackTrace(); 449 if(exit) 450 System.exit(0); 451 } 452 } 453 454 455 459 public static String dumpQueue(Queue q) { 460 StringBuffer sb=new StringBuffer (); 461 LinkedList values=q.values(); 462 if(values.size() == 0) { 463 sb.append("empty"); 464 } 465 else { 466 for(Iterator it=values.iterator(); it.hasNext();) { 467 Object o=it.next(); 468 String s=null; 469 if(o instanceof Event) { 470 Event event=(Event)o; 471 int type=event.getType(); 472 s=Event.type2String(type); 473 474 if(type == Event.MSG) { 475 s+="["; 476 Message m=(Message)event.getArg(); 477 Map headers=m.getHeaders(); 478 for(Iterator i=headers.keySet().iterator(); i.hasNext();) { 479 Object headerKey=i.next(); 480 Object value=headers.get(headerKey); 481 String headerToString=null; 482 if(value instanceof FD.FdHeader) { 483 headerToString=value.toString(); 484 } 485 else 486 if(value instanceof PingHeader) { 487 headerToString=headerKey + "-"; 488 if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) { 489 headerToString+="GMREQ"; 490 } 491 else 492 if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) { 493 headerToString+="GMRSP"; 494 } 495 else { 496 headerToString+="UNKNOWN"; 497 } 498 } 499 else { 500 headerToString=headerKey + "-" + (value == null ? "null" : value.toString()); 501 } 502 s+=headerToString; 503 504 if(i.hasNext()) { 505 s+=","; 506 } 507 } 508 s+="]"; 509 } 510 } 511 else { 512 s=o.toString(); 513 } 514 sb.append(s).append(" "); 515 } 516 } 517 return sb.toString(); 518 } 519 520 521 524 public static String printStackTrace(Throwable t) { 525 StringWriter s=new StringWriter(); 526 PrintWriter p=new PrintWriter(s); 527 t.printStackTrace(p); 528 return s.toString(); 529 } 530 531 public static String getStackTrace(Throwable t) { 532 return printStackTrace(t); 533 } 534 535 538 public static String printStackTrace() { 539 try { 540 throw new Exception ("Dumping stack:"); 541 } 542 catch(Throwable t) { 543 StringWriter s=new StringWriter(); 544 PrintWriter p=new PrintWriter(s); 545 t.printStackTrace(p); 546 return s.toString(); 547 } 548 } 549 550 public static String print(Throwable t) { 551 return printStackTrace(t); 552 } 553 554 555 public static void crash() { 556 System.exit(-1); 557 } 558 559 560 public static String printEvent(Event evt) { 561 Message msg; 562 563 if(evt.getType() == Event.MSG) { 564 msg=(Message)evt.getArg(); 565 if(msg != null) { 566 if(msg.getLength() > 0) 567 return printMessage(msg); 568 else 569 return msg.printObjectHeaders(); 570 } 571 } 572 return evt.toString(); 573 } 574 575 576 577 public static String printMessage(Message msg) { 578 if(msg == null) 579 return ""; 580 if(msg.getLength() == 0) 581 return null; 582 583 try { 584 return msg.getObject().toString(); 585 } 586 catch(Exception e) { return ""; 588 } 589 590 } 591 592 593 595 public static String printMethodCall(Message msg) { 596 Object obj; 597 if(msg == null) 598 return ""; 599 if(msg.getLength() == 0) 600 return ""; 601 602 try { 603 obj=msg.getObject(); 604 return obj.toString(); 605 } 606 catch(Exception e) { return ""; 608 } 609 610 } 611 612 613 public static void printThreads() { 614 Thread threads[]=new Thread [Thread.activeCount()]; 615 Thread.enumerate(threads); 616 System.out.println("------- Threads -------"); 617 for(int i=0; i < threads.length; i++) { 618 System.out.println("#" + i + ": " + threads[i]); 619 } 620 System.out.println("------- Threads -------\n"); 621 } 622 623 624 public static String activeThreads() { 625 StringBuffer sb=new StringBuffer (); 626 Thread threads[]=new Thread [Thread.activeCount()]; 627 Thread.enumerate(threads); 628 sb.append("------- Threads -------\n"); 629 for(int i=0; i < threads.length; i++) { 630 sb.append("#" + i + ": " + threads[i] + '\n'); 631 } 632 sb.append("------- Threads -------\n"); 633 return sb.toString(); 634 } 635 636 637 643 public static byte[][] fragmentBuffer(byte[] buf, int frag_size, int length) { 644 byte[] retval[]; 645 long total_size=length; 646 int accumulated_size=0; 647 byte[] fragment; 648 int tmp_size=0; 649 int num_frags; 650 int index=0; 651 652 num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1; 653 retval=new byte[num_frags][]; 654 655 while(accumulated_size < total_size) { 656 if(accumulated_size + frag_size <= total_size) 657 tmp_size=frag_size; 658 else 659 tmp_size=(int)(total_size - accumulated_size); 660 fragment=new byte[tmp_size]; 661 System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size); 662 retval[index++]=fragment; 663 accumulated_size+=tmp_size; 664 } 665 return retval; 666 } 667 668 public static byte[][] fragmentBuffer(byte[] buf, int frag_size) { 669 return fragmentBuffer(buf, frag_size, buf.length); 670 } 671 672 673 674 684 public static java.util.List computeFragOffsets(int offset, int length, int frag_size) { 685 java.util.List retval=new ArrayList(); 686 long total_size=length + offset; 687 int index=offset; 688 int tmp_size=0; 689 Range r; 690 691 while(index < total_size) { 692 if(index + frag_size <= total_size) 693 tmp_size=frag_size; 694 else 695 tmp_size=(int)(total_size - index); 696 r=new Range(index, tmp_size); 697 retval.add(r); 698 index+=tmp_size; 699 } 700 return retval; 701 } 702 703 public static java.util.List computeFragOffsets(byte[] buf, int frag_size) { 704 return computeFragOffsets(0, buf.length, frag_size); 705 } 706 707 712 public static byte[] defragmentBuffer(byte[] fragments[]) { 713 int total_length=0; 714 byte[] ret; 715 int index=0; 716 717 if(fragments == null) return null; 718 for(int i=0; i < fragments.length; i++) { 719 if(fragments[i] == null) continue; 720 total_length+=fragments[i].length; 721 } 722 ret=new byte[total_length]; 723 for(int i=0; i < fragments.length; i++) { 724 if(fragments[i] == null) continue; 725 System.arraycopy(fragments[i], 0, ret, index, fragments[i].length); 726 index+=fragments[i].length; 727 } 728 return ret; 729 } 730 731 732 public static void printFragments(byte[] frags[]) { 733 for(int i=0; i < frags.length; i++) 734 System.out.println('\'' + new String (frags[i]) + '\''); 735 } 736 737 738 739 757 795 798 799 800 801 public static String array2String(long[] array) { 802 StringBuffer ret=new StringBuffer ("["); 803 804 if(array != null) { 805 for(int i=0; i < array.length; i++) 806 ret.append(array[i] + " "); 807 } 808 809 ret.append(']'); 810 return ret.toString(); 811 } 812 813 public static String array2String(int[] array) { 814 StringBuffer ret=new StringBuffer ("["); 815 816 if(array != null) { 817 for(int i=0; i < array.length; i++) 818 ret.append(array[i] + " "); 819 } 820 821 ret.append(']'); 822 return ret.toString(); 823 } 824 825 public static String array2String(boolean[] array) { 826 StringBuffer ret=new StringBuffer ("["); 827 828 if(array != null) { 829 for(int i=0; i < array.length; i++) 830 ret.append(array[i] + " "); 831 } 832 ret.append(']'); 833 return ret.toString(); 834 } 835 836 837 841 public static Vector pickSubset(Vector members, double subset_percentage) { 842 Vector ret=new Vector(), tmp_mbrs; 843 int num_mbrs=members.size(), subset_size, index; 844 845 if(num_mbrs == 0) return ret; 846 subset_size=(int)Math.ceil(num_mbrs * subset_percentage); 847 848 tmp_mbrs=(Vector)members.clone(); 849 850 for(int i=subset_size; i > 0 && tmp_mbrs.size() > 0; i--) { 851 index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size()); 852 ret.addElement(tmp_mbrs.elementAt(index)); 853 tmp_mbrs.removeElementAt(index); 854 } 855 856 return ret; 857 } 858 859 860 864 public static Vector determineLeftMembers(Vector old_mbrs, Vector new_mbrs) { 865 Vector retval=new Vector(); 866 Object mbr; 867 868 if(old_mbrs == null || new_mbrs == null) 869 return retval; 870 871 for(int i=0; i < old_mbrs.size(); i++) { 872 mbr=old_mbrs.elementAt(i); 873 if(!new_mbrs.contains(mbr)) 874 retval.addElement(mbr); 875 } 876 877 return retval; 878 } 879 880 881 public static String printMembers(Vector v) { 882 StringBuffer sb=new StringBuffer ("("); 883 boolean first=true; 884 Object el; 885 886 if(v != null) { 887 for(int i=0; i < v.size(); i++) { 888 if(!first) 889 sb.append(", "); 890 else 891 first=false; 892 el=v.elementAt(i); 893 if(el instanceof Address) 894 sb.append(el); 895 else 896 sb.append(el); 897 } 898 } 899 sb.append(')'); 900 return sb.toString(); 901 } 902 903 904 909 public static void doubleWrite(byte[] buf, OutputStream out) throws Exception { 910 if(buf.length > 1) { 911 out.write(buf, 0, 1); 912 out.write(buf, 1, buf.length - 1); 913 } 914 else { 915 out.write(buf, 0, 0); 916 out.write(buf); 917 } 918 } 919 920 921 public static long sizeOf(String classname) { 922 Object inst; 923 byte[] data; 924 925 try { 926 ClassLoader loader=Thread.currentThread().getContextClassLoader(); 929 inst=loader.loadClass(classname).newInstance(); 930 data=Util.objectToByteBuffer(inst); 931 return data.length; 932 } 933 catch(Exception ex) { 934 if(log.isErrorEnabled()) log.error("exception=" + ex); 935 return 0; 936 } 937 } 938 939 940 public static long sizeOf(Object inst) { 941 byte[] data; 942 943 try { 944 data=Util.objectToByteBuffer(inst); 945 return data.length; 946 } 947 catch(Exception ex) { 948 if(log.isErrorEnabled()) log.error("exception+" + ex); 949 return 0; 950 } 951 } 952 953 public static long sizeOf(Streamable inst) { 954 byte[] data; 955 ByteArrayOutputStream output; 956 DataOutputStream out; 957 958 try { 959 output=new ByteArrayOutputStream(); 960 out=new DataOutputStream(output); 961 inst.writeTo(out); 962 out.flush(); 963 data=output.toByteArray(); 964 return data.length; 965 } 966 catch(Exception ex) { 967 if(log.isErrorEnabled()) log.error("exception+" + ex); 968 return 0; 969 } 970 } 971 972 973 974 public static boolean sameHost(Address one, Address two) { 975 InetAddress a, b; 976 String host_a, host_b; 977 978 if(one == null || two == null) return false; 979 if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) { 980 if(log.isErrorEnabled()) log.error("addresses have to be of type IpAddress to be compared"); 981 return false; 982 } 983 984 a=((IpAddress)one).getIpAddress(); 985 b=((IpAddress)two).getIpAddress(); 986 if(a == null || b == null) return false; 987 host_a=a.getHostAddress(); 988 host_b=b.getHostAddress(); 989 990 return host_a.equals(host_b); 992 } 993 994 995 public static void removeFile(String fname) { 996 if(fname == null) return; 997 try { 998 new File(fname).delete(); 999 } 1000 catch(Exception ex) { 1001 if(log.isErrorEnabled()) log.error("exception=" + ex); 1002 } 1003 } 1004 1005 1006 public static boolean fileExists(String fname) { 1007 return (new File(fname)).exists(); 1008 } 1009 1010 1011 1014 public static long[] parseCommaDelimitedLongs(String s) { 1015 StringTokenizer tok; 1016 Vector v=new Vector(); 1017 Long l; 1018 long[] retval=null; 1019 1020 if(s == null) return null; 1021 tok=new StringTokenizer(s, ","); 1022 while(tok.hasMoreTokens()) { 1023 l=new Long (tok.nextToken()); 1024 v.addElement(l); 1025 } 1026 if(v.size() == 0) return null; 1027 retval=new long[v.size()]; 1028 for(int i=0; i < v.size(); i++) 1029 retval[i]=((Long )v.elementAt(i)).longValue(); 1030 return retval; 1031 } 1032 1033 1034 public static java.util.List parseCommaDelimitedStrings(String l) { 1035 java.util.List tmp=new ArrayList(); 1036 StringTokenizer tok=new StringTokenizer(l, ","); 1037 String t; 1038 1039 while(tok.hasMoreTokens()) { 1040 t=tok.nextToken(); 1041 tmp.add(t); 1042 } 1043 1044 return tmp; 1045 } 1046 1047 1048 1049 public static String shortName(String hostname) { 1050 int index; 1051 StringBuffer sb=new StringBuffer (); 1052 1053 if(hostname == null) return null; 1054 1055 index=hostname.indexOf('.'); 1056 if(index > 0 && !Character.isDigit(hostname.charAt(0))) 1057 sb.append(hostname.substring(0, index)); 1058 else 1059 sb.append(hostname); 1060 return sb.toString(); 1061 } 1062 1063 public static String shortName(InetAddress hostname) { 1064 if(hostname == null) return null; 1065 StringBuffer sb=new StringBuffer (); 1066 if(resolve_dns) 1067 sb.append(hostname.getHostName()); 1068 else 1069 sb.append(hostname.getHostAddress()); 1070 return sb.toString(); 1071 } 1072 1073 1074 1075 public static ServerSocket createServerSocket(int start_port) { 1076 ServerSocket ret=null; 1077 1078 while(true) { 1079 try { 1080 ret=new ServerSocket (start_port); 1081 } 1082 catch(BindException bind_ex) { 1083 start_port++; 1084 continue; 1085 } 1086 catch(IOException io_ex) { 1087 if(log.isErrorEnabled()) log.error("exception is " + io_ex); 1088 } 1089 break; 1090 } 1091 return ret; 1092 } 1093 1094 public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) { 1095 ServerSocket ret=null; 1096 1097 while(true) { 1098 try { 1099 ret=new ServerSocket (start_port, 50, bind_addr); 1100 } 1101 catch(BindException bind_ex) { 1102 start_port++; 1103 continue; 1104 } 1105 catch(IOException io_ex) { 1106 if(log.isErrorEnabled()) log.error("exception is " + io_ex); 1107 } 1108 break; 1109 } 1110 return ret; 1111 } 1112 1113 1114 1115 1122 public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception { 1123 DatagramSocket sock=null; 1124 1125 if(addr == null) { 1126 if(port == 0) { 1127 return new DatagramSocket (); 1128 } 1129 else { 1130 while(port < MAX_PORT) { 1131 try { 1132 return new DatagramSocket (port); 1133 } 1134 catch(BindException bind_ex) { port++; 1136 continue; 1137 } 1138 catch(Exception ex) { 1139 throw ex; 1140 } 1141 } 1142 } 1143 } 1144 else { 1145 if(port == 0) port=1024; 1146 while(port < MAX_PORT) { 1147 try { 1148 return new DatagramSocket (port, addr); 1149 } 1150 catch(BindException bind_ex) { port++; 1152 continue; 1153 } 1154 catch(Exception ex) { 1155 throw ex; 1156 } 1157 } 1158 } 1159 return sock; } 1161 1162 1163 public static boolean checkForLinux() { 1164 String os=System.getProperty("os.name"); 1165 return os != null && os.toLowerCase().startsWith("linux") ? true : false; 1166 } 1167 1168 public static boolean checkForSolaris() { 1169 String os=System.getProperty("os.name"); 1170 return os != null && os.toLowerCase().startsWith("sun") ? true : false; 1171 } 1172 1173 public static boolean checkForWindows() { 1174 String os=System.getProperty("os.name"); 1175 return os != null && os.toLowerCase().startsWith("win") ? true : false; 1176 } 1177 1178 public static void prompt(String s) { 1179 System.out.println(s); 1180 System.out.flush(); 1181 try { 1182 while(System.in.available() > 0) 1183 System.in.read(); 1184 System.in.read(); 1185 } 1186 catch(IOException e) { 1187 e.printStackTrace(); 1188 } 1189 } 1190 1191 1192 public static int getJavaVersion() { 1193 String version=System.getProperty("java.version"); 1194 int retval=0; 1195 if(version != null) { 1196 if(version.startsWith("1.2")) 1197 return 12; 1198 if(version.startsWith("1.3")) 1199 return 13; 1200 if(version.startsWith("1.4")) 1201 return 14; 1202 if(version.startsWith("1.5")) 1203 return 15; 1204 if(version.startsWith("5")) 1205 return 15; 1206 if(version.startsWith("1.6")) 1207 return 16; 1208 if(version.startsWith("6")) 1209 return 16; 1210 } 1211 return retval; 1212 } 1213 1214 public static String memStats(boolean gc) { 1215 StringBuffer sb=new StringBuffer (); 1216 Runtime rt=Runtime.getRuntime(); 1217 if(gc) 1218 rt.gc(); 1219 long free_mem, total_mem, used_mem; 1220 free_mem=rt.freeMemory(); 1221 total_mem=rt.totalMemory(); 1222 used_mem=total_mem - free_mem; 1223 sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem); 1224 sb.append("\nTotal mem: ").append(total_mem); 1225 return sb.toString(); 1226 } 1227 1228 1229 1269 1270 public static void main(String args[]) throws Exception { 1271 ClassConfigurator.getInstance(true); 1272 1273 Message msg=new Message(null, new IpAddress("127.0.0.1", 4444), "Bela"); 1274 long size=Util.sizeOf(msg); 1275 System.out.println("size=" + msg.size() + ", streamable size=" + size); 1276 1277 msg.putHeader("belaban", new NakAckHeader((byte)1, 23, 34)); 1278 size=Util.sizeOf(msg); 1279 System.out.println("size=" + msg.size() + ", streamable size=" + size); 1280 1281 msg.putHeader("bla", new UdpHeader("groupname")); 1282 size=Util.sizeOf(msg); 1283 System.out.println("size=" + msg.size() + ", streamable size=" + size); 1284 1285 1286 IpAddress a1=new IpAddress(1234), a2=new IpAddress("127.0.0.1", 3333); 1287 a1.setAdditionalData("Bela".getBytes()); 1288 size=Util.sizeOf(a1); 1289 System.out.println("size=" + a1.size() + ", streamable size of a1=" + size); 1290 size=Util.sizeOf(a2); 1291 System.out.println("size=" + a2.size() + ", streamable size of a2=" + size); 1292 1293 1294 } 1299 1300 1301 1302} 1303 | Popular Tags |