Package org.jgroups.util
Class Util
java.lang.Object
org.jgroups.util.Util
Collection of various utility routines that can not be assigned to other classes.
- Version:
- $Id: Util.java,v 1.137.2.11.2.2 2009/04/07 09:52:40 belaban Exp $
- Author:
- Bela Ban
-
Field Summary
Fields -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic String
static boolean
all
(Collection c, Object obj) Returns true if all elements of c match objstatic String
array2String
(boolean[] array) static String
array2String
(int[] array) static String
array2String
(long[] array) static String
array2String
(short[] array) static String
array2String
(Object[] array) static Message
byteBufferToMessage
(byte[] buffer, int offset, int length) byteBufferToMessageList
(byte[] buffer, int offset, int length) static void
checkBufferSize
(String buf_name, long val) Verifies that val is invalid input: '<'= max memorystatic boolean
static boolean
static boolean
static void
close
(InputStream inp) static void
close
(OutputStream out) static void
close
(DatagramSocket my_sock) static void
static void
static void
static byte[]
static List
computeFragOffsets
(byte[] buf, int frag_size) static List
computeFragOffsets
(int offset, int length, int frag_size) Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and return them in a list.static void
crash()
static DatagramSocket
createDatagramSocket
(InetAddress addr, int port) Creates a DatagramSocket bound to addr.static MulticastSocket
createMulticastSocket
(int port) static MulticastSocket
createMulticastSocket
(InetAddress mcast_addr, int port, org.apache.commons.logging.Log log) static ServerSocket
createServerSocket
(int start_port) Finds first available port starting at start_port and returns server socketstatic ServerSocket
createServerSocket
(InetAddress bind_addr, int start_port) static View
createView
(Address coord, long id, Address... members) static byte[]
defragmentBuffer
(byte[][] fragments) Concatenates smaller fragments into entire buffers.determineLeftMembers
(Vector<Address> old_mbrs, Vector<Address> new_mbrs) Returns all members that left between 2 views.static void
doubleWrite
(byte[] buf, int offset, int length, OutputStream out) 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).static void
doubleWrite
(byte[] buf, OutputStream out) 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).static String
Debugging method used to dump the content of a protocol queue in a condensed form.static void
dumpStack
(boolean exit) static String
static boolean
fileExists
(String fname) static byte[][]
fragmentBuffer
(byte[] buf, int frag_size) static byte[][]
fragmentBuffer
(byte[] buf, int frag_size, int length) Fragments a byte buffer into smaller fragments of (max.) frag_size.static String
generateList
(Collection c, String separator) static List
<NetworkInterface> static InetAddress
getBindAddress
(Properties props) Returns the address of the interface to use defined by bind_addr and bind_interfacestatic InetAddress
static InetAddress
static ThreadGroup
static String
static int
static MBeanServer
static String
getProperty
(String[] system_props, Properties props, String prop_name, boolean ignore_sysprops, String default_value) Returns a value associated wither with one or more system properties, or found in the props mapstatic String
getProperty
(Protocol prot, String prop_name) static InputStream
getResourceAsStream
(String name, Class clazz) static String
static boolean
static boolean
interruptAndWaitToDie
(Thread t, long timeout) static boolean
static boolean
static int
static Class
Tries to load the class from the current thread's context class loader.static void
static String
mapToString
(Map<? extends Object, ? extends Object> map) static boolean
match
(long[] a1, long[] a2) static boolean
static String
Converts a java.lang.String in to a MD5 hashed Stringstatic String
memStats
(boolean gc) static Buffer
static Buffer
msgListToByteBuffer
(List<Message> xmit_list) Marshalls a list of messages.static Object
objectFromByteBuffer
(byte[] buffer) Creates an object from a byte bufferstatic Object
objectFromByteBuffer
(byte[] buffer, int offset, int length) static byte[]
objectToByteBuffer
(Object obj) Serializes/Streams an object into a byte buffer.static Object
oldObjectFromByteBuffer
(byte[] buffer) For backward compatibility in JBoss 4.0.2static Object
oldObjectFromByteBuffer
(byte[] buffer, int offset, int length) static byte[]
Serializes/Streams an object into a byte buffer.static InetAddress
parseBindAddress
(Properties props, String property) static boolean
parseBoolean
(Properties props, String property, boolean defaultValue) static long[]
Parses comma-delimited longs; e.g., 2000,4000,8000.e.g.static int
parseInt
(Properties props, String property, int defaultValue) static List
<NetworkInterface> static long
parseLong
(Properties props, String property, long defaultValue) parseStringList
(String l, String separator) static Object
pickRandomElement
(Object[] array) static Object
pickRandomElement
(List list) static Vector
pickSubset
(Vector members, double subset_percentage) Selects a random subset of members according to subset_percentage and returns them.static String
static String
print
(List<NetworkInterface> interfaces) static String
printBytes
(double bytes) static String
printBytes
(long bytes) static String
printEvent
(Event evt) static void
printFragments
(byte[][] frags) static <T> String
printListWithDelimiter
(Collection<T> list, String delimiter) static String
static String
printMessage
(Message msg) Tries to read an object from the message's buffer and prints itstatic String
printMethodCall
(Message msg) Tries to read aMethodCall
object from the message's buffer and prints it.static String
printPingRsps
(List<PingRsp> rsps) static String
Use with caution: lots of overheadstatic void
static void
static long
random
(long range) Returns a random value in the range [1 - range]static Address
static Collection
<Address> readAddresses
(DataInputStream in, Class cl) static AuthToken
static byte[]
static Streamable
static Object
static Streamable
readStreamable
(Class clazz, DataInputStream in) static String
static boolean
Checks whether 2 Addresses are on the same hoststatic String
Converts a java.lang.String in to a SHA hashed Stringstatic String
static String
shortName
(InetAddress hostname) static long
size
(Collection addrs) Returns the marshalled size of a Collection of Addresses.static int
static long
static long
static int
sizeOf
(Streamable inst) static void
sleep
(long timeout) Sleep for timeout msecs.static void
sleep
(long msecs, boolean busy_sleep) On most UNIX systems, the minimum sleep time is 10-20ms.static void
sleep
(long timeout, int nanos) static void
sleepRandom
(long timeout) Sleeps between 1 and timeout milliseconds, chosen randomly.static void
sleepRandom
(long floor, long ceiling) Sleeps between floor and ceiling milliseconds, chosen randomlystatic boolean
static boolean
startFlush
(Channel c, int numberOfAttempts, long randomSleepTimeoutFloor, long randomSleepTimeoutCeiling) static boolean
startFlush
(Channel c, List<Address> flushParticipants) static boolean
startFlush
(Channel c, List<Address> flushParticipants, int numberOfAttempts, long randomSleepTimeoutFloor, long randomSleepTimeoutCeiling) static Streamable
streamableFromByteBuffer
(Class cl, byte[] buffer) static Streamable
streamableFromByteBuffer
(Class cl, byte[] buffer, int offset, int length) static byte[]
static String
substituteVariable
(String val) Replaces variables of ${var:default} with System.getProperty(var, default).static boolean
tossWeightedCoin
(double probability) Tosses a coin weighted with probability and returns true or false.static <T> Vector
<T> unmodifiableVector
(Vector<? extends T> v) static void
writeAddress
(Address addr, DataOutputStream out) static void
writeAddresses
(Collection v, DataOutputStream out) Writes a Vector of Addresses.static void
writeAuthToken
(AuthToken token, DataOutputStream out) static void
writeByteBuffer
(byte[] buf, DataOutputStream out) static void
writeFully
(ByteBuffer buf, WritableByteChannel out) 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.static void
writeGenericStreamable
(Streamable obj, DataOutputStream out) static void
writeObject
(Object obj, DataOutputStream out) static void
writeStreamable
(Streamable obj, DataOutputStream out) static void
writeString
(String s, DataOutputStream out)
-
Field Details
-
MAX_PORT
public static final int MAX_PORT- See Also:
-
-
Constructor Details
-
Util
public Util()
-
-
Method Details
-
getGlobalThreadGroup
-
checkBufferSize
Verifies that val is invalid input: '<'= max memory- Parameters:
buf_name
-val
-
-
keyPress
-
close
-
close
-
close
-
close
-
close
-
close
-
objectFromByteBuffer
Creates an object from a byte buffer- Throws:
Exception
-
objectFromByteBuffer
- Throws:
Exception
-
objectToByteBuffer
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- Throws:
Exception
-
oldObjectFromByteBuffer
For backward compatibility in JBoss 4.0.2- Throws:
Exception
-
oldObjectFromByteBuffer
public static Object oldObjectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception - Throws:
Exception
-
oldObjectToByteBuffer
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- Throws:
Exception
-
streamableFromByteBuffer
- Throws:
Exception
-
streamableFromByteBuffer
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception - Throws:
Exception
-
streamableToByteBuffer
- Throws:
Exception
-
collectionToByteBuffer
- Throws:
Exception
-
size
-
writeAuthToken
- Throws:
IOException
-
readAuthToken
public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException -
writeAddress
- Throws:
IOException
-
readAddress
public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException -
writeAddresses
Writes a Vector of Addresses. Can contain 65K addresses at most- Parameters:
v
- A Collectionout
-- Throws:
IOException
-
readAddresses
public static Collection<Address> readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException - Parameters:
in
-cl
- The type of Collection, e.g. Vector.class- Returns:
- Collection of Address objects
- Throws:
IOException
IllegalAccessException
InstantiationException
-
size
Returns the marshalled size of a Collection of Addresses. Assumes elements are of the same type !- Parameters:
addrs
- Collection- Returns:
- long size
-
writeStreamable
- Throws:
IOException
-
readStreamable
public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException -
writeGenericStreamable
- Throws:
IOException
-
readGenericStreamable
- Throws:
IOException
-
writeObject
- Throws:
Exception
-
readObject
- Throws:
Exception
-
writeString
- Throws:
IOException
-
readString
- Throws:
IOException
-
writeByteBuffer
- Throws:
IOException
-
readByteBuffer
- Throws:
IOException
-
messageToByteBuffer
- Throws:
IOException
-
byteBufferToMessage
- Throws:
Exception
-
msgListToByteBuffer
Marshalls a list of messages.- Parameters:
xmit_list
- LinkedList- Returns:
- Buffer
- Throws:
IOException
-
byteBufferToMessageList
public static List<Message> byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception - Throws:
Exception
-
match
-
match
public static boolean match(long[] a1, long[] a2) -
sleep
public static void sleep(long timeout) Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted -
sleep
public static void sleep(long timeout, int nanos) -
sleep
public static void sleep(long msecs, boolean busy_sleep) On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the thread never relinquishes control and therefore the sleep(x) is exactly x ms long. -
random
public static long random(long range) Returns a random value in the range [1 - range] -
sleepRandom
public static void sleepRandom(long timeout) Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 -
sleepRandom
public static void sleepRandom(long floor, long ceiling) Sleeps between floor and ceiling milliseconds, chosen randomly -
tossWeightedCoin
public static boolean tossWeightedCoin(double probability) Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8, chances are that in 80% of all cases, true will be returned and false in 20%. -
getHostname
-
dumpStack
public static void dumpStack(boolean exit) -
dumpThreads
-
interruptAndWaitToDie
-
interruptAndWaitToDie
-
dumpQueue
Debugging method used to dump the content of a protocol queue in a condensed form. Useful to follow the evolution of the queue's content in time. -
printStackTrace
Use with caution: lots of overhead -
getStackTrace
-
print
-
crash
public static void crash() -
printEvent
-
printMessage
Tries to read an object from the message's buffer and prints it -
mapToString
-
printMethodCall
Tries to read aMethodCall
object from the message's buffer and prints it. Returns empty string if object is not a method call -
printThreads
public static void printThreads() -
activeThreads
-
printBytes
-
printBytes
-
fragmentBuffer
public static byte[][] fragmentBuffer(byte[] buf, int frag_size, int length) Fragments a byte buffer into smaller fragments of (max.) frag_size. Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments of 248 bytes each and 1 fragment of 32 bytes.- Returns:
- An array of byte buffers (
byte[]
).
-
fragmentBuffer
public static byte[][] fragmentBuffer(byte[] buf, int frag_size) -
computeFragOffsets
Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and return them in a list. Example:
Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}). This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length of 2 bytes.- Parameters:
frag_size
-- Returns:
- List. A List
of offset/length pairs
-
computeFragOffsets
-
defragmentBuffer
public static byte[] defragmentBuffer(byte[][] fragments) Concatenates smaller fragments into entire buffers.- Parameters:
fragments
- An array of byte buffers (byte[]
)- Returns:
- A byte buffer
-
printFragments
public static void printFragments(byte[][] frags) -
printListWithDelimiter
-
array2String
-
array2String
-
array2String
-
array2String
-
array2String
-
all
Returns true if all elements of c match obj -
isCoordinator
-
pickSubset
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. -
pickRandomElement
-
pickRandomElement
-
createView
-
determineLeftMembers
public static Vector<Address> determineLeftMembers(Vector<Address> old_mbrs, Vector<Address> new_mbrs) Returns all members that left between 2 views. All members that are element of old_mbrs but not element of new_mbrs are returned. -
printMembers
-
printPingRsps
-
doubleWrite
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).- Throws:
Exception
-
doubleWrite
public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception 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).- Throws:
Exception
-
writeFully
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.- Throws:
IOException
-
sizeOf
-
sizeOf
-
sizeOf
-
loadClass
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.- Parameters:
classname
- Desired class.clazz
- Class object used to obtain a class loader if no context class loader is available.- Returns:
- Class, or null on failure.
- Throws:
ClassNotFoundException
-
getResourceAsStream
-
sameHost
Checks whether 2 Addresses are on the same host -
fileExists
-
parseCommaDelimitedLongs
Parses comma-delimited longs; e.g., 2000,4000,8000. Returns array of long, or null. -
parseCommaDelimitedStrings
e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} -
parseStringList
-
parseInt
-
parseLong
-
parseBoolean
-
parseBindAddress
public static InetAddress parseBindAddress(Properties props, String property) throws UnknownHostException - Throws:
UnknownHostException
-
parseInterfaceList
- Parameters:
s
-- Returns:
- List
- Throws:
Exception
-
print
-
shortName
-
shortName
-
startFlush
-
startFlush
-
startFlush
public static boolean startFlush(Channel c, int numberOfAttempts, long randomSleepTimeoutFloor, long randomSleepTimeoutCeiling) -
startFlush
-
createServerSocket
Finds first available port starting at start_port and returns server socket- Throws:
IOException
-
createServerSocket
public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) throws IOException - Throws:
IOException
-
createDatagramSocket
Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use, start_port will be incremented until a socket can be created.- Parameters:
addr
- The InetAddress to which the socket should be bound. If null, the socket will not be bound.port
- The port which the socket should use. If 0, a random port will be used. If > 0, but port is already in use, it will be incremented until an unused port is found, or until MAX_PORT is reached.- Throws:
Exception
-
createMulticastSocket
- Throws:
IOException
-
createMulticastSocket
public static MulticastSocket createMulticastSocket(InetAddress mcast_addr, int port, org.apache.commons.logging.Log log) throws IOException - Throws:
IOException
-
getBindAddress
public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException Returns the address of the interface to use defined by bind_addr and bind_interface- Parameters:
props
-- Returns:
- Throws:
UnknownHostException
SocketException
-
checkForLinux
public static boolean checkForLinux() -
checkForSolaris
public static boolean checkForSolaris() -
checkForWindows
public static boolean checkForWindows() -
prompt
-
getJavaVersion
public static int getJavaVersion() -
unmodifiableVector
-
memStats
-
getFirstNonLoopbackAddress
- Throws:
SocketException
-
getFirstNonLoopbackIPv6Address
- Throws:
SocketException
-
getAllAvailableInterfaces
- Throws:
SocketException
-
getProperty
public static String getProperty(String[] system_props, Properties props, String prop_name, boolean ignore_sysprops, String default_value) Returns a value associated wither with one or more system properties, or found in the props map- Parameters:
system_props
-props
- List of properties read from the configuration fileprop_name
- The name of the property, will be removed from props if foundignore_sysprops
- If true, system properties are not used and the values will only be retrieved from props (not system_props)default_value
- Used to return a default value if the properties or system properties didn't have the value- Returns:
- The value, or null if not found
-
isBindAddressPropertyIgnored
public static boolean isBindAddressPropertyIgnored() -
getMBeanServer
-
getProperty
-
main
- Throws:
Exception
-
generateList
-
substituteVariable
Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns the same string, otherwise a copy of the string with variables substituted- Parameters:
val
-- Returns:
- A string with vars replaced, or the same string if no vars found
-
md5
Converts a java.lang.String in to a MD5 hashed String- Parameters:
source
- the source String- Returns:
- the MD5 hashed version of the string
-
sha
Converts a java.lang.String in to a SHA hashed String- Parameters:
source
- the source String- Returns:
- the MD5 hashed version of the string
-