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.
- Author:
- Bela Ban
-
Nested Class Summary
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected static intprotected static intprotected static floatstatic final int -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic Stringstatic voidstatic booleanall(Collection c, Object obj) Returns true if all elements of c match objstatic Stringarray2String(boolean[] array) static Stringarray2String(int[] array) static Stringarray2String(long[] array) static Stringarray2String(short[] array) static Stringarray2String(Object[] array) static voidassertEquals(Object val1, Object val2) static voidassertEquals(String message, Object val1, Object val2) static voidassertFalse(boolean condition) static voidassertFalse(String message, boolean condition) static voidassertNotNull(Object val) static voidassertNotNull(String message, Object val) static voidassertNull(String message, Object val) static voidassertTrue(boolean condition) static voidassertTrue(String message, boolean condition) static StringattributeNameToMethodName(String attr_name) static voidblockUntilViewsReceived(long timeout, long interval, Channel... channels) Blocks until all channels have the same viewstatic MessagebyteBufferToMessage(byte[] buffer, int offset, int length) byteBufferToMessageList(byte[] buffer, int offset, int length) static booleanstatic booleanstatic booleanstatic booleanstatic booleanstatic booleanstatic voidcheckIfValidAddress(InetAddress bind_addr, String prot_name) static byteclearFlags(byte bits, byte flag) static voidclose(InputStream inp) static voidclose(OutputStream out) static voidclose(DatagramSocket my_sock) static voidstatic voidstatic voidclose(Connection conn) static voidstatic voidstatic byte[]static String[]components(String path, String separator) computeFragOffsets(byte[] buf, int frag_size) 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 voidconnect(Socket sock, SocketAddress dest, int sock_conn_timeout) Utility method.static booleancontainsViewId(Collection<View> views, ViewId vid) static voidcrash()static <K,V> ConcurrentMap <K, V> static <K,V> ConcurrentMap <K, V> createConcurrentMap(int initial_capacity) static <K,V> ConcurrentMap <K, V> createConcurrentMap(int initial_capacity, float load_factor, int concurrency_level) static DatagramSocketcreateDatagramSocket(SocketFactory factory, String service_name, InetAddress addr, int port) Creates a DatagramSocket bound to addr.static <K,V> Map <K, V> static MulticastSocketcreateMulticastSocket(SocketFactory factory, String service_name, InetAddress mcast_addr, int port, Log log) static Addressstatic AddresscreateRandomAddress(String name) static ServerSocketcreateServerSocket(SocketFactory factory, String service_name, int start_port) Finds first available port starting at start_port and returns server socketstatic ServerSocketcreateServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port) static ServerSocketcreateServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port, int end_port) Finds first available port starting at start_port and returns server socket.static Object[][]static ViewcreateView(Address coord, long id, Address... members) static byte[]defragmentBuffer(byte[][] fragments) Concatenates smaller fragments into entire buffers.determineLeftMembers(List<Address> old_mbrs, List<Address> new_mbrs) Returns all members that left between 2 views.static Collection<Address> determineMergeCoords(Map<Address, View> map) This is the same or a subset ofdetermineMergeParticipants(java.util.Map)and contains only members which are currently sub-partition coordinators.static Collection<Address> Determines the members which take part in a merge.determineNewMembers(List<Address> old_mbrs, List<Address> new_mbrs) Returns the members which joined between 2 subsequent viewsstatic intReads and discards all characters from the input stream until a \r\n or EOF is encounteredstatic voiddoubleWrite(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 voiddoubleWrite(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 StringDebugging method used to dump the content of a protocol queue in a condensed form.static voiddumpStack(boolean exit) static Stringstatic booleanfileExists(String fname) static Stringformat(double value) 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 StringgenerateList(Collection c, String separator) static Stringstatic InetAddressgetAddress(NetworkInterface intf, Util.AddressScope scope) Returns the first address on the given interface on the current host, which satisfies scopestatic InetAddressgetAddress(Util.AddressScope scope) Returns the first address on any interface of the current host, which satisfies scopestatic Collection<InetAddress> static List<NetworkInterface> static Field[]getAllDeclaredFields(Class clazz) static Field[]getAllDeclaredFieldsWithAnnotations(Class clazz, Class<? extends Annotation>... annotations) static Method[]getAllDeclaredMethods(Class clazz) static Method[]getAllDeclaredMethodsWithAnnotations(Class clazz, Class<? extends Annotation>... annotations) static InetAddressgetBindAddress(Properties props) Returns the address of the interface to use defined by bind_addr and bind_interfacestatic Fieldstatic ThreadGroupstatic Stringstatic StackTypestatic InetAddressgetLocalhost(StackType ip_version) IP related utilitiesstatic MBeanServerstatic InetAddressReturns the first non-loopback address on any interface on the current host.static Stringstatic StringgetProperty(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 intstatic InputStreamgetResourceAsStream(String name, Class clazz) static shortstatic SCOPE.ScopeHeadergetScopeHeader(Message msg) static Stringstatic shortstatic booleaninterfaceHasIPAddresses(NetworkInterface intf, StackType ip_version) A function to check if an interface supports an IP version (i.e has addresses defined for that IP version).static booleanstatic booleaninterruptAndWaitToDie(Thread t, long timeout) static booleanstatic booleanstatic booleanisCoordinator(View view, Address local_addr) static booleanisFlagSet(byte bits, byte flag) static booleanisStackAvailable(boolean ipv4) static intleftMembers(Collection<Address> old_list, Collection<Address> new_list) leftMembers(View one, View two) Returns a list of members which left from view one to twostatic ClassTries to load the class from the current thread's context class loader.static StringmapToString(Map<? extends Object, ? extends Object> map) static booleanmatch(long[] a1, long[] a2) static booleanstatic StringConverts a java.lang.String in to a MD5 hashed Stringstatic Bufferstatic StringmethodNameToAttributeName(String methodName) static BuffermsgListToByteBuffer(List<Message> xmit_list) Marshalls a list of messages.newMembers(List<Address> old_list, List<Address> new_list) static ObjectobjectFromByteBuffer(byte[] buffer) Creates an object from a byte bufferstatic ObjectobjectFromByteBuffer(byte[] buffer, int offset, int length) static Objectstatic byte[]objectToByteBuffer(Object obj) Serializes/Streams an object into a byte buffer.static voidobjectToStream(Object obj, DataOutputStream out) parseCommaDelimitedHosts(String hosts, int port_range) Input is "daddy[8880],sindhu[8880],camille[5555].static List<InetSocketAddress> parseCommaDelimitedHosts2(String hosts, int port_range) Input is "daddy[8880],sindhu[8880],camille[5555].static long[]Parses comma-delimited longs; e.g., 2000,4000,8000.e.g.static List<NetworkInterface> static Stringstatic StringparseString(DataInputStream in, boolean break_on_newline) static StringparseString(ByteBuffer buf) static StringparseString(ByteBuffer buf, boolean discard_whitespace) parseStringList(String l, String separator) static <T> TReturns the object next to element in liststatic <T> List<T> Returns the next min(N,list.size()) elements after objstatic ObjectpickRandomElement(Object[] array) static ObjectpickRandomElement(List list) pickSubset(Vector<Address> members, double subset_percentage) Selects a random subset of members according to subset_percentage and returns them.static Stringstatic <T> Stringprint(Collection<T> objs) static Stringprint(List<NetworkInterface> interfaces) static <T> Stringstatic StringprintBytes(double bytes) static StringprintBytes(long bytes) MByte nowadays doesn't mean 1024 * 1024 bytes, but 1 million bytes, see http://en.wikipedia.org/wiki/Megabytestatic StringprintEvent(Event evt) static voidprintFragments(byte[][] frags) static <T> StringprintListWithDelimiter(Collection<T> list, String delimiter) static <T> StringprintMapWithDelimiter(Map<T, T> map, String delimiter) static StringprintMessage(Message msg) Tries to read an object from the message's buffer and prints itstatic StringprintMethodCall(Message msg) Tries to read aMethodCallobject from the message's buffer and prints it.static StringprintPingData(List<PingData> rsps) static StringUse with caution: lots of overheadstatic voidstatic Stringstatic StringprintViews(Collection<View> views) static voidstatic longrandom(long range) Returns a random value in the range [1 - range]static Addressstatic Collection<? extends Address> readAddresses(DataInputStream in, Class cl) static Stringstatic AuthTokenstatic byte[]static doublereadBytesDouble(String input) static intreadBytesInteger(String input) static longreadBytesLong(String input) static Class<?> static doublereadDoubleFromStdin(String message) static Streamablestatic intreadIntFromStdin(String message) static StringreadLine(InputStream in) Reads a line of text.static longreadLongFromStdin(String message) static intreadNewLine(ByteBuffer buf) static Objectstatic StreamablereadStreamable(Class clazz, DataInputStream in) static Stringstatic StringreadStringFromStdin(String message) static Viewstatic voidregisterChannel(JChannel channel, String name) static StringreplaceProperties(String string, Properties props) Go through the input string and replace any occurance of ${p} with the props.getProperty(p) value.static voidrunAsync(Runnable task, ThreadFactory factory, ThreadGroup group, String thread_name) Runs a task on a separate threadstatic booleanChecks whether 2 Addresses are on the same hoststatic booleansameViewId(ViewId one, ViewId two) static bytesetFlag(byte bits, byte flag) static voidstatic StringConverts a java.lang.String in to a SHA hashed Stringstatic Stringstatic StringshortName(InetAddress hostname) static voidDrops messages to/from other members and then closes the channel.static longsize(Collection<? extends Address> addrs) Returns the marshalled size of a Collection of Addresses.static intstatic intstatic longstatic longstatic intsizeOf(Streamable inst) static voidsleep(long timeout) Sleep for timeout msecs.static voidsleep(long msecs, boolean busy_sleep) On most UNIX systems, the minimum sleep time is 10-20ms.static voidsleep(long timeout, int nanos) static voidsleepRandom(long timeout) Sleeps between 1 and timeout milliseconds, chosen randomly.static voidsleepRandom(long floor, long ceiling) Sleeps between floor and ceiling milliseconds, chosen randomlystatic booleanstatic booleanstartFlush(Channel c, int numberOfAttempts, long randomSleepTimeoutFloor, long randomSleepTimeoutCeiling) static booleanstartFlush(Channel c, List<Address> flushParticipants) static booleanstartFlush(Channel c, List<Address> flushParticipants, int numberOfAttempts, long randomSleepTimeoutFloor, long randomSleepTimeoutCeiling) static StreamablestreamableFromByteBuffer(Class cl, byte[] buffer) static StreamablestreamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) static byte[]static StringsubstituteVariable(String val) Replaces variables of ${var:default} with System.getProperty(var, default).static booleantossWeightedCoin(double probability) Tosses a coin weighted with probability and returns true or false.static <T> Vector<T> unmodifiableVector(Vector<? extends T> v) static InetAddressvalidateBindAddressFromInterface(InetAddress bind_addr, String bind_interface_str) Method used by PropertyConverters.BindInterface to check that a bind_address is consistent with a specified interface Idea: 1.static voidwriteAddress(Address addr, DataOutputStream out) static voidwriteAddresses(Collection<? extends Address> v, DataOutputStream out) Writes a Vector of Addresses.static voidwriteAsciiString(String str, DataOutputStream out) static voidwriteAuthToken(AuthToken token, DataOutputStream out) static voidwriteByteBuffer(byte[] buf, int offset, int length, DataOutputStream out) static voidwriteByteBuffer(byte[] buf, DataOutputStream out) static voidwriteClass(Class<?> classObject, DataOutputStream out) static voidwriteFully(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 voidwriteGenericStreamable(Streamable obj, DataOutputStream out) static voidwriteObject(Object obj, DataOutputStream out) static voidwriteStreamable(Streamable obj, DataOutputStream out) static voidwriteString(String s, DataOutputStream out) static voidwriteString(ByteBuffer buf, String s) static voidwriteView(View view, DataOutputStream out)
-
Field Details
-
MAX_PORT
public static final int MAX_PORT- See Also:
-
CCHM_INITIAL_CAPACITY
protected static int CCHM_INITIAL_CAPACITY -
CCHM_LOAD_FACTOR
protected static float CCHM_LOAD_FACTOR -
CCHM_CONCURRENCY_LEVEL
protected static int CCHM_CONCURRENCY_LEVEL
-
-
Constructor Details
-
Util
public Util()
-
-
Method Details
-
getGlobalThreadGroup
-
assertTrue
public static void assertTrue(boolean condition) -
assertTrue
-
assertFalse
public static void assertFalse(boolean condition) -
assertFalse
-
assertEquals
-
assertEquals
-
assertNotNull
-
assertNotNull
-
assertNull
-
blockUntilViewsReceived
public static void blockUntilViewsReceived(long timeout, long interval, Channel... channels) throws TimeoutException Blocks until all channels have the same view- Parameters:
timeout- How long to wait (max in ms)interval- Check every interval mschannels- The channels which should form the view. The expected view size is channels.length. Must be non-null- Throws:
TimeoutException
-
addFlush
-
setScope
-
getScope
-
getScopeHeader
-
connect
public static void connect(Socket sock, SocketAddress dest, int sock_conn_timeout) throws IOException Utility method. If the dest address is IPv6, convert scoped link-local addrs into unscoped ones- Parameters:
sock-dest-sock_conn_timeout-- Throws:
IOException
-
close
-
close
-
close
-
close
-
close
-
close
-
close
-
close
-
shutdown
Drops messages to/from other members and then closes the channel. Note that this member won't get excluded from the view until failure detection has kicked in and the new coord installed the new view- Throws:
Exception
-
setFlag
public static byte setFlag(byte bits, byte flag) -
isFlagSet
public static boolean isFlagSet(byte bits, byte flag) -
clearFlags
public static byte clearFlags(byte bits, byte flag) -
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.- Throws:
Exception
-
objectToStream
- Throws:
Exception
-
objectFromStream
- 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
-
writeAuthToken
- Throws:
IOException
-
readAuthToken
public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException -
writeView
- Throws:
IOException
-
readView
public static View readView(DataInputStream in) throws IOException, InstantiationException, IllegalAccessException -
writeAddress
- Throws:
IOException
-
readAddress
public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException -
size
-
size
-
writeAddresses
public static void writeAddresses(Collection<? extends Address> v, DataOutputStream out) throws IOException Writes a Vector of Addresses. Can contain 65K addresses at most- Parameters:
v- A Collectionout-- Throws:
IOException
-
readAddresses
public static Collection<? extends 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:
IOExceptionIllegalAccessExceptionInstantiationException
-
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
-
writeClass
- Throws:
IOException
-
readClass
- Throws:
IOExceptionClassNotFoundException
-
writeObject
- Throws:
Exception
-
readObject
- Throws:
Exception
-
writeString
- Throws:
IOException
-
readString
- Throws:
IOException
-
writeAsciiString
- Throws:
IOException
-
readAsciiString
- Throws:
IOException
-
parseString
-
parseString
-
readStringFromStdin
- Throws:
Exception
-
readLongFromStdin
- Throws:
Exception
-
readDoubleFromStdin
- Throws:
Exception
-
readIntFromStdin
- Throws:
Exception
-
writeByteBuffer
- Throws:
IOException
-
writeByteBuffer
public static void writeByteBuffer(byte[] buf, int offset, int length, DataOutputStream out) throws IOException - 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
-
sameViewId
-
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. -
keyPress
-
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 aMethodCallobject 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
MByte nowadays doesn't mean 1024 * 1024 bytes, but 1 million bytes, see http://en.wikipedia.org/wiki/Megabyte- Parameters:
bytes-- Returns:
-
printTime
-
format
-
readBytesLong
-
readBytesInteger
-
readBytesDouble
-
printBytes
-
split
-
components
-
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
-
printMapWithDelimiter
-
array2String
-
array2String
-
array2String
-
array2String
-
array2String
-
all
Returns true if all elements of c match obj -
leftMembers
Returns a list of members which left from view one to two- Parameters:
one-two-- Returns:
-
leftMembers
-
newMembers
-
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. -
containsViewId
-
determineMergeParticipants
Determines the members which take part in a merge. The resulting list consists of all merge coordinators plus members outside a merge partition, e.g. for views A={B,A,C}, B={B,C} and C={B,C}, the merge coordinator is B, but the merge participants are B and A.- Parameters:
map-- Returns:
-
determineMergeCoords
This is the same or a subset ofdetermineMergeParticipants(java.util.Map)and contains only members which are currently sub-partition coordinators.- Parameters:
map-- Returns:
-
getRank
-
pickRandomElement
-
pickRandomElement
-
pickNext
Returns the object next to element in list- Type Parameters:
T-- Parameters:
list-obj-- Returns:
-
pickNext
Returns the next min(N,list.size()) elements after obj -
createView
-
createRandomAddress
-
createRandomAddress
-
createTimer
-
determineLeftMembers
Returns all members that left between 2 views. All members that are element of old_mbrs but not element of new_mbrs are returned. -
determineNewMembers
Returns the members which joined between 2 subsequent views- Parameters:
old_mbrs-new_mbrs-- Returns:
-
printViews
-
print
-
print
-
printPingData
-
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
-
getAllDeclaredFields
-
getAllDeclaredFieldsWithAnnotations
public static Field[] getAllDeclaredFieldsWithAnnotations(Class clazz, Class<? extends Annotation>... annotations) -
getAllDeclaredMethods
-
getAllDeclaredMethodsWithAnnotations
public static Method[] getAllDeclaredMethodsWithAnnotations(Class clazz, Class<? extends Annotation>... annotations) -
getField
-
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"} -
parseCommaDelimitedHosts
public static List<IpAddress> parseCommaDelimitedHosts(String hosts, int port_range) throws UnknownHostException Input is "daddy[8880],sindhu[8880],camille[5555]. Returns a list of IpAddresses- Throws:
UnknownHostException
-
parseCommaDelimitedHosts2
public static List<InetSocketAddress> parseCommaDelimitedHosts2(String hosts, int port_range) throws UnknownHostException Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of InetSocketAddress- Throws:
UnknownHostException
-
parseStringList
-
parseString
-
parseString
-
readNewLine
-
discardUntilNewLine
Reads and discards all characters from the input stream until a \r\n or EOF is encountered- Parameters:
in-- Returns:
-
readLine
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.- Returns:
- A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
- Throws:
IOException- If an I/O error occurs
-
writeString
-
parseInterfaceList
- Parameters:
s-- Returns:
- List
- Throws:
Exception
-
print
-
shortName
-
startFlush
-
startFlush
-
startFlush
public static boolean startFlush(Channel c, int numberOfAttempts, long randomSleepTimeoutFloor, long randomSleepTimeoutCeiling) -
startFlush
-
shortName
-
generateLocalName
-
incrCounter
public static short incrCounter() -
createConcurrentMap
public static <K,V> ConcurrentMap<K,V> createConcurrentMap(int initial_capacity, float load_factor, int concurrency_level) -
createConcurrentMap
-
createConcurrentMap
-
createHashMap
-
createServerSocket
public static ServerSocket createServerSocket(SocketFactory factory, String service_name, int start_port) Finds first available port starting at start_port and returns server socket -
createServerSocket
public static ServerSocket createServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port) -
createServerSocket
public static ServerSocket createServerSocket(SocketFactory factory, String service_name, InetAddress bind_addr, int start_port, int end_port) throws Exception Finds first available port starting at start_port and returns server socket. Will not bind to port >end_port. Sets srv_port- Throws:
Exception
-
createDatagramSocket
public static DatagramSocket createDatagramSocket(SocketFactory factory, String service_name, InetAddress addr, int port) throws Exception 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
public static MulticastSocket createMulticastSocket(SocketFactory factory, String service_name, InetAddress mcast_addr, int port, 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:
UnknownHostExceptionSocketException
-
validateBindAddressFromInterface
public static InetAddress validateBindAddressFromInterface(InetAddress bind_addr, String bind_interface_str) throws UnknownHostException, SocketException Method used by PropertyConverters.BindInterface to check that a bind_address is consistent with a specified interface Idea: 1. We are passed a bind_addr, which may be null 2. If non-null, check that bind_addr is on bind_interface - if not, throw exception, otherwise, return the original bind_addr 3. If null, get first non-loopback address on bind_interface, using stack preference to get the IP version. If no non-loopback address, then just return null (i.e. the bind_interface did not influence the decision).- Throws:
UnknownHostExceptionSocketException
-
checkForFreeBSD
public static boolean checkForFreeBSD() -
checkForLinux
public static boolean checkForLinux() -
checkForHp
public static boolean checkForHp() -
checkForSolaris
public static boolean checkForSolaris() -
checkForWindows
public static boolean checkForWindows() -
checkForMac
public static boolean checkForMac() -
prompt
-
unmodifiableVector
-
getLocalhost
IP related utilities- Throws:
UnknownHostException
-
getNonLoopbackAddress
Returns the first non-loopback address on any interface on the current host.- Throws:
SocketException
-
getAddress
Returns the first address on any interface of the current host, which satisfies scope- Throws:
SocketException
-
getAddress
public static InetAddress getAddress(NetworkInterface intf, Util.AddressScope scope) throws SocketException Returns the first address on the given interface on the current host, which satisfies scope- Parameters:
intf- the interface to be checked- Throws:
SocketException
-
interfaceHasIPAddresses
public static boolean interfaceHasIPAddresses(NetworkInterface intf, StackType ip_version) throws SocketException, UnknownHostException A function to check if an interface supports an IP version (i.e has addresses defined for that IP version).- Parameters:
intf-- Returns:
- Throws:
SocketExceptionUnknownHostException
-
getIpStackType
-
isStackAvailable
public static boolean isStackAvailable(boolean ipv4) -
getAllAvailableInterfaces
- Throws:
SocketException
-
getAllAvailableAddresses
-
checkIfValidAddress
- Throws:
Exception
-
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() -
isCoordinator
-
isCoordinator
-
getMBeanServer
-
registerChannel
-
generateList
-
replaceProperties
Go through the input string and replace any occurance of ${p} with the props.getProperty(p) value. If there is no such property p defined, then the ${p} reference will remain unchanged. If the property reference is of the form ${p:v} and there is no such property p, then the default value v will be returned. If the property reference is of the form ${p1,p2} or ${p1,p2:v} then the primary and the secondary properties will be tried in turn, before returning either the unchanged input, or the default value. The property ${/} is replaced with System.getProperty("file.separator") value and the property ${:} is replaced with System.getProperty("path.separator").- Parameters:
string- - the string with possible ${} referencesprops- - the source for ${x} property ref values, null means use System.getProperty()- Returns:
- the input string with all property references replaced if any. If there are no valid references the input string will be returned.
-
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
-
getProperty
-
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
-
methodNameToAttributeName
-
attributeNameToMethodName
-
runAsync
public static void runAsync(Runnable task, ThreadFactory factory, ThreadGroup group, String thread_name) Runs a task on a separate thread- Parameters:
task-factory-group-thread_name-
-